微信小程序音频处理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月小程序登录、用户信息相关接口调整处理

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