<view class="play" @click="handerPlay">
<image
:src="isPlay ? '/static/noplay.png' : '/static/play.png'"
mode="aspectFit"
></image>
</view>
<script>
const innerAudioContext = uni.createInnerAudioContext()
export default {
data() {
return {
isPlay: false,
audioObj: {
url:"https://hkx-dev-res.oss-cn-beijing.aliyuncs.com/%E4%BA%92%E5%8A%A8%E5%BC%8F%E7%9B%B4%E6%92%AD3.mp3"
},
timer: null,
currentTime: "00:00",
duration: "00:00"
};
},
methods: {
handerPlay() {
// debugger
this.isPlay = !this.isPlay;
if (this.isPlay) {
this.doPlay()
} else {
this.doPause()
}
},
// 播放
doPlay() {
if (!innerAudioContext.url) {
// 音频地址
innerAudioContext.url = this.audioObj.url;
innerAudioContext.play();
}
innerAudioContext.play();
},
doPause() {
innerAudioContext.pause();
// 清除定时器
clearInterval(this.timer);
},
}
onLoad() {
this.timer = null;
innerAudioContext.onCanplay(() => {
innerAudioContext.duration
// 延迟大约300ms以上才能获取音频总时长
setTimeout(() => {
// 获取音频总时长
this.duration = this.formatSeconds(innerAudioContext.duration);
}, 300);
});
// 监听音频播放
innerAudioContext.onPlay(() => {
// 获取当前音频的播放时间
this.timer = setInterval(() => {
this.currentTime = this.formatSeconds(
innerAudioContext.currentTime
);
}, 1000);
});
innerAudioContext.onError(err => {
console.log(err)
})
}
</script>
代码差不多是这样, 点击播放,完全没有反应只有按钮图片的切换,再点暂停,会报 The play() request was interrupted by a call to pause()