The following code will reproduce a sine wave at 0.5 and 2.0. Call the function play_buffersource() in your button or in any play_buffersource() location.
Tested using Chrome with the Web Audio flag enabled. In your case, all you have to do is just shuffle your audio bytes in buf .
<script type="text/javascript"> const kSampleRate = 44100; // Other sample rates might not work depending on the your browser AudioContext const kNumSamples = 16834; const kFrequency = 440; const kPI_2 = Math.PI * 2; function play_buffersource() { if (!window.AudioContext) { if (!window.webkitAudioContext) { alert("Your browser sucks because it does NOT support any AudioContext!"); return; } window.AudioContext = window.webkitAudioContext; } var ctx = new AudioContext(); var buffer = ctx.createBuffer(1, kNumSamples, kSampleRate); var buf = buffer.getChannelData(0); for (i = 0; i < kNumSamples; ++i) { buf[i] = Math.sin(kFrequency * kPI_2 * i / kSampleRate); } var node = ctx.createBufferSource(0); node.buffer = buffer; node.connect(ctx.destination); node.noteOn(ctx.currentTime + 0.5); node = ctx.createBufferSource(0); node.buffer = buffer; node.connect(ctx.destination); node.noteOn(ctx.currentTime + 2.0); } </script>
Recommendations:
If you need to re-sample the audio, you can use the JavaScript resampler: https://github.com/grantgalitz/XAudioJS
If you need to decode base64 data, there are many base64 JavaScript decoders: https://github.com/carlo/jquery-base64
Peter Lee
source share