Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Play an audio file using JavaScript
window.AudioContext = (function(){
return window.webkitAudioContext || window.AudioContext ;
// Global variables
var audioContext;
var audioBuffer = 0;
var audioUrl = "/assets/Doctor_Who_theme_excerpt.ogg";
$(document).ready(function() {
// check that your browser supports the API
try {
// the AudioContext is the primary container for all audio objects
audioContext = new AudioContext();
catch(e) {
alert('Web Audio API is not supported in this browser');
$("#play_button").click(function(e) {
// load the sound from a URL
function load_audio(url) {
var request = new XMLHttpRequest();'GET', url, true);
request.responseType = 'arraybuffer';
// When loaded decode the data and store the audio buffer in memory
request.onload = function() {
audioContext.decodeAudioData(request.response, function(buffer) {
audioBuffer = buffer;
}, onError);
function play_audio(buffer) {
var audioSourceNode = audioContext.createBufferSource();
audioSourceNode.buffer = audioBuffer;
// log if an error occurs
function onError(e) {
<p style="text-align:center">
<button id="play_button" style="font-size: 18px">Click to Play</button>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment