uni.createInnerAudioContext能够创建并返回内部audio上下文innerAudioContext对象,从而代替audio组件。
为了兼容性和音质,推荐使用mp3格式
在pages文件夹下创建文件,其代码如下:
<template>
<view>
<view class="page-body">
<view class="page-section page-section-gap" style="text-align:center;">
<button type="default" @click="doPlay()">播放</button>
<button type="default" @click="doPause()">暂停</button>
<view style="margin-top: 20rpx;">当前播放时间:{{ currentTime }} / {{ duration }}</view>
</view>
</view>
</view>
</template>
<script>
export default{
name: 'audio-component',
data(){
return {
currentTime: "00:00",
duration:"00:00"
}
},
onLoad(){
this.timer = null;
this.innerAudioContext = uni.createInnerAudioContext();
// 监听音频进入可以播放状态的事件
this.innerAudioContext.onCanplay(()=>{
this.innerAudioContext.duration;
// 延迟大约300ms以上才能获取音频总时长
setTimeout(()=>{
// 获取音频总时长
this.duration = this.formatSeconds(this.innerAudioContext.duration);
},300)
});
// 监听音频播放
this.innerAudioContext.onPlay(()=>{
// 获取当前音频的播放时间
this.timer = setInterval(()=>{
this.currentTime = this.formatSeconds(this.innerAudioContext.currentTime);
},1000)
})
},
onUnload(){
clearInterval(this.timer);
// 销毁innerAudioContext实例
this.innerAudioContext.destroy();
},
methods:{
// 播放
doPlay(){
if (!this.innerAudioContext.src) {
// 音频地址
this.innerAudioContext.src = "/static/RedVelvet_ZOOM.flac";
}
this.innerAudioContext.play();
},
doPause(){
this.innerAudioContext.pause();
// 清除定时器
clearInterval(this.timer);
},
// 将秒转换成03:30格式
formatSeconds(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>