小編給大家分享一下微信小程序怎么實現音頻文件播放進度,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
問題描述
在微信小程序中經常會用到控制文件播放的滑塊,通過滑塊可控制音頻播放進度,下面即用代碼實現。
解決方案
首先用.wxml與 .wmss 代碼實現進度條的效果,再通過 .js 文件控制進度條的進度和進度條的時間顯示。
.wxml中(播放進度結構的代碼):
<view class="content-play-progress">
<text>{{play.currentTime}}</text>
<view>
<slider activeColor="#d33a31" block-size="12" backgroundColor="#dadada" value="{{play.percent}}"/>
</view>
<text>{{play.duration}}</text>
</view>在上述代碼中,第五行用到了slider組件,其值為播放進度 play.percent。
.wxss中(播放進度樣式的代碼) :
.content-play-progress{
display: flex;
align-items: center;
margin: 0 35rpx;
font-size: 9pt;
text-align: center;
}
.content-play-progress>view{
flex: 1;
}保存上述代碼后,運行程序,效果如圖:
圖 1 微信小程序進度條的實現
.js中(控制進度條的進度和時間的代碼) :
onReady: function(){
this.audioCtx=wx.createInnerAudioContext()
var that=this
//播放失敗檢測
this. audioCtx.onError(function(){
console.log( ‘ 播放失?。?nbsp;' +that.audioCtx.src)
})
//播放完成自動換下一曲
this. audioCtx.OnEnded(function(){
that.next()
})
//自動更新播放進度
this. audioCtx.onPlay(function(){
this. audioCtx.onTimeUpdate(function(){
that.setData({
‘ play.duration ' : formatTime(that.audioCtx.duration),
‘ play.currrentTime ' : formatTime(that.audioCtx. currrentTime),
‘ play.percent ' : that.audioCtx. currrentTime /
that.audioCtx.duration*100
})
})
//默認選擇第一曲
T his.setMusic(0)
//格式化時間
function formatTime(time){
var minute=Math.floor(time/60)%60;
var second=Math.floor(time)%60
return (minute<10? ' 0 ' +minute:minute)+ ' : ' +
(second<10? ' 0 ' +second:second)
}
})
}上述代碼中,通過調用audioCtx的 onTimeUpdate() 的方法,獲取音視頻狀態信息,并通過 formatTime() 函數處理時間格式,最后渲染到頁面實現實時更新效果,效果如圖:
圖 2 微信小程序進度條的滑動
在slider組件上綁定 bindchange 事件,可以實現滑動進度條調節音視頻文件播放進度,代碼示例 :
<slider bindchange= ” sliderChange ” activeColor= ” #d33a31 ” block-size= ” 12 ” backgroundColor= ” #dadada ” value= ” {{play.percent}} ” / >在.js文件中編寫 sliderChange 函數獲取用戶當前選擇的進度,將時間通過 audioCtx 對象的 seek() 方法進行設置,代碼示例:
sliderChange: function(e){
var second=e.detail.value* that.audioCtx.duration/100
that.audioCtx.seek(secend)
},以上是“微信小程序怎么實現音頻文件播放進度”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。