Skip to content

Instantly share code, notes, and snippets.

@JorenSix
Forked from revolunet/web-audio-fetch-stream.js
Created February 20, 2018 19:55
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JorenSix/f0bf4dc9635db41e587528ddf06c2c57 to your computer and use it in GitHub Desktop.
Save JorenSix/f0bf4dc9635db41e587528ddf06c2c57 to your computer and use it in GitHub Desktop.
Web Audio streaming with fetch API
//
// loads remote file using fetch() streams and "pipe" it to webaudio API
// remote file must have CORS enabled if on another domain
//
// mostly from http://stackoverflow.com/questions/20475982/choppy-inaudible-playback-with-chunked-audio-through-web-audio-api
//
function appendBuffer( buffer1, buffer2 ) {
var tmp = new Uint8Array( buffer1.byteLength + buffer2.byteLength );
tmp.set( new Uint8Array( buffer1 ), 0 );
tmp.set( new Uint8Array( buffer2 ), buffer1.byteLength );
return tmp.buffer;
}
function play(url) {
var context = new (window.AudioContext || window.webkitAudioContext)();
var audioStack = [];
var nextTime = 0;
fetch(url).then(function(response) {
var reader = response.body.getReader();
var header = null;//first 44bytes
function read() {
return reader.read().then(({ value, done })=> {
var audioBuffer = null;
if (header == null){
//copy first 44 bytes (wav header)
header = value.buffer.slice(0,44);
audioBuffer = value.buffer;
}else{
audioBuffer = appendBuffer(header,value.buffer);
}
context.decodeAudioData(audioBuffer, function(buffer) {
audioStack.push(buffer);
if (audioStack.length) {
scheduleBuffers();
}
}, function(err) {
console.log("err(decodeAudioData): "+err);
});
if (done) {
console.log('done');
return;
}
//read next buffer
read();
});
}
read();
})
function scheduleBuffers() {
while ( audioStack.length) {
var buffer = audioStack.shift();
var source = context.createBufferSource();
source.buffer = buffer;
source.connect(context.destination);
if (nextTime == 0)
nextTime = context.currentTime + 0.02; /// add 50ms latency to work well across systems - tune this if you like
source.start(nextTime);
nextTime += source.buffer.duration; // Make the next buffer wait the length of the last buffer before being played
};
}
}
var url = '/beats1.wav'
play(url);
@JorenSix
Copy link
Author

Fixed the problem with decoding audio without a header: added the 44byte wave header to every buffer to decode. Hacky but works...

@tomcontr
Copy link

tomcontr commented Jun 6, 2020

Did you finally figure out how to play the music without cuts?

Regards

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment