let audioCtx;
let buffer;
let source;
async function loadAudio() {
try {
// Load an audio file
const response = await fetch("viper.mp3");
// Decode it
buffer = await audioCtx.decodeAudioData(await response.arrayBuffer());
} catch (err) {
console.error(`Unable to fetch the audio file. Error: ${err.message}`);
}
}
play.addEventListener("click", async () => {
if (!audioCtx) {
audioCtx = new AudioContext();
await loadAudio();
}
// …
});BaseAudioContext: decodeAudioData() method / notebook
BaseAudioContext: decodeAudioData() method
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
let audioCtx;
let source;
function playBuffer(buffer) {
source = audioCtx.createBufferSource();
source.buffer = buffer;
source.connect(audioCtx.destination);
source.loop = true;
source.start();
}
async function loadAudio() {
try {
// Load an audio file
const response = await fetch("viper.mp3");
// Decode it
audioCtx.decodeAudioData(await response.arrayBuffer(), playBuffer);
} catch (err) {
console.error(`Unable to fetch the audio file. Error: ${err.message}`);
}
}
play.addEventListener("click", async () => {
if (!audioCtx) {
audioCtx = new AudioContext();
await loadAudio();
} else {
playBuffer();
}
});