小程序之背景音乐—wx.getBackgroundAudioManager播放音频

wxml

<view class='container'>
    <view class='learn-tit'>
      <view class='answer-name'>
        <view>{{courseName}}</view>
        <view>{{courseSubName}}</view>
      </view>
      <view class='answer-pic'>
        <image
          src="../../img/record.png"
          mode="scaleToFill"
          lazy-load="false"
        />
      </view>
      <view class='audioControls'>
        <view class='flex'>
          <view
            class='bottom'
            catchtap='playAudio'
          >
            <!-- 按钮 -->
            <view wx:if="{{isPlayAudio}}">
              <image src='../../img/pauses.png' />
            </view>
            <view wx:else>
              <image src='../../img/pause.png' />
            </view>
          </view>
          <view class='slider'>
            <slider
              bindchange='sliderChange'
              activeColor='red'
              backgroundColor='#fff'
              block-size="12"
              value='{{audioTime}}'
            />
          </view>
        </view>
        <view class='time'>
          {{showTime1}} / {{showTime2}}
        </view>
      </view>
    </view>
  </view>

初始化数据如下:

    data = {
        user:[],
        innerAudioContext:'',
        audiolist:[ //获取音频
        {
            filePath:'',
            coverimg:"https://goss.veer.com/creative/vcg/veer/800water/veer-146156021.jpg"
        }
        ],
        isPlayAudio: false,
        audioSeek: 0,
        audioDuration: 0,
        showTime1: '00:00',
        showTime2: '00:00',
        audioTime: 0,
    };

点击开始播放操作

    methods = {
        playAudio() {
          if(!this.innerAudioContext.src) {
            this.audiolist[0].filePath='http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E061FF02C31F716658E5C81F5594D561F2E88B854E81CAAB7806D5E4F103E55D33C16F3FAC506D1AB172DE8600B37E43FAD&fromtag=46'
            this.innerAudioContext.src = this.audiolist[0].filePath;
          }
          //获取播放状态和当前播放时间
          var isPlayAudio = this.isPlayAudio;
          var seek = this.audioSeek;
          this.innerAudioContext.title =  '此时此刻';
          this.innerAudioContext.epname =  '此时此刻';
          this.innerAudioContext.singer = '';            
          this.innerAudioContext.pause();
          //更改播放状态
          this.isPlayAudio = !this.isPlayAudio
          if (isPlayAudio) {
            //如果在播放则记录播放的时间seek,暂停
            this.audioSeek = this.innerAudioContext.currentTime
          } else {
            //如果在暂停,获取播放时间并继续播放
            if (this.innerAudioContext.duration != 0) {
              this.audioDuration = this.innerAudioContext.duration
            }
            //跳转到指定时间播放
            this.innerAudioContext.seek(seek);
            this.innerAudioContext.play();
          }
        }       
    };

其余操作:

  //初始化播放器,获取duration
    Initialization(){
        var t=this;
        if (this.audiolist[0].filePath.length != 0) {
        //设置src  初始设置src默认自动播放
        // t.innerAudioContext.src = this.audiolist[0].filePath;
        //运行一次
        t.innerAudioContext.play();
        // t.innerAudioContext.pause();
        t.innerAudioContext.title =  '此时此刻';
        t.innerAudioContext.epname =  '此时此刻';
        t.innerAudioContext.singer = '';        
        t.innerAudioContext.onCanplay(() => {
            //初始化duration
            t.innerAudioContext.duration
            setTimeout(function () {
            //延时获取音频真正的duration
            var duration = t.innerAudioContext.duration;
            var min = parseInt(duration / 60);
            var sec = parseInt(duration % 60);
            if (min.toString().length == 1) {
                min = `0${min}`;
            }
            if (sec.toString().length == 1) {
                sec = `0${sec}`;
            }
            t.audioDuration = t.innerAudioContext.duration
            setTimeout(function(){
              t.showTime2 = `${min}:${sec}`
              t.$apply()
            },200)
            t.$apply()
            }, 1000)
        })
        }
    }
  //拖动进度条事件    
    sliderChange(e) {
        if(!this.innerAudioContext.src) {
          this.audioSeek = 0
            return
        } else {
            var that = this;
            // that.innerAudioContext.src = this.audiolist[0].filePath;
            //获取进度条百分比
            var value = e.detail.value;
            this.audioTime = value
            var duration = this.audioDuration;
            //根据进度条百分比及歌曲总时间,计算拖动位置的时间
            value = parseInt(value * duration / 100);
            //更改状态
              that.audioSeek = value
              that.isPlayAudio = true
            setTimeout(function(){
              //调用seek方法跳转歌曲时间
              that.innerAudioContext.seek(value);
            //播放歌曲
            that.innerAudioContext.play();
            that.$apply()
            },300)
        }
    }  

  loadaudio() {
    var that = this;
    //设置一个计步器
    this.durationIntval = setInterval(function () {
      //当歌曲在播放时执行
      if (that.isPlayAudio == true) {
        //获取歌曲的播放时间,进度百分比
        var seek = that.audioSeek;
        var duration = that.innerAudioContext.duration;
        var time = that.audioTime;
        time = parseInt(100 * seek / duration);
        //当歌曲在播放时,每隔一秒歌曲播放时间+1,并计算分钟数与秒数
        var min = parseInt((seek + 1) / 60);
        var sec = parseInt((seek + 1) % 60);
        //填充字符串,使3:1这种呈现出 03:01 的样式
        if (min.toString().length == 1) {
          min = `0${min}`;
        }
        if (sec.toString().length == 1) {
          sec = `0${sec}`;
        }
        var min1 = parseInt(duration / 60);
        var sec1 = parseInt(duration % 60);
        if (min1.toString().length == 1) {
          min1 = `0${min1}`;
        }
        if (sec1.toString().length == 1) {
          sec1 = `0${sec1}`;
        }
        //当进度条完成,停止播放,并重设播放时间和进度条
        if (time >= 99) {
          that.innerAudioContext.stop();
          that.audioSeek = 0
          that.audioTime = 0
          that.audioDuration = duration
          that.isPlayAudio = false
          that.showTime1 = '00:00'
          return false;
        }
        //正常播放,更改进度信息,更改播放时间信息
        that.audioSeek = seek + 1
        that.audioTime = time
        that.audioDuration = duration
        that.showTime1 = `${min}:${sec}`
        that.showTime2 = `${min1}:${sec1}`
      }
      that.$apply()
    }, 1000);
  }
    onLoad() {
        this.loadaudio();        
     };
    onShow() {
      this.innerAudioContext = wx.getBackgroundAudioManager()
        this.Initialization();
        this.onBackgroundAudioStop()
        this.onBackgroundAudioPlay()
        this.onBackgroundAudioQuit()     
    };
    //监听音频暂停
    onBackgroundAudioStop(){
        var that = this
        this.innerAudioContext.onPause(()=>{
            that.isPlayAudio = false
            that.$apply()
        })
    }    
    //监听音频播放
    onBackgroundAudioPlay(){
        var that = this
        this.innerAudioContext.onPlay(()=>{      
            that.isPlayAudio = true
            that.$apply()
        })        
    }
    //监听音频停止事件
    onBackgroundAudioQuit() {
        var that = this
        this.innerAudioContext.onStop(()=>{    
            that.isPlayAudio = false
            that.showTime1 = '00:00'
            that.audioSeek = 0
            that.audioTime = 0     
            that.$apply()        
        }) 
    }
    onUnload() {
      clearInterval(this.terval)
      clearInterval(this.durationIntval)
      this.innerAudioContext.pause();
    }

wxss:

.learn-tit {
  width: 100%;
  background: #f5f5f5;
}
.learn-head {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 15px;
}
.learn-head-left {
  display: flex;
  align-items: center;
  margin-left: 10px;
}
.learn-name {
  display: flex;
  border-radius: 30px;
  height: 30px;
  align-items: center;
  margin-right: 15px;
  background: rgba(68, 6, 0, 0.1);
}
.learn-name view {
  font-size: 13px;
  color: #222;
  height: 21px;
  max-width: 70px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.userinfo-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 5px;
}
.gender {
  width: 15px;
  height: 15px;
  margin: 0 6px;
}
.editor-name {
  width: 17px;
  height: 17px;
}
.learn-head-right {
  display: flex;
  align-items: center;
  margin-right: 10px;
  font-size: 13px;
  color: #fff;
  padding: 10px;
}
.learn-head-right text {
  height: 21px;
  margin-right: 5px;
  color: #222;
  font-size: 13px;
}
.flex {
  display: flex;
  align-items: center;
}
.audioPlayer {
  width: 100%;
  height: 400rpx;
  margin-bottom: 30rpx;
  box-sizing: border-box;
  padding: 20rpx 30rpx;
}
.player {
  width: 100%;
  height: 100%;
  position: relative;
}
.audioBack {
  width: 100%;
  height: 100%;
}
.audioControls {
  width: 100%;
  color: white;
  text-align: center;
}
.audioControls .bottom {
  height: 100%;
  margin-left: 10px;
  padding: 10px;
}
.audioControls .bottom image {
  width: 12px;
  height: 15px;
}
.audioControls .slider {
  width: 80%;
  height: 100%;
}
.slider slider {
  margin-right: 0;
}
.audioControls .time {
  height: 100%;
  font-size: 15px;
  color: #000;
  padding-bottom: 19px;
}
.answer-name {
  width: 100%;
  font-size: 14px;
  text-align: center;
  margin-top: 10px;
  margin-bottom: 10px;
}
.answer-pic {
  display: flex;
  justify-content: center;
  width: 100%;
}
.answer-pic image {
  margin-left: 16%;
  width: 209px;
  height: 179px;
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
wx.getBackgroundAudioManager() 是小程序中获取背景音频管理器的方法。背景音频管理器是用来控制背景音频播放的管理对象。 使用方法如下: 1. 在小程序中,通过 wx.getBackgroundAudioManager() 方法获取背景音频管理器的实例。 2. 可以通过获取的背景音频管理器实例对象,对背景音频进行控制和管理。 常用的方法如下: - play():播放背景音频。 - pause():暂停背景音频。 - stop():停止背景音频。 - seek(number):跳转到指定的位置播放。 - onPlay(callback):背景音频播放事件回调函数。 - onPause(callback):背景音频暂停事件回调函数。 - onStop(callback):背景音频停止事件回调函数。 - onEnded(callback):背景音频自然播放结束事件回调函数。 - onError(callback):背景音频播放错误事件回调函数。 - onPrev(callback):点击上一曲按钮事件回调函数。 - onNext(callback):点击下一曲按钮事件回调函数。 使用示例: 在小程序的某个页面,可以这样使用背景音频管理器: ``` // 获取背景音频管理器实例 const backgroundAudioManager = wx.getBackgroundAudioManager(); // 设置音频地址和标题 backgroundAudioManager.src = 'http://music.163.com/song/media/outer/url?id=28614699.mp3'; backgroundAudioManager.title = '小幸运'; // 播放背景音频 backgroundAudioManager.play(); // 监听背景音频播放事件 backgroundAudioManager.onPlay(() => { console.log('背景音频开始播放'); }); // 监听背景音频停止事件 backgroundAudioManager.onStop(() => { console.log('背景音频停止播放'); }); // ... ``` 以上就是 wx.getBackgroundAudioManager() 的基本使用方法和示例。通过背景音频管理器,可以实现背景音频的控制和管理,使小程序更加丰富和有趣。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值