音频播放hooks
约 99 字小于 1 分钟
2025-01-19
import { ref, onUnmounted } from 'vue';
let currentAudio: HTMLAudioElement | null = null;
export function useAudioPlayer() {
const isPlaying = ref(false);
// 播放音频的方法
const playAudio = (src: string) => {
if (currentAudio) {
currentAudio.pause();
currentAudio.currentTime = 0;
}
// 创建新的 audio 元素并开始播放
currentAudio = new Audio(src);
currentAudio.play();
isPlaying.value = true;
currentAudio.onended = () => {
isPlaying.value = false;
currentAudio = null;
};
};
const pauseAudio = () => {
if (currentAudio) {
currentAudio.pause();
isPlaying.value = false;
}
};
// 清理当前音频资源
onUnmounted(() => {
if (currentAudio) {
currentAudio.pause();
currentAudio = null;
}
});
return {
isPlaying,
playAudio,
pauseAudio,
};
}