微信小程序-音频播放-wx.createInnerAudioContext-每次都是重复播放同一条录音
目录
微信小程序-音频播放-wx.createInnerAudioContext() 每次都是重复播放同一条录音
每个项目产品都会让你加埋点,你是愿意花几天一个个加,还是愿意几分钟一个小时加完去喝茶聊天?来试试这520web工具, 高效加埋点,目前我们公司100号前端都在用,因为很好用,所以很自然普及开来了,推荐给大家吧
自己开发所以免费,埋点越多越能节约时间,点两下埋点就加上了,还不会犯错,里面有使用视频,反正免费 😄
转载于
前言
在调试微信小程序音频播放时,刚开始我也是直接复制官方文档的实例:
const innerAudioContext = wx.createInnerAudioContext()
innerAudioContext.autoplay = true
innerAudioContext.src = 'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E061FF02C31F716658E5C81F5594D561F2E88B854E81CAAB7806D5E4F103E55D33C16F3FAC506D1AB172DE8600B37E43FAD&fromtag=46'
innerAudioContext.onPlay(() => {
console.log('开始播放')
})
innerAudioContext.onError((res) => {
console.log(res.errMsg)
console.log(res.errCode)
})
然而此时就出现了,无论按多少下都是重复播放同一条语音的情况!
从 得知,wx.createInnerAudioContext()这个api新建了一个实例之后,需要销毁实例,才能重新new一个实例。所以,我做了以下改动:
const innerAudioContext = wx.createInnerAudioContext()
innerAudioContext.autoplay = true
innerAudioContext.src = res.tempFilePath
innerAudioContext.onPlay(() => {
console.log('开始播放')
})
innerAudioContext.onStop(() => {
console.log('i am onStop')
innerAudioContext.stop()
//播放停止,销毁该实例
innerAudioContext.destroy()
})
innerAudioContext.onEnded(() => {
console.log('i am onEnded')
//播放结束,销毁该实例
innerAudioContext.destroy()
console.log('已执行destory()')
})
innerAudioContext.onError((res) => {
console.log(res.errMsg)
console.log(res.errCode)
innerAudioContext.destroy()
})
最终解决方案
然而!无论我执行多少次,还是播放第一条语音!从我的后台来看,每次返回的语音文件都是不同的,甚至我把服务器上的文件下载到本地,也是不同的!于是我就怀疑它下载过一次这个地址就不再下载了。所以我又换一种写法,在上面加上wx.downloadFile这个api。
wx.downloadFile({
url: 'http://47.106.74.22:8081/voice/download_audio', //仅为示例,并非真实的资源
success: function (res) {
// 只要服务器有响应数据,就会把响应内容写入文件并进入 success 回调,业务需要自行判断是否下载到了想要的内容
if (res.statusCode === 200) {
const innerAudioContext = wx.createInnerAudioContext()
innerAudioContext.autoplay = true
innerAudioContext.src = res.tempFilePath
innerAudioContext.onPlay(() => {
console.log('开始播放')
})
innerAudioContext.onStop(() => {
console.log('i am onStop')
innerAudioContext.stop()
//播放停止,销毁该实例
innerAudioContext.destroy()
})
innerAudioContext.onEnded(() => {
console.log('i am onEnded')
//播放结束,销毁该实例
innerAudioContext.destroy()
console.log('已执行destory()')
})
innerAudioContext.onError((res) => {
console.log(res.errMsg)
console.log(res.errCode)
innerAudioContext.destroy()
})
}
}
})
到这里,终于解决这个问题
注意的是,wx.createInnerAudioContext()无法播放wav文件,于是这里我用的是MP3文件。而wx.playVoice(OBJECT)也无法播放mp3文件。
——————— 本文来自 Himhin 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/a600849155/article/details/81356576?utm_source=copy