WeChat applet audio playback failed: TypeError: Cannot read property 'duration' of undefined

Error screenshot

insert image description here
The bottom this.setData() error can be ignored, it is a problem with the value of this

solve

  1. When you need to play and pause functions, you need to put the audio and its src outside the Page.
  2. The two methods audioCtx.onPlay() and audioCtx.onError() cannot be missing, and they need to be placed before the play() method
  3. If {useWebAudioImplement:true} is added in wx.createInnerAudioContext(), remove it.
//需要播放暂停音频功能时,需要将这两个变量放在 Page()上面
let audioCtx=wx.createInnerAudioContext()
audioCtx.src='http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3' //填入你自己的音频链接
Page({
    
    
     data: {
    
    
          isPlay: false,
     },
     playMusic(){
    
    
          audioCtx.onPlay(()=>{
    
    
               console.log("开始播放");
          })
           audioCtx.onError((res)=>{
    
    
             wx.showToast({
    
    
                title: '音乐播放错误',
                icon: 'error',
                duration: 3000
              })
           })
           let isPlay = !this.data.isPlay //控制播放和暂停的变量
           this.setData({
    
    
                isPlay:isPlay
               })
          if(isPlay){
    
    
               audioCtx.play()
               audioCtx.loop = true;
          }else{
    
    
               audioCtx.pause()
          }
     },
     },
     onLoad() {
    
    
          this.playMusic(); //加载完毕,开始播放
     },
});

Guess you like

Origin blog.csdn.net/weixin_51033461/article/details/131704534