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
56
57
58
59
60
61
62
63
64
65
66
| import { ref, watch } from "vue";
|
| let currentAudio: HTMLAudioElement | null = null;
|
| export function useAudioPlayer() {
| const source = ref<string | null>(null);
| const isPlaying = ref(false);
|
| // 播放音频
| const play = (src: string) => {
| if (!src) return;
|
| // 如果当前正在播放其他音频,先暂停并释放
| if (currentAudio) {
| currentAudio.pause();
| currentAudio = null;
| isPlaying.value = false;
| }
|
| currentAudio = new Audio(src);
| currentAudio.loop = true; // 循环播放
| currentAudio.volume = 1.0; // 音量最大
| currentAudio
| .play()
| .then(() => {
| isPlaying.value = true;
| })
| .catch((err) => {
| console.error("音频播放失败:", err);
| });
|
| // 监听播放完毕
| currentAudio.onended = () => {
| isPlaying.value = false;
| };
|
| source.value = src;
| };
|
| // 暂停播放
| const pause = () => {
| if (currentAudio) {
| currentAudio.pause();
| isPlaying.value = false;
| }
| };
|
| // 停止播放(并清除资源)
| const stop = () => {
| if (currentAudio) {
| currentAudio.pause();
| currentAudio.currentTime = 0;
| currentAudio = null;
| isPlaying.value = false;
| source.value = null;
| }
| };
|
| return {
| source,
| isPlaying,
| play,
| pause,
| stop,
| };
| }
|
|