使用vue3创建媒体池播放器

使用vue3创建媒体池/播放器

1、音频类型枚举

1
2
3
4
export enum SoundEffects {
tipsMusic = 0,
bgMusic = 1
}

2、创建reactive对象,存储音频Howl相关信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
const playbackControls = reactive({
// 数组存储音频
sounds: [{
playId: '',
playing: false,
sound: null,
},{
playId: '',
playing: false,
sound: null,
}] as any,
// 播放音频
play: (src: string,typeIndex :SoundEffects) => {
let {playId,playing,sound:Sound} = playbackControls.sounds[typeIndex];
// 如果正在播放,停止播放
if (playing) {
Sound.stop();
return;
}
// 如果有可用的音频,播放音频
if (Sound) {
// 停止所有音频
Howler.stop();
Sound.volume(typeIndex === SoundEffects.tipsMusic ? config.volume.tips/100 : config.volume.bg/100)
Sound.play(playId);
return;
}

console.log('创建音频','调试音量tips',config.volume.tips)
console.log('创建音频','调试音量bg',config.volume.bg)
const sound = new Howl({
src: [src],
volume: typeIndex === SoundEffects.tipsMusic ? config.volume.tips/100 : config.volume.bg/100,
onplay: function(id) {
console.log('onplay',id)
playbackControls.sounds[typeIndex] = {
playId: id,
playing: true,
sound: sound,
};
},
onstop: function(id){
playbackControls.sounds[typeIndex].playing = false;
},
onend:function(id){
playbackControls.sounds[typeIndex].playing = false;
}
});
sound.play();
},
// 销毁音频
destroy: () => {
Howler.unload()
},
});

3、监听一下音量变化

1
2
3
4
5
6
7
8
watch([()=>config.volume.tips,()=>config.volume.bg],(newVal) => {
playbackControls.sounds.forEach((item,index) => {
if(item.playing){
console.log('调试音量',item.playId,newVal[index]/100)
item.sound.volume(newVal[index]/100,item.playId);
}
})
})