如何在 JavaScript AudioContext 中的指定时间播放音频文件?

How can I play an audio file at specified times in JavaScript AudioContext?

如何在 JavaScript AudioContext 中的指定时间播放音频文件?

    const context = new AudioContext();
    const source = context.createBufferSource();
    const audioBuffer = await fetch('./Sound.wav')
      .then(res => res.arrayBuffer())
      .then(ArrayBuffer => context.decodeAudioData(ArrayBuffer));

    source.buffer = audioBuffer;
    source.connect(context.destination);
    source.start(1,3,5,7,20,30,40); // I want to play many times this file at these seconds. (Sound.wav length is 1second)
 

AudioBufferSourceNode#start() 方法接受可选的 offsetduration 参数(以秒为单位)作为它的第二个和第三个参数(第一个通常 开始播放)。

但是你只能启动这样一个节点一次(即使你可以让它循环)。因此,每次要开始播放音频文件时,您都必须创建一个新节点。不过别担心,这些节点的占用空间极小,不会占用您的内存。

(async () => {
  const url = "https://upload.wikimedia.org/wikipedia/en/transcoded/d/dc/Strawberry_Fields_Forever_%28Beatles_song_-_sample%29.ogg/Strawberry_Fields_Forever_%28Beatles_song_-_sample%29.ogg.mp3";
  const context = new AudioContext();
  const audioBuffer = await fetch(url)
    .then(res => res.arrayBuffer())
    .then(buffer => context.decodeAudioData(buffer));

  const play = (startTime, duration) => {
    const source = context.createBufferSource();
    source.buffer = audioBuffer;
    source.connect(context.destination);
    source.start(context.currentTime, startTime, duration);
  };

  [1, 3, 5, 10, 15, 18].forEach((startTime) => {
    const btn = document.createElement("button");
    btn.onclick = (evt) => play(startTime, 1);
    btn.textContent = "start at " + startTime + "s";
    document.body.append(btn);
  });
})().catch(console.error)
body {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 5px;
}