Audio Buffer Example

by bradisbell

HTML

<input type="file" accept="audio/*" />

JavaScript

const audioContext = new AudioContext();
let buffer;

document.addEventListener('DOMContentLoaded', (e) => {
	document.querySelector('input[type="file"]').addEventListener('change', async (e) => {
  	// Start the AudioContext, now that we have user ineraction
    audioContext.resume();

    // Ensure we actually have at least one file before continuing
    if ( !(e.currentTarget.files && e.currentTarget.files[0]) ) {
    	return;
    }
    
    // Read the file and decode the audio
    buffer = await audioContext.decodeAudioData(
    	await e.currentTarget.files[0].arrayBuffer()
    );
  });
});

document.addEventListener('keydown', (e) => {
	// Ensure we've loaded audio
	if (!buffer) {
  	return;
  }
  
  // Create the node that will play our previously decoded buffer
  bufferSourceNode = audioContext.createBufferSource();
  bufferSourceNode.buffer = buffer;
  
  // Hook up the buffer source to our output node (speakers, headphones, etc.)
  bufferSourceNode.connect(audioContext.destination);
  
  // Adjust pitch based on the key we pressed, just for fun
  bufferSourceNode.detune.value = (e.keyCode - 65) * 100;
  
  // Start playing... right now
  bufferSourceNode.start();
});