代码示例

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)
  1. 调用play(2),也就是期望播放2次。
  2. 初始化一个计数器和一个Audio对象。
  3. 为音频添加播放结束事件监听器,回调函数为onEnded
  4. 然后调用audio.play()进行播放。
  5. onEnded被调用,说明播放完成,我们将计数器自增加1
  6. 检查计数器是否达到期望次数:

    • 如果达到,则移除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);
  };
};

热饭班长
3.7k 声望434 粉丝

先去做,做出一坨狗屎,再改进。