I have a livestream that is served through Icecast as an audio/mpeg. I use the following code to grab the audio from a livestream to listen to the audio:
function playLiveAudio() {
// Fix up prefixing
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();
var offset = 0;
var byteOffset = 0;
var minDecodeSize = 4096; // This is your chunk size
var request = new XMLHttpRequest();
request.onprogress = function(evt)
{
if (request.response)
{
var size = request.response.length - byteOffset;
if (size < minDecodeSize) return;
// In Chrome, XHR stream mode gives text, not ArrayBuffer.
// If in Firefox, you can get an ArrayBuffer as is
var buf;
if (request.response instanceof ArrayBuffer)
buf = request.response;
else
{
ab = new ArrayBuffer(size);
buf = new Uint8Array(ab);
for (var i = 0; i < size; i++)
buf[i] = request.response.charCodeAt(i + byteOffset) & 0xff;
}
byteOffset = request.response.length;
context.decodeAudioData(ab, function(buffer) {
playSound(buffer);
}, function(error) {
console.log(error);
});
}
};
request.onloadend = function(evt) {
console.log(evt);
};
request.open('GET', liveURL, true);
request.responseType = "stream"; // 'stream' in chrome, 'moz-chunked-arraybuffer' in firefox, 'ms-stream' in IE
request.overrideMimeType('text/plain; charset=x-user-defined');
request.send(null);
function playSound(buffer) {
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(offset); // play the source now
// note: on older systems, may have to use deprecated noteOn(time);
offset += buffer.duration;
}
}
I tried changing stream to moz-chunked-arraybuffer and seeing if I could manipulate the audio buffer but it doesn't seem to make a difference - I always get a decode promise rejection in Safari with no further message, or a decode audio data error in Firefox.
For some reason, it only works on Desktop Chrome - it doesn't work on any versions of Firefox, Safari or Mobile Chrome. How can decodeAudioData() be made to work on all environments? In Firefox I receive the error: cannot decodeAudioData(). I can set an audio element to livestream the URL but then there is an 8 second delay. This code achieves a 1 second delay.