微信小程序音频背景播放

由于微信小程序官方将音频的样式固定死了,往往再工作中和UI设计师设计出来的样式不符,故一般都采用背景音频播放来实现自定义的UI样式的音频播放,即使用官网API提供的BackgroundAudioManager进行操作 也可以去官网https://developers.weixin.qq.com/miniprogram/dev/api/media/background-audio/BackgroundAudioManager.play.html查看详情

第一步,在对应的wxml页面添加如下代码,eg,放在index.wxml中

<view class='audioMeaage'>
        <view bindtap='playAudio1'>
          <image wx:if="{{!audioImg}}" class='playIcom' src='{{palyIcon}}'></image>
          <image wx:else class='playIcom' src='{{pausIcon}}'></image>
        </view>
        <view class='sliderWrap'>
          <view class='audioNames'>{{audioTitle}}</view>
          <view class='progressWrap'>
            <slider class="slider2"
              bindchange="hanle_slider_change" 
              bindtouchstart="handle_slider_move_start" 
              bindtouchend="handle_slider_move_end"
              min="0" 
              block-size="10" 
              max="{{slider_max}}" 
              activeColor="#ffd038"
              block-color="#ffd038"
              backgroundColor="#f2f2f2" 
              value="{{slider_value}}" 
            />
            <view class='proTime'>{{current_process}}/{{total_process}}</view>
          </view>
        </view>
      </view>

第二步,对应的index.js,注意这里的playAudio方法是点击以后从后台获取音频的url和标题等信息的

//获取应用实例
const app = getApp()
const AUDIOMANAGER = getApp().globalData.global_bac_audio_manager.manage
const AUDIO = getApp().globalData.global_bac_audio_manager
Page({
  data: {
    audioImg:false,
    palyIcon: "./../../images/home_img_vedio_play.png",
    pausIcon:"./../../images/home_img_vedio_play2.png",
    audioFlag: false,
    is_moving_slider: false,
    current_process:"",
    slider_value: "",
    total_process: "",
    slider_max: "",
    audioTitle:"",
  },
    playAudio: function(e){
    const item = e.currentTarget.dataset.url
    AUDIOMANAGER.src = item.link_url
    AUDIOMANAGER.title = item.tit // 音频标题

    AUDIO.is_play= true
    //背景音频播放进度更新事件
    const that = this
    that.setData({
      audioFlag: true,
      audioTitle: item.tit,
      audioImg: true
    })
    AUDIOMANAGER.onTimeUpdate(() => {
      if (!that.data.is_moving_slider) {
        that.setData({
          current_process: that.format(AUDIOMANAGER.currentTime),
          slider_value: Math.floor(AUDIOMANAGER.currentTime),
          total_process: that.format(AUDIOMANAGER.duration),
          slider_max: Math.floor(AUDIOMANAGER.duration)
        })
      }
      AUDIO.time = AUDIOMANAGER.currentTime
    })

    // 背景音频播放完毕
    AUDIOMANAGER.onEnded(() => {
        // 单曲循环
        that.setData({
          slider_value: 0,
          current_process: '00:00',
          total_process: that.format(AUDIOMANAGER.duration)
        })
    })
  },
  // 拖动进度条,到指定位置
  hanle_slider_change(e) {
    const position = e.detail.value
    this.seekCurrentAudio(position)
  },
  // 拖动进度条控件
  seekCurrentAudio(position) {
    // 更新进度条
    let that = this
    wx.seekBackgroundAudio({
      position: Math.floor(position),
      success: function () {
        AUDIOMANAGER.currentTime = position
        that.setData({
          current_process: that.format(position),
          slider_value: Math.floor(position)
        })
      }
    })
  },
  // 进度条滑动
  handle_slider_move_start() {
    this.setData({
      is_moving_slider: true
    });
  },
  handle_slider_move_end() {
    this.setData({
      is_moving_slider: false
    });
  },
  // 时间格式化
  format: function(t) {
    let time = Math.floor(t / 60) >= 10 ? Math.floor(t / 60) : '0' + Math.floor(t / 60)
    t = time + ':' + ((t % 60) / 100).toFixed(2).slice(-2)
    return t
  },
    // 播放音频
  playAudio1: function(){
    console.log(9799875)
    console.log(AUDIO.is_play)
    if(AUDIO.is_play) {
      AUDIOMANAGER.pause()
      AUDIO.is_play = false
      this.setData({
        audioImg: false
      })
    } else {
      AUDIOMANAGER.play()
      AUDIO.is_play = true
      this.setData({
        audioImg: true
      })
    }

  },
})

第三步,由于index.js里引入了app.js的方法或者属性了,其实就是将AUDIO的方法提出来了,放在了一个公用的里面,自己单独建立公用文件或者直接写在app.js里都是可以的,这里将其放在app.js中,可以对应这修改globalData里的属性

globalData: {
    userInfo: null,
    global_bac_audio_manager: {
      manage: wx.getBackgroundAudioManager(),
      is_play: false,
      id: '',
      play_time: '',
      article_id: '',
    }
  }

index.wxss

.audioMeaage{
  height: 124rpx;
  display: flex;
  align-items: center;
}
.proTime{
  font-size: 20rpx;
  color: #888888;
}
.progressWrap{
  display: flex;
  align-items: center;
}
.playIcom{
  width: 84rpx;
  height: 84rpx;
}
.slider{
  /* width: 502rpx; */
  
}
.slider1{
  width: 466rpx;
  margin:0 29rpx 0 8rpx;
}
.slider2{
  width: 466rpx;
  margin:0 29rpx 0 19rpx;
}