代码示例
const play = (times = 1) => {
let count = 0;
const audio = new Audio('https://dict.youdao.com/dictvoice?type=0&audio=I%20don%27t%20want%20to%20be%20here%20all%20the%20day');
const onEnded = () => {
count++;
if (count === times) {
audio.removeEventListener('ended', onEnded);
} else {
audio.play();
}
};
audio.addEventListener('ended', onEnded);
audio.play();
};
play(2)
- 调用
play(2)
,也就是期望播放2
次。 - 初始化一个计数器和一个
Audio
对象。 - 为音频添加播放结束事件监听器,回调函数为
onEnded
。 - 然后调用
audio.play()
进行播放。 - 当
onEnded
被调用,说明播放完成,我们将计数器自增加1
。 检查计数器是否达到期望次数:
- 如果达到,则移除
audio
上的ended
事件,流程结束。 - 如果未达到,则再次调用
audio.play()
进行播放,当播放完成,onEnded
会再次被调用,回到第5
步的流程继续,一直到计数器达到期望值。
- 如果达到,则移除
添加异常处理
const play = (times = 1) => {
let count = 0;
const audio = new Audio('https://dict.youdao.com/dictvoice?type=0&audio=I%20don%27t%20want%20to%20be%20here%20all%20the%20day');
const onEnded = () => {
count++;
if (count === times) {
audio.removeEventListener('ended', onEnded);
} else {
audio.play();
}
};
const onError = (error) => {
console.error('Audio play error:', error);
audio.removeEventListener('ended', onEnded);
};
audio.addEventListener('ended', onEnded);
audio.addEventListener('error', onError);
audio.play();
};
添加停止能力
const play = (times = 1) => {
let count = 0;
const audio = new Audio(
'https://dict.youdao.com/dictvoice?type=0&audio=I%20don%27t%20want%20to%20be%20here%20all%20the%20day'
);
const onEnded = () => {
count++;
if (count === times) {
audio.removeEventListener('ended', onEnded);
} else {
audio.play();
}
};
const onError = (error) => {
console.error('Audio play error:', error);
audio.removeEventListener('ended', onEnded);
};
audio.addEventListener('ended', onEnded);
audio.addEventListener('error', onError);
audio.play();
return () => {
audio.pause();
audio.currentTime = 0;
audio.removeEventListener('ended', onEnded);
audio.removeEventListener('error', onError);
};
};
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。