目录

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

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

每个项目产品都会让你加埋点,你是愿意花几天一个个加,还是愿意几分钟一个小时加完去喝茶聊天?来试试这520web工具, 高效加埋点,目前我们公司100号前端都在用,因为很好用,所以很自然普及开来了,推荐给大家吧

自己开发所以免费,埋点越多越能节约时间,点两下埋点就加上了,还不会犯错,里面有使用视频,反正免费 😄

转载于

前言

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

 
  1. const innerAudioContext = wx.createInnerAudioContext()
  2. innerAudioContext.autoplay = true
  3. innerAudioContext.src = 'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E061FF02C31F716658E5C81F5594D561F2E88B854E81CAAB7806D5E4F103E55D33C16F3FAC506D1AB172DE8600B37E43FAD&fromtag=46'
  4. innerAudioContext.onPlay(() => {
  5. console.log('开始播放')
  6. })
  7. innerAudioContext.onError((res) => {
  8. console.log(res.errMsg)
  9. console.log(res.errCode)
  10. })

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

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

 
  1. const innerAudioContext = wx.createInnerAudioContext()
  2. innerAudioContext.autoplay = true
  3. innerAudioContext.src = res.tempFilePath
  4. innerAudioContext.onPlay(() => {
  5. console.log('开始播放')
  6. })
  7. innerAudioContext.onStop(() => {
  8. console.log('i am onStop')
  9. innerAudioContext.stop()
  10. //播放停止,销毁该实例
  11. innerAudioContext.destroy()
  12. })
  13. innerAudioContext.onEnded(() => {
  14. console.log('i am onEnded')
  15. //播放结束,销毁该实例
  16. innerAudioContext.destroy()
  17. console.log('已执行destory()')
  18. })
  19. innerAudioContext.onError((res) => {
  20. console.log(res.errMsg)
  21. console.log(res.errCode)
  22. innerAudioContext.destroy()
  23. })

最终解决方案

然而!无论我执行多少次,还是播放第一条语音!从我的后台来看,每次返回的语音文件都是不同的,甚至我把服务器上的文件下载到本地,也是不同的!于是我就怀疑它下载过一次这个地址就不再下载了。所以我又换一种写法,在上面加上wx.downloadFile这个api。

 
  1. wx.downloadFile({
  2. url: 'http://47.106.74.22:8081/voice/download_audio', //仅为示例,并非真实的资源
  3. success: function (res) {
  4. // 只要服务器有响应数据,就会把响应内容写入文件并进入 success 回调,业务需要自行判断是否下载到了想要的内容
  5. if (res.statusCode === 200) {
  6. const innerAudioContext = wx.createInnerAudioContext()
  7. innerAudioContext.autoplay = true
  8. innerAudioContext.src = res.tempFilePath
  9. innerAudioContext.onPlay(() => {
  10. console.log('开始播放')
  11. })
  12. innerAudioContext.onStop(() => {
  13. console.log('i am onStop')
  14. innerAudioContext.stop()
  15. //播放停止,销毁该实例
  16. innerAudioContext.destroy()
  17. })
  18. innerAudioContext.onEnded(() => {
  19. console.log('i am onEnded')
  20. //播放结束,销毁该实例
  21. innerAudioContext.destroy()
  22. console.log('已执行destory()')
  23. })
  24. innerAudioContext.onError((res) => {
  25. console.log(res.errMsg)
  26. console.log(res.errCode)
  27. innerAudioContext.destroy()
  28. })
  29. }
  30. }
  31. })

到这里,终于解决这个问题

注意的是,wx.createInnerAudioContext()无法播放wav文件,于是这里我用的是MP3文件。而wx.playVoice(OBJECT)也无法播放mp3文件。

——————— 本文来自 Himhin 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/a600849155/article/details/81356576?utm_source=copy