Created
March 21, 2016 21:48
-
-
Save richjava/8b3ca18a6b4efa83d296 to your computer and use it in GitHub Desktop.
Getting started with Web Audio API (from http://www.html5rocks.com/en/tutorials/webaudio/intro/)
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>TODO supply a title</title> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
</head> | |
<body> | |
<div onclick="playDogSound()">Play dog sound</div> | |
<script> | |
var url = 'http://localhost:8383/webaudio/audio/dog_bark_x.wav'; | |
//var url = | |
var dogBarkingBuffer = null; | |
var context; | |
window.addEventListener('load', init, false); | |
function init() { | |
try { | |
// Fix up for prefixing | |
window.AudioContext = window.AudioContext || window.webkitAudioContext; | |
context = new AudioContext(); | |
loadDogSound(url); | |
} | |
catch (e) { | |
alert('Web Audio API is not supported in this browser'); | |
} | |
} | |
function loadDogSound(url) { | |
var request = new XMLHttpRequest(); | |
request.open('GET', url, true); | |
request.responseType = 'arraybuffer'; | |
// Decode asynchronously | |
request.onload = function () { | |
context.decodeAudioData(request.response, function (buffer) { | |
dogBarkingBuffer = buffer; | |
}, onError); | |
} | |
request.send(); | |
} | |
function playDogSound(){ | |
playSound(dogBarkingBuffer); | |
} | |
function playSound(buffer) { | |
var source = context.createBufferSource(); // creates a sound source | |
source.buffer = buffer; // tell the source which sound to play | |
source.connect(context.destination); // connect the source to the context's destination (the speakers) | |
source.start(0); // play the source now | |
// note: on older systems, may have to use deprecated noteOn(time); | |
} | |
var onError = function (error) { | |
console.log('Whoops, there was an error!' + error); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment