700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 微信小程序-音频播放 每次都是重复播放同一条录音

微信小程序-音频播放 每次都是重复播放同一条录音

时间:2020-08-19 21:49:46

相关推荐

微信小程序-音频播放 每次都是重复播放同一条录音

前言

在调试微信小程序音频播放时,刚开始我也是直接复制官方文档的实例:

const innerAudioContext = wx.createInnerAudioContext()innerAudioContext.autoplay = trueinnerAudioContext.src = 'http://ws.stream./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)})

然而此时就出现了,无论按多少下都是重复播放同一条语音的情况!

从 /qq_39364032/article/details/79742120得知,wx.createInnerAudioContext()这个api新建了一个实例之后,需要销毁实例,才能重新new一个实例。所以,我做了以下改动:

const innerAudioContext = wx.createInnerAudioContext()innerAudioContext.autoplay = trueinnerAudioContext.src = res.tempFilePathinnerAudioContext.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 = trueinnerAudioContext.src = res.tempFilePathinnerAudioContext.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文件。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。