当前位置:   article > 正文

【微信小程序开发(八)】音频背景音乐播放问题汇总_音频onended事件失效

音频onended事件失效

提示:以下是本篇文章正文内容

一、全局维护同一个背景音频播放

app.js

wx.$globalData = {
  backgroundAudioManager: wx.getBackgroundAudioManager()
}
  • 1
  • 2
  • 3

二、背景音频播放 src赋值即为播放,且每次从头播放

  playBackGround(){
    // 如果已经赋值了 且 播放地址没有发生改变,只切换播放器的播放状态,即为  继续播放
    if (wx.$globalData.backgroundAudioManager.src != this.data.currentVoice.mp3) {
      wx.$globalData.backgroundAudioManager.title = this.data.currentVoice.name;
      wx.$globalData.backgroundAudioManager.epname = this.data.currentVoice.name;
      wx.$globalData.backgroundAudioManager.singer = this.data.currentVoice.userBy;
      wx.$globalData.backgroundAudioManager.src = this.data.currentVoice.mp3 + '?date=' + Date.now();
      wx.$globalData.backgroundAudioManager.coverImgUrl = 'https://consultation-1251943848.jiandanxinli.com/videos/52b4e6f7-edb3-4e39-8bd8-96791556df6a.png';


      wx.$globalData.backgroundAudioManager.onError(() => {
        wx.$globalData.backgroundAudioManager.stop()
        wx.$globalData.backgroundAudioManager.play()
        console.log("音乐播放错误");
      })
    } else {
      wx.$globalData.backgroundAudioManager.play()
    }
  },
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

3.同步屏幕保护手机系统播放器的播放暂停按钮控制

 //播放开始触发onEnded方法
 wx.$globalData.backgroundAudioManager.onPlay(() => {
   // 可以通过手机屏幕保护的播放器操作播放 OR 暂停 同步状态
   if (this.data.innerAudioContextStatus != '1' && !this.data.handPause) {
     this.playExcute()
   }
 })
 wx.$globalData.backgroundAudioManager.onPause(() => {
 // 可以通过手机屏幕保护的播放器操作播放 OR 暂停 同步状态
   this.pauseExcute()
 })
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

4. 背景音频播放的单曲循环控制

播放结束触发onEnded方法 一旦结束,则 小程序将wx.$globalData.backgroundAudioManager.src立即变为空字符串

