Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peace098beat/10582498 to your computer and use it in GitHub Desktop.
Save peace098beat/10582498 to your computer and use it in GitHub Desktop.
WEB SOUNDER オーディオデータを再生する
// 参考
// [WEB SOUNDER オーディオデータを再生する](http://curtaincall.weblike.jp/portfolio-web-sounder/webaudioapi-basic/audio)
window.onload = function () {
// body...
alert('test_02.js: window.onloadが呼ばれました.');
}
window.AudioContext = window.AudioContext || window.webkitAudioContext;
//Create the instance of AudioContext
var context = new AudioContext();
var xhr = new XMLHttpRequest();
var url = './media/sample.wav';
//XMLHttpRequest Level 2
xhr.responseType = 'arraybuffer';
// xhrの状態変化時に呼び出される
// http://memopad.bitter.jp/w3c/ajax/ajax_xmlhttprequest_onreadystatechange.html
xhr.onreadystatechange = function(){
if ((xhr.readyState === xhr.DONE) && (xhr.status === 200)) {
var arrayBuffer = xhr.response;
if (arrayBuffer instanceof ArrayBuffer) {
var successCallback = function(audioBuffer){
/* audioBuffer is the instance of AudioBuffer */
//Create the instance of AudioBufferSourceNode
var source = context.createBufferSource();
//Set the instance of AudioBuffer
source.buffer = audioBuffer;
//Set parameters
source.loop = false;
source.loopStart = 0;
source.loopEnd = audioBuffer.duration;
source.playbackRate.value = 1.0;
//AudioBufferSourceNode (input) -> AudioDestinationNode (output)
source.connect(context.destination);
//for legacy browsers
source.start = source.start || source.noteOn;
source.stop = source.stop || source.noteOff;
//Start audio
source.start(0);
var endedCallback = function(event){
//Stop audio
source.stop(0);
event ? window.alert('STOP by "on' + event.type + '" event handler !!') : window.alert('STOP by "setTimeout" method !!');
//Audio is not started !!
//It is necessary to create the instance of AudioBufferSourceNode again
//source.start(0);
};
//The 'onended' event is implemented ?
if ('onended' in source) {
source.onended = endedCallback;
} else if (!source.loop) {
window.setTimeout(endedCallback, ((source.buffer.duration / source.playbackRate.value) * 1000));
}
};
var errorCallback = function(){
window.alert('Error : "decodeAudioData" method !!');
};
//Create the instance of AudioBuffer (Asynchronously)
context.decodeAudioData(arrayBuffer, successCallback, errorCallback);
}
}
};
xhr.open('GET', url, true);
xhr.send(null);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment