一,官方文档地址
https://uniapp.dcloud.net.cn/api/media/audio-context.html#createinneraudiocontext
说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest
对应的源码可以访问这里获取: https://github.com/liuhongdi/
或: https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: [email protected]
二,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", } }, onl oad(){ 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>