WeChat applet development combat (29): control background music

The applet also provides a set of APIs for playing background music. The difference between background music and normal music is that after the background music is played on the current page, it will not stop playing even if you switch to other pages of the current applet. But when the applet exits, the background music will stop playing.

In the applet, it is allowed to play background music, pause background music, stop background music, and randomly locate background music. These 4 functions are realized by the following 4 methods respectively.

  • wx. playBackgroundAudio: play background music
  • wx.pauseBackgroundAudio: Pause background music
  • wx.stopBackgroundAudio: stop background music
  • wx.seekBackgroundAudio: randomly locate background music

In addition, the applet also provides the wx.getBackgroundAudioPlayerState method to get the background music state. These methods all need to set some properties. These contents will be introduced together with the case in this section.

In this section, we will implement a small program that can play background music online. The main interface is shown in Figure 1.

Figure 1 The main interface of playing background music

The control part of this small program is composed of 3 <button> components and one <slider> component. Click the "Play background music" button to play the background music, click the "Pause background music" button to pause the background music, click the "Play background music" button again to continue to play the background music, click the "Stop background music" button, Will stop the background music playback.

By sliding the slider of the <slider> component, it will locate a certain position of the background music, and continue to play the background music from that position. If you test on the simulator, a music controller will appear below the simulator, which can pause and continue playing background music.

The following is the layout code to implement the interface shown in Figure 10-11.

<view style="margin: 30px;">
  <view style="width: 100%;display: flex;">
    <text style="width: 100%;font-size: 60px;margin: 20px; text-align: center; ">{
    
    {formatedPlayTime}}</text>
  </view>
  <slider style="width: 100%" min="0" max="401" step="1" value="{
    
    {playTime}}" bindchange="seek" ></slider>
  <view style="font-size: 28px; width: 100%;display: flex;justify-content: space-between;box-sizing: border-box;">
    <text>00:00</text>
    <text>06:41</text>
  </view>
  <button style="margin-top:20px" bindtap="playBackgroundAudio">播放背景音乐</button>
  <button style="margin-top:20px" bindtap="pauseBackgroundAudio">暂停背景音乐</button>
  <button style="margin-top:20px" bindtap="stopBackgroundAudio">停止背景音乐</button>
</view>

As you can see from this layout code, the drag event of the <slider> component is bound to the seek function, and the 3 buttons are bound to the playBackgroundAudio, pauseBackgroundAudio, and stopBackgroundAudio functions. Since these APIs cannot obtain the duration of the background music, the duration (06:41) is directly specified in the layout code. The max attribute value of the <slider> component is 401. Each scale represents 1 second. The length of 06:41 is exactly 401 seconds.

Below is the complete JavaScript code.

//  背景音乐文件对应的Url(在线播放)
var dataUrl =
'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E061FF02C31F716658E5C81F5594D561F2E88B854E81CAAB7806D5E4F103E55D33C16F3FAC506D1AB172DE8600B37E43FAD&fromtag=46'
 
var app = getApp()
Page({
  data: {
    playTime:0,                        //  <slider>组件当前的位置
    formatedPlayTime: '00:00:00'    //  当前播放的位置
  },
  //播放背景音乐
  playBackgroundAudio: function () {
    var that = this
    wx.playBackgroundAudio({
      dataUrl: dataUrl,
      title: '此时此刻',    
    })
    this.enableInterval()
    app.globalData.backgroundAudioPlaying = true
  },
  //  暂停背景音乐
  pauseBackgroundAudio: function () {
    var that = this
    wx.pauseBackgroundAudio()
    app.globalData.backgroundAudioPlaying = false
  },
  //  停止背景音乐
  stopBackgroundAudio: function () {
    var that = this
    wx.stopBackgroundAudio({
      success: function (res) {
        that.setData({
           playTime: 0,
          formatedPlayTime: '00:00:00'
        })
      }
    })
    app.globalData.backgroundAudioPlaying = false
 
  },
  //  将秒格式的时间格式化为00:00:00形式(时分秒)
  formatTime: function (time) {
    if (typeof time !== 'number' || time < 0) {
      return time
    }
    var hour = parseInt(time / 3600)
    time = time % 3600
    var minute = parseInt(time / 60)
    time = time % 60
    var second = time
 
    return ([hour, minute, second]).map(function (n) {
      n = n.toString()
      return n[1] ? n : '0' + n
    }).join(':')
  },
  //  随机定位背景音乐
  seek: function (e) {
 
    clearInterval(this.updateInterval)
    var that = this   
    wx.seekBackgroundAudio({
      position: e.detail.value,
      complete: function () {
        // 实际会延迟两秒左右才跳过去
        setTimeout(function () {
          that.enableInterval()
        }, 2000)
      }
    })
  },
  //  开启定时器,播放计时
  enableInterval: function () {
    var that = this
update()
//  开启定时器,500毫秒获取一次背景音乐的播放位置
    this.updateInterval = setInterval(update, 500)
 
    function update() {
      wx.getBackgroundAudioPlayerState({
        success: function (res) {
          if (res.currentPosition != undefined) {
that.setData({
  playTime: res.currentPosition,
              formatedPlayTime: that.formatTime(res.currentPosition + 1)
            })
          }
        }
      })
    }
  },
})

We can understand this code from the following points.

  • The wx.playBackgroundAudio method supports online playback of background music, and the Url of the online background music is specified through the dataUrl attribute
  • Here the app.globalData.backgroundAudioPlaying variable is used to save the playback state of the background music. Where app.globalData is the global scope. Since the background music is global to the current applet, it is required that even if the current window playing the background music is closed, the playback state variables are still valid, so these variables that are global to the current applet need to be placed in app.globalData
  • In this example, a standard timer in JavaScript is used to obtain the current position of the background music, and the position of the background music is obtained through the wx.getBackgroundAudioPlayerState method every 500 milliseconds.

If you are interested in this article, you can add teacher Li Ning's WeChat public account (unitymarvel):

Follow the "Geek Origin" official account to get more free technical videos and articles.

Guess you like

Origin blog.csdn.net/nokiaguy/article/details/108414279