Skip to content

Instantly share code, notes, and snippets.

@fukuroder
Last active December 28, 2015 12:29
Show Gist options
  • Save fukuroder/7501137 to your computer and use it in GitHub Desktop.
Save fukuroder/7501137 to your computer and use it in GitHub Desktop.
local wave file play test using Web Audio API (Google Chrome only)>>> http://fukuroder.sakura.ne.jp/gist/7501137/local_wave_file_play_test.html
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>local wave file play test</title>
<script src='http://code.jquery.com/jquery-2.1.1.min.js'></script>
<script>
$(function(){
var bufferSource;
var gainNode;
var decodedBuffer;
// get AudioContext
var context = new AudioContext();
var decodeFinished = function(buffer){
// set decoded buffer
decodedBuffer = buffer;
// enable play button and file selector
$('#play').removeAttr('disabled');
$('#wave').removeAttr('disabled');
};
var loadFinished = function(loaded_evt){
// decode
context.decodeAudioData(loaded_evt.target.result, decodeFinished);
};
$('#play')
.attr({disabled:'disabled', value:'play'})
.css({width:'100px'})
.click(function(){
if($(this).val() == 'stop'){
//--------------
// play -> stop
//--------------
// change button caption
$(this).val('play');
// enable file selector
$('#wave').removeAttr('disabled');
// stop
bufferSource.stop(0);
}
else{
//--------------
// stop -> play
//--------------
// change button caption
$(this).val('stop');
// disable file selector
$('#wave').attr({disabled:'disabled'})
// generate source
bufferSource = context.createBufferSource();
bufferSource.buffer = decodedBuffer;
// generate gain node
gainNode = context.createGain();
gainNode.gain.value = $('#gain').val()*0.01;
// connect (source->gain->destination)
bufferSource.connect(gainNode);
gainNode.connect(context.destination);
// play
bufferSource.start(0);
}
});
$('#gain')
.attr({min:0, max:100, value:50})
.change(function(){
// update gain
if(gainNode) gainNode.gain.value = $(this).val()*0.01;
});
$('#wave')
.attr({accept:'audio/*'})
.change(function(file_evt){
// disable play button
$('#play').attr({disabled:'disabled'});
if(file_evt.target.files.length == 0) return;
// disable file selector
$(this).attr({disabled:'disabled'});
// read local wave file
var reader = new FileReader();
reader.onload = loadFinished;
reader.readAsArrayBuffer(file_evt.target.files[0]);
});
});
</script>
</head>
<body>
local wave file play test using Web Audio API (Google Chrome only)
<hr/>
<input type='button' id='play'/>
volume:<input type='number' id='gain'/>
<input type='file' id='wave'/>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment