前言

在调试微信小程序音频播放时,刚开始我也是直接复制官方文档的实例:
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) })
然而此时就出现了,无论按多少下都是重复播放同一条语音的情况!

从 https://blog.csdn.net/qq_39364032/article/details/79742120
<https://blog.csdn.net/qq_39364032/article/details/79742120>
 得知,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文件。

 

友情链接
KaDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:[email protected]
QQ群:637538335
关注微信