//播放结束触发onEnded方法
wx.$globalData.backgroundAudioManager.onEnded(() => {
  // 这里是业务需求有播放结束 重头播放的需求 即为 单曲循环
  this.data.onEnded = true; // 这个标记是为了在
  setTimeout(()=>{
    this.data.onEnded = false
  },2000)
  this.playBackGround();
  console.log("音乐播放结束");
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

在播放控制时间进度的代码中添加如下判断

if (wx.$globalData.backgroundAudioManager.src=='') {
   if (!this.data.onEnded) { // 不是播放结束导致的
     // 背景音频删除操作 初始化播放器状态
     this.restart();
   }
 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

5. 切换音频,处于播放状态才直接播放

changeVoice(voice) {
    this.setData({
      currentVoice: voice.detail
    })
    // 切换时在播放才播放
    if (typeof(wx.$globalData.backgroundAudioManager.src) != 'undefined' && wx.$globalData.backgroundAudioManager.src != '' && !wx.$globalData.backgroundAudioManager.paused) {
      this.playBackGround()
    }
},
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

以上为片段整理,下面将整个页面的代码贴出来,仅供参考

const app = getApp()

Page({
  data: {
    currentIndex: 1,
    startPageY: 0,
    showChangeVoice: false,
    currentVoice: null,
    innerAudioContextStatus: '0'
  },
  //分享
  onShareAppMessage: function (res) {
    let userInfo = wx.getStorageSync("xxx")
    let title = `xxxx~`
    let imageUrl = 'xxx'
    return {
        title: title,
        imageUrl: imageUrl,
        path: `/pages/index/index`,
        success: function (res) {
        }
    }
  },
  formatTime: function (time) {
    var hr = ~~(time / 3600);
    var min = ~~((time % 3600) / 60);
    var sec = time % 60;
    var sec_min = "";
    min = hr * 60 + min;
    if (min < 10) {
      min = '0' + min;
    }
    sec_min += "" + min + ":" + (sec < 10 ? "0" : "");
    sec_min += "" + sec;
    return sec_min;
  },
  onReady() {
  },
  // 滑动手势开始事件
  startEvent: function(event) {
    if (event.changedTouches[0].pageX) {
      this.data.startPageY = event.changedTouches[0].pageY
    } else {
      this.data.startPageY = event.changedTouches[0].y
    }
  },
  // 滑动手势结束事件
  endEvent: function(event) {
    let endPageY = 0
    if (event.changedTouches[0].pageX) {
      endPageY = event.changedTouches[0].pageY
    } else {
      endPageY = event.changedTouches[0].y
    }
    const moveY = endPageY - this.data.startPageY
    if (Math.abs(moveY) < 20) return
    if (moveY > 0) {
      // 上滑
      this.prev()  //这里写你的上滑方法
    } else {
      // 下滑
      this.next()  //这里写你的下滑方法
    }
  },
  prev: function() {
    this.animationTimePre()
  },
  next: function() {
    this.animationTimeNext()
  },
  animationTimePre: function(){
    if (this.data.currentIndex == 0) {
      // wx.showToast({
      //   title: '上面没有了',
      //   icon: 'none'
      // })
      return;
    }
    switch(this.data.currentIndex) {
      case 1 :
        this.setData({
          ['class_'+(this.data.currentIndex-1)]: 'am-top-show-big',
          ['class_'+(this.data.currentIndex)]: 'am-top-show-small',
          ['class_'+(this.data.currentIndex+1)]: 'am-top-show-hide'
        })
        break
      case 5 :
      case 2 :
      case 3 :
      case 4 :
        this.setData({
          ['class_'+(this.data.currentIndex-2)]: 'am-top-show',
          ['class_'+(this.data.currentIndex-1)]: 'am-top-show-big',
          ['class_'+(this.data.currentIndex)]: 'am-top-show-small',
          ['class_'+(this.data.currentIndex+1)]: 'am-top-show-hide'
        })
        break
    }
    // 3个动画分别执行
    this.setData({
      currentIndex: this.data.currentIndex - 1
    })
  },
  animationTimeNext: function(){
    if (this.data.currentIndex == 4) {
      // wx.showToast({
      //   title: '下面没有了',
      //   icon: 'none'
      // })
      return;
    }
    switch(this.data.currentIndex) {
      case 0 :
        this.setData({
          ['class_'+(this.data.currentIndex)]: 'am-bottom-show-small',
          ['class_'+(this.data.currentIndex+1)]: 'am-bottom-show-big',
          ['class_'+(this.data.currentIndex+2)]: 'am-bottom-show'
        })
        break
      case 1 :
      case 2 :
      case 3 :
      case 4 :
        console.log(this.data.currentIndex)
        this.setData({
          ['class_'+(this.data.currentIndex-1)]: 'am-bottom-hide',
          ['class_'+(this.data.currentIndex)]: 'am-bottom-show-small',
          ['class_'+(this.data.currentIndex+1)]: 'am-bottom-show-big',
          ['class_'+(this.data.currentIndex+2)]: 'am-bottom-show'
        })
        break
    }
    // 3个动画分别执行
    this.setData({
      currentIndex: this.data.currentIndex + 1
    })
  },
  playBackGround(){
    if (wx.$globalData.backgroundAudioManager.src != this.data.currentVoice.mp3) {
      wx.$globalData.backgroundAudioManager.title = this.data.currentVoice.name;
      wx.$globalData.backgroundAudioManager.epname = this.data.currentVoice.name;
      wx.$globalData.backgroundAudioManager.singer = this.data.currentVoice.userBy;
      wx.$globalData.backgroundAudioManager.src = this.data.currentVoice.mp3 + '?date=' + Date.now();
      wx.$globalData.backgroundAudioManager.coverImgUrl = 'https://consultation-1251943848.jiandanxinli.com/videos/52b4e6f7-edb3-4e39-8bd8-96791556df6a.png';
      //播放开始触发onEnded方法
      wx.$globalData.backgroundAudioManager.onPlay(() => {
        if (this.data.innerAudioContextStatus != '1' && !this.data.handPause) {
          this.playExcute()
        }
      })
      wx.$globalData.backgroundAudioManager.onPause(() => {
        this.pauseExcute()
      })
      //播放结束触发onEnded方法
      wx.$globalData.backgroundAudioManager.onEnded(() => {
        this.data.onEnded = true;
        setTimeout(()=>{
          this.data.onEnded = false
        },2000)
        this.playBackGround();
        console.log("音乐播放结束");
      })
      wx.$globalData.backgroundAudioManager.onError(() => {
        wx.$globalData.backgroundAudioManager.stop()
        wx.$globalData.backgroundAudioManager.play()
        console.log("音乐播放错误");
      })
    } else {
      wx.$globalData.backgroundAudioManager.play()
    }
  },
  audioPlay () {
    app.subscribeMessage(['Z2CkCq1PNoCh-btDUBRQ_61M1UYfFE2Av3_2yTgKw2M'],()=>{
      // 先来个一个初始动画
      this.setData({
        animationStart: true
      })
      setTimeout(()=>{
        this.audioPlayButton();
      },600)
      
      setTimeout(()=>{
        this.setData({
          animationStart: false
        })
      },1000)
      
    });
    this.clickTrack('startplay',this.data.currentVoice.name)
  },
  audioPlayButtonContinue(){
    this.setData({
      continueAnimation: true
    })
    setTimeout(()=>{
      this.setData({
        continueAnimation: false
      })
      this.audioPlayButton()
    }, 590)
  },
  audioPlayButton(){
    // 设置了 src 之后会自动播放
    this.playBackGround()
    
    this.playExcute()
  },
  testProgress(){
    wx.$globalData.backgroundAudioManager.seek(wx.$globalData.backgroundAudioManager.duration-3)
  },
  testProgress2(){
    let totalTimeChooseMap = [15*60,30*60, 60*60,120*60,180*60];
    this.data.currentProgress =  totalTimeChooseMap[this.data.currentIndex] - 3;
  },
  testProgress3(){
    this.data.currentProgress =  60;
  },
  playExcute(){
    let totalTimeChooseMap = [15*60,30*60, 60*60,120*60,180*60];
    let currentIndex = 1; // 默认30分钟
    this.data.currentProgress = 0;
    // 如果是从0 开始
    if (this.data.innerAudioContextStatus == '0') {
      currentIndex = this.data.currentIndex;
      wx.setStorageSync('concentrate_currentIndex', currentIndex);
      wx.setStorageSync('concentrate_currentProgress', 0);
    } else {
      currentIndex = parseInt(wx.getStorageSync('concentrate_currentIndex'));
      this.data.currentProgress = parseInt(wx.getStorageSync('concentrate_currentProgress'));
    }

    this.setData({
      innerAudioContextStatus: '1'
    })

    if(this.timer) {
      clearInterval(this.timer)
    }
    let time_start_log = Date.now() - 1000;
    this.timer = setInterval(()=> {
      if (this.data.innerAudioContextStatus != '1') {
        clearInterval(this.timer)
        return
      }
      if (parseInt(totalTimeChooseMap[currentIndex]) - parseInt(this.data.currentProgress) <= 0){
        clearInterval(this.timer)
        this.restart()
        return
      }
      if (wx.$globalData.backgroundAudioManager.src=='') {
        if (!this.data.onEnded) { // 不是结束导致的
          // 背景音频删除操作
          this.restart();
        }
      }
      if (Date.now() - time_start_log >= 1000) {
        time_start_log = Date.now()
        this.setData({
          slider_max: totalTimeChooseMap[currentIndex],
          slider_value: this.data.currentProgress,
          current_left: this.formatTime(parseInt(totalTimeChooseMap[currentIndex]) - parseInt(this.data.currentProgress))
        })
        console.log(this.formatTime(parseInt(totalTimeChooseMap[currentIndex]) - parseInt(this.data.currentProgress)))
        this.data.currentProgress++;
        wx.setStorageSync('concentrate_currentProgress', this.data.currentProgress);
      }
    },10)
    // 添加动画
    this.setData({
      circle_class_1: 'am-cicle-1',
      circle_class_2: 'am-cicle-2',
      circle_class_3: 'am-cicle-3',
      circle_class_4: 'am-cicle-4',
      circle_class_5: 'am-cicle-5',
      circle_class_6: 'am-cicle-6'
    })
  },
  audioPause () {
    wx.$globalData.backgroundAudioManager.pause()
    this.data.handPause = true;
    setTimeout(()=>{
      this.data.handPause = false;
    },1000)
    this.pauseExcute()
  },
  pauseExcute(){
    this.setData({
      innerAudioContextStatus: '2'
    })
    this.setData({
      circle_class_1: '',
      circle_class_2: '',
      circle_class_3: '',
      circle_class_4: '',
      circle_class_5: '',
      circle_class_6: '',
    })
    this.clickTrack('pause')
  },
  restart () {
    wx.$globalData.backgroundAudioManager.stop()
    this.setData({
      innerAudioContextStatus: '0'
    })
    this.clickTrack('finish');
    if (this.data.currentProgress >= 60) {
      this.overLink();
    }
  },
  overLink(){
    wx.navigateTo({url: `/pages/result/index?times=${this.data.slider_value}&type=1&content=睡眠`})
  },
  onLoad: function() {
    this.viewTrack()
  },
  onUnload:function(){
    if (this.timer) {
      clearInterval(this.timer)
    }
    wx.$globalData.backgroundAudioManager.stop()
    this.setData({
      innerAudioContextStatus: '0'
    })
  },
  navigateToLink: function(e){
    wx.navigateTo({url: e.currentTarget.dataset['link']})
  },
  changeVoiceShow () {
    this.setData({
      showChangeVoice: true
    })
    this.clickTrack('changebgm')
  },
  closeVoiceShow () {
    this.setData({
      showChangeVoice: false
    })
    this.clickTrack('confirmchangebgm',this.data.currentVoice.name)
  },
  changeVoiceInit(voice) {
    this.setData({
      currentVoice: voice.detail
    })
  },
  changeVoice(voice) {
    this.setData({
      currentVoice: voice.detail
    })
    // 切换时在播放才播放
    if (typeof(wx.$globalData.backgroundAudioManager.src) != 'undefined' && wx.$globalData.backgroundAudioManager.src != '' && !wx.$globalData.backgroundAudioManager.paused) {
      this.playBackGround()
    }
  },
  viewTrack() {
    app.sensors.track('PageBrowser',{
      page_name: 'meditation_focushomepage',
      platform_type: 'miniprogram',
      miniprogramName: 'meditation'
    });
    logstash.track({event:'PageView',url: "pages/sleepList/index",page_id: 'meditation_focushomepage'});
  },
  clickTrack(str,content){
    const trackData = {
      page_name: 'meditation_focushomepage',
      platform_type: 'miniprogram',
      miniprogramName: 'meditation',
      $element_content: str
    }
    if(content){
      trackData.content = content
    }
    app.sensors.track('ButtonClick',trackData);
    logstash.actionEvent({
        action_id: `meditation_focushomepage_${str}`,
        element_content: content?content:str,
        event: "WebClick",
    },{
        page_id: 'meditation_focushomepage'
    });
  }
})

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
  • 333
  • 334
  • 335
  • 336
  • 337
  • 338
  • 339
  • 340
  • 341
  • 342
  • 343
  • 344
  • 345
  • 346
  • 347
  • 348
  • 349
  • 350
  • 351
  • 352
  • 353
  • 354
  • 355
  • 356
  • 357
  • 358
  • 359
  • 360
  • 361
  • 362
  • 363
  • 364
  • 365
  • 366
  • 367
  • 368
  • 369
  • 370
  • 371
  • 372
  • 373
  • 374
  • 375
  • 376
  • 377
  • 378
  • 379
  • 380
  • 381
  • 382
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/473948
推荐阅读
相关标签
  

闽ICP备14008679号