uni-app:播放音频mp3(hbuilderx 3.7.3)

一,官方文档地址

https://uniapp.dcloud.net.cn/api/media/audio-context.html#createinneraudiocontext

说明:刘宏缔的架构森林是一个专注架构的博客,

网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/06/05/uniapp-bo-fang-yin-pin-mp3-hbuilderx-3-7-3/

         对应的源码可以访问这里获取: https://github.com/liuhongdi/
         或: https://gitee.com/liuhongdi

说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,js代码:

<template>
    <view>
        <button @click="play">播放</button>
        <button @click="pause">停止</button>
        <text>当前播放时间:{{currentTime}}/{{duration}}</text>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                music:null,
                currentTime:'00:00',
                duration:"00:00",
            }
        },
        onLoad(){
            this.timer = null;
            this.music = uni.createInnerAudioContext();
            //得到时长
            this.music.onCanplay(()=>{
                this.music.duration;
                setTimeout(()=>{
                    this.duration = this.formatTime(this.music.duration);
                },1300);
            });
            //显示当前时间
            this.music.onPlay(()=>{
                this.timer = setInterval(()=>{
                    this.currentTime = this.formatTime(this.music.currentTime);
                    this.duration = this.formatTime(this.music.duration);
                },1000);
            }
            );
        },
        onUnload(){
            clearInterval(this.timer);
            this.music.destroy();
        },
        methods: {
            //播放
            play(){
               this.music.src = "http://file.lhdtest.com/audio/wxx.mp3";
               this.music.play();
            },
            //暂停
            pause(){
                this.music.pause();
                clearInterval(this.timer);
            },
            //格式化时间
            formatTime(value){
                let minute = parseInt(value/60);
                let second = parseInt(value%60);
                if (minute<10){
                    minute = "0"+minute;
                }
                if (second<10){
                    second = "0"+second;
                }
                return minute+":"+second;
            }
        }
    }
</script>

<style>

</style>

三,测试效果

四,查看hbuilderx的版本: 

posted @ 2023-03-18 12:14  刘宏缔的架构森林  阅读(1625)  评论(0编辑  收藏  举报