微信原生小程序实现音乐播放进度条

时间:2024-03-31 09:27:29

audio标签、progress标签实现音乐播放进度条

HTML5 audio标签、progress标签实现音乐播放及进度条,通过拖动进度条更新播放进度。本次分享以功能实现为主,样式先不考究,见谅。

HTML

  <view class="audio-play">
    <audio src=""></audio>
  </view>
  
  <view>
    <view class="one-column play-it" bindtap="playMusic">
      <view>点击播放</view>
    </view>
    
    <progress class="music-prog" bindtouchmove="setTouchMove" percent="{{musicPercent}}"></progress>
    
    <view class="percent-num">{{musicPercent}}%</view>
  </view>
  1. audio 标签必须写进HTML,只要不设置controls="true"就不会展示出来;
  2. bindtouchmove表示触摸事件;
  3. progress标签通过percent属性设置进度

CSS

.play-it{
  margin-left: 300rpx;
}

.music-prog{
  width: 550rpx;
  height: 10rpx;
  margin: 50rpx 100rpx;
  color: #0099ff;
  background-color: #999;
}

.percent-num{
  margin: -20rpx 0 0 100rpx;
  font-size: 28rpx;
}

JS

  onShow() {
    // 监听音乐播放
    let that = this
    wx.onBackgroundAudioPlay(() => {
      that.timer && clearInterval(that.timer)
      that.timer = setInterval(() => {
        wx.getBackgroundAudioPlayerState({
          success: res => {
            let per = (res.currentPosition/res.duration)*10000
            that.setData({
              musicPercent: Math.round(per)/100 + '',
              duration: res.duration
            })
          }
        })
      }, 1000)
    })

    // 监听背景音频暂停事件
    wx.onBackgroundAudioPause(() => {
      clearInterval(that.timer)
    })

    // 监听背景音频停止事件
    wx.onBackgroundAudioStop(() => {
      clearInterval(that.timer)
    })
  },
  playMusic() {
      
 	 let obj = {
          dataUrl: 'http://p6jceeddp.bkt.clouddn.com/%E5%B0%A4%E9%95%BF%E9%9D%96%20-%20%E6%98%A8%E6%97%A5%E9%9D%92%E7%A9%BA.mp3',
          title: '昨日青空',
          coverImgUrl: '/static/images/avatar.png'
        }
        wx.playBackgroundAudio(obj)
      },
  
  setTouchMove (e) {
    if(e.touches[0].clientY >= 390 && e.touches[0].clientY <= 410) {
      if (e.touches[0].clientX >= 55 && e.touches[0].clientX <= 355) {
        let percent = (e.touches[0].clientX - 55)/300*10000
        this.setData({
          musicPercent: Math.round(percent)/100 + ''
        })
        let current = (this.data.musicPercent/100)*this.data.duration
        wx.seekBackgroundAudio({
          position: current,
          success () {
            console.log('seek', current)
          }
        })
      }
    }
  }

确定进度条的有效区域

横向: e.touches[0].clientX
纵向: e.touches[0].clientY

横向: 55~355
纵向: 390~410

微信原生小程序实现音乐播放进度条

定义触摸事件

获取到的横向进度条位置,计算用户所拖拽到的进度条位置,调用wx.seekBackgroundAudio()设置播放进度