このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

View in English Always switch to English

AudioBufferSourceNode: loopEnd プロパティ

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2015年7月⁩.

loopEndAudioBufferSourceNode インターフェイスのプロパティで、 AudioBuffer の再生が loopStart プロパティで示される時刻にループで戻るオフセットを秒単位で指定する浮動小数点の数値です。 これは loop プロパティが true である場合にのみ使用されます。

各ループがループの最初に戻る(つまり、現在の再生時刻が AudioBufferSourceNode.loopStart にリセットされる)音声バッファー内のオフセットを、秒単位で示した浮動小数点の数値です。このプロパティは loop プロパティが true である場合にのみ使用されます。

既定値は 0 です。

loopEnd の設定

この例では、ユーザーが "Play" を押すと、音声トラックを読み込んでデコードし、AudioBufferSourceNode に入れます。

例えば、この例では loop プロパティを true に設定し、トラックがループして再生されるようにしています。

ユーザーは、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;
});

仕様書

Specification
Web Audio API
# dom-audiobuffersourcenode-loopend

ブラウザーの互換性

関連情報