AudioBufferSourceNode: loopEnd 属性

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

AudioBufferSourceNode 接口的 loopEnd 属性是一个浮点数,以秒为单位指定,在播放 AudioBuffer 期间,应在哪个时间点循环回 loopStart 属性指定的时间。仅当 loop 属性为 true 时才使用此属性。

一个浮点数,表示循环中每个循环将返回到循环开头的音频缓冲区的偏移量(以秒为单位),即当前播放时间将重置为 AudioBufferSourceNode.loopStart。仅当 loop 属性为 true 时才使用此属性。

默认值为 0。

示例

设置 loopEnd

在此示例中,当用户按下“播放”按钮时,我们将加载一个音轨,对其进行解码,然后将其放入 AudioBufferSourceNode 中。

然后,该示例将 loop 属性设置为 true,以便音轨循环播放。

用户可以使用 range 控件 来设置 loopStartloopEnd 属性。

注意:您可以 在线运行完整示例(或 查看源代码)。

js
let audioCtx;
let buffer;
let source;

const play = document.getElementById("play");
const stop = document.getElementById("stop");

const loopstartControl = document.getElementById("loopstart-control");
const loopstartValue = document.getElementById("loopstart-value");

const loopendControl = document.getElementById("loopend-control");
const loopendValue = document.getElementById("loopend-value");

async function loadAudio() {
  try {
    // Load an audio file
    const response = await fetch("rnb-lofi-melody-loop.wav");
    // Decode it
    buffer = await audioCtx.decodeAudioData(await response.arrayBuffer());
    const max = Math.floor(buffer.duration);
    loopstartControl.setAttribute("max", max);
    loopendControl.setAttribute("max", max);
  } catch (err) {
    console.error(`Unable to fetch the audio file. Error: ${err.message}`);
  }
}

play.addEventListener("click", async () => {
  if (!audioCtx) {
    audioCtx = new AudioContext();
    await loadAudio();
  }
  source = audioCtx.createBufferSource();
  source.buffer = buffer;
  source.connect(audioCtx.destination);
  source.loop = true;
  source.loopStart = loopstartControl.value;
  source.loopEnd = loopendControl.value;
  source.start();
  play.disabled = true;
  stop.disabled = false;
  loopstartControl.disabled = false;
  loopendControl.disabled = false;
});

stop.addEventListener("click", () => {
  source.stop();
  play.disabled = false;
  stop.disabled = true;
  loopstartControl.disabled = true;
  loopendControl.disabled = true;
});

loopstartControl.addEventListener("input", () => {
  source.loopStart = loopstartControl.value;
  loopstartValue.textContent = loopstartControl.value;
});

loopendControl.addEventListener("input", () => {
  source.loopEnd = loopendControl.value;
  loopendValue.textContent = loopendControl.value;
});

规范

规范
Web Audio API
# dom-audiobuffersourcenode-loopend

浏览器兼容性

另见