AudioBufferSourceNode: loop 属性
AudioBufferSourceNode 接口的 loop 属性是一个布尔值,指示在到达 AudioBuffer 结尾时是否必须重新播放音频资源。
loop 属性的默认值为 false。
值
如果启用了循环,则返回 true;否则返回 false。
启用循环后,当调用 start() 时,声音将从指定的开始时间开始播放。当到达 loopEnd 属性指定的到达时间时,播放将从 loopStart 指定的时间继续。
示例
设置 loop
在此示例中,当用户按下“播放”按钮时,我们将加载一个音轨,对其进行解码,然后将其放入 AudioBufferSourceNode 中。
然后,该示例将 loop 属性设置为 true,以便音轨循环播放。
用户可以使用 range 控件 来设置 loopStart 和 loopEnd 属性。
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-loop |
浏览器兼容性
加载中…