Created
June 4, 2012 19:02
-
-
Save thingsinjars/2870195 to your computer and use it in GitHub Desktop.
Web Audio API Example code
This file contains hidden or 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset=utf-8 /> | |
<title>Web Audio API</title> | |
</head> | |
<body> | |
<p class="play">Play</p> | |
<p class="stop">Stop</p> | |
</body> | |
</html> |
This file contains hidden or 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
(function() { | |
var context, | |
soundSource, | |
soundBuffer, | |
url = 'http://thelab.thingsinjars.com/web-audio-tutorial/nokia.mp3'; | |
// Step 1 - Initialise the Audio Context | |
// There can be only one! | |
function init() { | |
if (typeof AudioContext == "function") { | |
context = new AudioContext(); | |
} else if (typeof webkitAudioContext == "function") { | |
context = new webkitAudioContext(); | |
} else { | |
throw new Error('AudioContext not supported. :('); | |
} | |
} | |
// Step 2: Load our Sound using XHR | |
function startSound() { | |
var url = 'http://thelab.thingsinjars.com/web-audio-tutorial/nokia.mp3'; | |
// Note: this loads asynchronously | |
var request = new XMLHttpRequest(); | |
request.open("GET", url, true); | |
request.responseType = "arraybuffer"; | |
// Our asynchronous callback | |
request.onload = function() { | |
var audioData = request.response; | |
audioGraph(audioData); | |
}; | |
request.send(); | |
} | |
// Finally: tell the source when to start | |
function playSound() { | |
// play the source now | |
soundSource.noteOn(context.currentTime); | |
} | |
function stopSound() { | |
// stop the source now | |
soundSource.noteOff(context.currentTime); | |
} | |
// Events for the play/stop bottons | |
document.querySelector('.play').addEventListener('click', startSound); | |
document.querySelector('.stop').addEventListener('click', stopSound); | |
// This is the code we are interested in | |
function audioGraph(audioData) { | |
// create a sound source | |
soundSource = context.createBufferSource(); | |
// The Audio Context handles creating source buffers from raw binary | |
soundBuffer = context.createBuffer(audioData, true/* make mono */); | |
// Add the buffered data to our object | |
soundSource.buffer = soundBuffer; | |
// Plug the cable from one thing to the other | |
soundSource.connect(context.destination); | |
// Finally | |
playSound(soundSource); | |
} | |
init(); | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment