Last active
December 27, 2015 17:09
-
-
Save webapprentice/7359638 to your computer and use it in GitHub Desktop.
Play an audio file using JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
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'); | |
} | |
load_audio(audioUrl); | |
$("#play_button").click(function(e) { | |
e.preventDefault(); | |
play_audio(audio_buffer); | |
}); | |
}); | |
// load the sound from a URL | |
function load_audio(url) { | |
var request = new XMLHttpRequest(); | |
request.open('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); | |
} | |
request.send(); | |
} | |
function play_audio(buffer) { | |
var audioSourceNode = audioContext.createBufferSource(); | |
audioSourceNode.buffer = audioBuffer; | |
audioSourceNode.connect(audioContext.destination); | |
audioSourceNode.noteOn(0); | |
} | |
// log if an error occurs | |
function onError(e) { | |
console.log(e); | |
} | |
</script> | |
<p style="text-align:center"> | |
<button id="play_button" style="font-size: 18px">Click to Play</button> | |
</p> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment