1. 程式人生 > >小程式實現播放器功能

小程式實現播放器功能

例項:一個簡單的播放器效果。實現的功能:1點選播放按鈕。音訊開始播放。2播放的同時,進度條在不停的更新走動3點選暫停按鈕,音訊停止播放4當音訊播放完畢以後,進度條再次回到原點5當拖滑動滑塊以後,鬆開滑塊,進度條繼續走動,音訊從滑塊鬆開的位置播放,直至播放結束html:<!--進度條--><viewclass="progresswrap"><sliderclass="drag"step="10"value="{{curTimeVal}}"max="{{duration}}"backgroundColor="#373636"activeColor="#FF1744"bindchange="slideBar"/></view><!--控制按鈕--><viewclass="btns"><viewbindtap='play'><imagesrc="{{playSrc}}"></image></view
><viewbindtap='pause'><imagesrc="{{pauseSrc}}"></image></view></view>jsconst innerAudioContext = wx.createInnerAudioContext();Page({duration:0,curTimeVal:0,})onLoad: function:(){wx.request({url: utils.baseUrl + "/message/get?sessionID=" + sessionID + "&id=" + id,success: function
(res) {var resData = res.data.datavar audioSrc ="https://www.rujian.vip"+resData.resourceURL;that.setData({contResponseArr: resData,audioSrc: audioSrc})innerAudioContext.src = audioSrc;}})},play: function (e) {var that=this;innerAudioContext.play();innerAudioContext.onPlay((res) =>that.updateTime(that)}) //沒有這個事件觸發,無法執行updatatime
}pause:function(){innerAudioContext.pause();},updateTime:function(that){innerAudioContext.onTimeUpdate((res) => {//更新時把當前的值給slide元件裡的value值。slide的滑塊就能實現同步更新console.log("duratio的值:", innerAudioContext.duration)that.setData({duration: innerAudioContext.duration.toFixed(2) *100,curTimeVal: innerAudioContext.currentTime.toFixed(2) *100,})})//播放到最後一秒
if (innerAudioContext.duration.toFixed(2) - innerAudioContext.currentTime.toFixed(2) <= 0) {that.setStopState(that)}innerAudioContext.onEnded(() => {that.setStopState(that)})
},//拖動滑塊slideBar:function(e){let that=this;var curval=e.detail.value; //滑塊拖動的當前值innerAudioContext.seek(curval); //讓滑塊跳轉至指定位置innerAudioContext.onSeeked((res)=>{this.updateTime(that) //注意這裡要繼續出發updataTime事件,})},setStopState:function(that){that.setData({curTimeVal: 0})innerAudioContext.stop()}

效果如下: