Skip to content

Instantly share code, notes, and snippets.

@webapprentice
Last active December 27, 2015 17:09
Show Gist options
  • Save webapprentice/7359638 to your computer and use it in GitHub Desktop.
Save webapprentice/7359638 to your computer and use it in GitHub Desktop.
Play an audio file using JavaScript
<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