src 音频的数据链接,用于直接播放。
play 播放(H5端部分浏览器需在用户交互时进行)
onEnded 音频自然播放结束事件
onShow() {
var music = null;
music = uni.createInnerAudioContext(); //创建播放器对象
music.src = '../../static/1.mp3'; // static文件夹下的音频
music.play(); //执行播放
music.onEnded(() => {
//播放结束
music = null;
});
},
H5端部分浏览器,需要写在事件中才能触发。否则会有报错
DOMException: play()失败,因为用户没有首先与文档交互
更新内容,实现背景音乐循环播放
data() {
return {
musicShow:true,// 默认音乐播放
musicData:null,
bgmList:[], //背景音乐
current_bgm:0,// 当前播放歌曲位置
current_src:'', //当前播放音乐的url
}
},
onLoad() {
this.$http.get('/api/ee/bgms').then(res=>{
if(res.code == 200){
this.bgmList = res.data.bgms
this.current_bgm = 0;
this.current_src = this.bgmList[this.current_bgm].url
console.log(this.bgmList.length);
this.musicData = null;
this.musicData = uni.createInnerAudioContext(); //创建播放器对象
this.musicData.src = this.current_src; // static文件夹下的音频
this.musicData.play(); //执行播放
this.musicData.onEnded(() => {
if(this.current_bgm == this.bgmList.length-1){
console.log('重头播放');
// 重头播放
this.current_bgm = 0
this.current_src = this.bgmList[this.current_bgm].url
this.musicData.src = this.current_src; // static文件夹下的音频
this.musicData.play(); //播放结束,循环播放
}else{
console.log('下一首音乐');
this.current_bgm++
this.current_src = this.bgmList[this.current_bgm].url
this.musicData.src = this.current_src; // static文件夹下的音频
this.musicData.play(); //播放结束,循环播放
}
});
}
})
},
// 音乐暂停播放按钮
changeMusic(){
if(this.musicShow){
console.log('暂停');
this.musicData.pause();
this.musicShow = !this.musicShow
}else{
console.log('开始');
this.musicData.play(); //播放结束,循环播放
this.musicShow = !this.musicShow
}
},