微信小程序音頻處理audio -自定義進度控制

使用InnerAudioContext 實例

使用方法參考:https://my.oschina.net/tianma3798/blog/5070045

1.Wxml

<text>
    播放狀態:{{audio.currentTime}}s / {{audio.duration}} s
</text>
<slider value="{{audio.percent}}" bindchange="sliderChange"></slider>
<button type="primary" bindtap="payClick">
    <text wx:if="{{audio.isPlaying}}">點擊暫停</text>
    <text wx:else>點擊播放</text>
</button>

2. js代碼

// InnerAudioContext
var context = null; //一個音頻上下文

Page({
    /**
     * 頁面的初始數據
     */
    data: {
        audio: {
            isPlaying: false, //播放狀態
            //時間位置
            currentTime: 0,
            duration: 0,
            isWarting: false
        }
    },
    /**
     * 生命週期函數--監聽頁面加載
     */
    onLoad: function (options) {
        var _this = this;
        context = wx.createInnerAudioContext();
        //context.autoplay = true;  //是否自動播放
        //context.loop=true;  //是否循環播放
        //contex.volume   //設置音量  範圍 0~1。默認爲 1

        //contex.currentTime (單位 s)
        //context.duration (單位 s)

        context.src = "http://music.jnqianle.cn/file/audio/9.mp3";
        //開始播放
        context.onPlay(() => {
            console.info('開始播放');
        });
        //播放進行中
        context.onTimeUpdate(() => {
            console.info(context.currentTime, context.duration);
            _this.setData({
                'audio.currentTime': context.currentTime,
                'audio.duration': context.duration,
                'audio.percent': context.currentTime / context.duration * 100,
            });
        });
        context.onWaiting(() => {
            context.pause(); //當沒有加載時候暫停
        });
        context.onCanplay(() => {
            if(_this.data.audio.isPlaying){
                context.play();//當加載完畢後再播放
            }
        });
        //結束播放
        context.onStop(() => {
            console.info('結束播放');
        });
        //報錯,提示性
        context.onError((res) => {
            console.log(res.errMsg)
            console.log(res.errCode)
        });

    },
    //播放暫停
    payClick() {
        var _this = this;
        var isPlaying = _this.data.audio.isPlaying;
        if (isPlaying) {
            context.pause(); //暫停播放
            //stop()  停止,下次從頭開始播放
        } else {
            context.play(); //開始播放
        }
        _this.setData({
            'audio.isPlaying': !_this.data.audio.isPlaying
        });
    },
    //切換進度
    sliderChange(e) {
        var _this = this;
        var val = e.detail.value;
        var second = context.duration * val / 100;
        context.seek(second);
    },
    /**
     * 生命週期函數--監聽頁面顯示
     */
    onShow: function () {
        //context.play();
    },

    /**
     * 生命週期函數--監聽頁面隱藏
     */
    onHide: function () {
        //  context.stop();
        // context.pause();
    },
})

3.顯示效果

 

 

更多:

 微信小程序音頻處理audio 使用整理

 微信小程序獲取Canvas實例-新版Api

 2021年4月小程序登錄、用戶信息相關接口調整處理

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章