Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web Audio playing back in Chrome but not Firefox

Firefox seems to be processing the audio but it won't play it back. This exact code works fine with Chrome. I'm seeing no errors from the console so I'm really at a loss. I'm thinking it has something to do with audioBuffer.getChannelData(0).set(audio); but I'm not sure. Anyone know why this audio won't play back in FF but will in Chrome? I'm running FF 27 right now.

window.AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();
var init = 0;
var nextTime = 0;
var audioStack = [];

function toArrayBuffer(buffer) {
    var ab = new ArrayBuffer(buffer.length);
    var view = new Uint8Array(ab);
    for (var i = 0; i < buffer.length; ++i) {
    view[i] = buffer[i];
    }
    return ab;
}

socket.on('stream', function(data) {
    audioStack.push(data);
    //if ((init!=0) || (audioStack.length > 10)) { // make sure we put at least 10 chunks in the buffer before starting
            init++;
            scheduleBuffers();
    //}
});

function scheduleBuffers() {
    while (audioStack.length) {

        var data  = toArrayBuffer(audioStack.shift().data);
        var audio = [];
        audData = new Int16Array(data);
        for (var i = 0; i < audData.length; i++) {
            audio[i] = (audData[i]>0)?audData[i]/32767:audData[i]/32768; // convert buffer to within the range -1.0 -> +1.0
        }

        var source      = context.createBufferSource();
        var audioBuffer = context.createBuffer(1, audio.length , 44100);
        source.buffer   = audioBuffer;

        audioBuffer.getChannelData(0).set(audio);

        source.connect(context.destination);
        if (nextTime == 0)
            nextTime = context.currentTime + 0.05;  /// add 50ms latency to work well across systems - tune this if you like
        source.start(nextTime);
        console.log('length: '+source.buffer.duration);
        nextTime+=source.buffer.duration; // Make the next buffer wait the length of the last buffer before being played
    };
}
like image 876
Brad.Smith Avatar asked Mar 20 '23 20:03

Brad.Smith


1 Answers

Looking at this code:

    source.buffer   = audioBuffer;
    audioBuffer.getChannelData(0).set(audio);

Can you try changing the order of these two lines? In other words, first set the channel data for audioBuffer and then assign it to source.buffer. Does that fix the problem for you?

like image 74
ehsan Avatar answered Apr 01 '23 07:04

ehsan