Core JavaScript

Fetch an Audio ArrayBuffer

This is JavaScript program demonstrates how to fetch an audio ArrayBuffer.

FetchAudioArrayBuffer.html

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width" />
		<title>XoaX.net's Javascript</title>
		<!-- Supply a transparent 1x1 favicon -->
		<link rel="icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=">
		<style type="text/css">
			.cPlay {
				background-color:#DDDDDD;
			}
			.cStop {
				background-color:#DD0000;
				color:white;
			}
		</style>
		<script type="text/javascript" src="FetchAudioArrayBuffer.js"></script>
	</head>
	<body onload="Initialize()">
		<button class="cPlay">Play</button>
		<button class="cStop">Stop</button>
		<span class="cError"></span>
		<pre></pre>
  </body>
</html>

FetchAudioArrayBuffer.js

function Initialize() {
	// NOTE: THIS REQUIRES A WEB SERVER TO RUN
	const qDisplayElement = document.querySelector("pre");
	const qSourceCodeElement = document.querySelector("script");
	const qPlayButton = document.querySelector(".cPlay");
	const qStopButton = document.querySelector(".cStop");
	const qErrorMessageElement = document.querySelector(".cError");
 	
	let qCurrentSource = null;

	qPlayButton.onclick = () => {
		RetrieveData(qPlayButton).then((qSourceAudio) => {
			qErrorMessageElement.innerHTML = "";
			qCurrentSource = qSourceAudio;
			qCurrentSource.start(0);
			qPlayButton.disabled = true;
		}).catch((qError) => {
			let sErrorText = document.createTextNode(`Error: ${error.message}`);
			qErrorMessageElement.appendChild(sErrorText);
		});
	};

	qStopButton.onclick = () => {
		if (qCurrentSource != null) {
			qCurrentSource.stop(0);
			qPlayButton.disabled = false;
		}
	}

	// Display the code
	qDisplayElement.innerHTML = qSourceCodeElement.innerHTML;
}

// Load the audio file, decode it, place it in a buffer, and connect it to the context.
function RetrieveData(qPlayButton) {
	const kqAudioContext = new AudioContext();

	return fetch("WalhallaWagner.mp3").then((qResponse) => {
		if (!qResponse.ok) {
			throw new Error(`HTTP Error, status = ${response.status}`);
		}
		return qResponse.arrayBuffer();
	}).then((qBuffer) => kqAudioContext.decodeAudioData(qBuffer)
	).then((qDecodedAudioData) => {
		const kqSourceNode = new AudioBufferSourceNode(kqAudioContext);
		kqSourceNode.buffer = qDecodedAudioData;
		kqSourceNode.connect(kqAudioContext.destination);
		// Enable the play button when the audio is done playing
		kqSourceNode.onended = () => {
			qPlayButton.disabled = false;
		};
		return kqSourceNode;
	});
}
 

Output

 
 

© 2007–2026 XoaX.net LLC. All rights reserved.