Skip to content

Instantly share code, notes, and snippets.

@Anoesj
Created November 14, 2020 15:33
Show Gist options
  • Save Anoesj/7d560cfb51223dfb7120827fe9f153c6 to your computer and use it in GitHub Desktop.
Save Anoesj/7d560cfb51223dfb7120827fe9f153c6 to your computer and use it in GitHub Desktop.
Play local audio files with Web Audio API and File System Access API
// Create audio context.
const ctx = new window.AudioContext();
// Autoplay policy: start context after user gesture.
window.addEventListener('click', () => {
ctx.resume().then(() => {
console.log('AudioContext started');
});
}, {
once: true,
capture: true,
passive: true,
});
// Play local audio file.
async function playAudio (fileHandle) {
const file = await fileHandle.getFile();
const arrayBuffer = await file.arrayBuffer();
const decodedBuffer = await ctx.decodeAudioData(arrayBuffer);
// Create source node
const source = ctx.createBufferSource();
source.buffer = decodedBuffer;
source.connect(ctx.destination);
source.start();
}
// Async IIFE
(async (event) => {
// Show file picker for one audio file.
const [fileHandle] = await window.showOpenFilePicker({
multiple: false,
types: [
{
description: 'Audio files',
accept: {
'audio/*': ['.wav', '.ogg', '.mp3', '.mp4', '.aac', '.flac', '.webm'],
}
},
],
excludeAcceptAllOption: true,
});
// You may need try/catch around above, but for now: play the audio file.
playAudio(fileHandle);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment