2014-01-22 113 views
4

Firefox似乎正在處理音頻,但不會播放它。這個確切的代碼適用於Chrome。我沒有看到控制檯出現任何錯誤,所以我真的不知所措。我認爲它與audioBuffer.getChannelData(0).set(audio)有關;但我不確定。任何人都知道爲什麼這個音頻不會在FF中播放,但會在Chrome中播放?我現在正在運行FF 27。Web音頻在Chrome瀏覽器中播放,但不是Firefox

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 
    }; 
} 
+0

你介意鏈接到顯示問題的完整網頁嗎? –

+0

這裏雅去:https://github.com/grkblood13/web-audio-stream/tree/master/socketio/socketio-pcm –

回答

7

看這段代碼:

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

可以嘗試更改這兩行的順序?換句話說,首先設置audioBuffer的通道數據,然後將其分配給source.buffer。這是否解決了你的問題?

+0

是的,這解決了問題!由於瀏覽器之間的結果不同,這會被認爲是一個錯誤嗎? –

+0

這將會導致未來在Chrome中出現問題。這是規範處理潛在競爭條件的相對較新的變化。 – cwilso

+3

是的。這裏的問題是,當您在AudioBufferSourceNode上設置緩衝區屬性時,我們將在分配的右手邊符號處使用的AudioBuffer對象中的基礎數組緩衝區中,以便將來無法修改數組緩衝區影響音頻線程看到的內容。正如Chris所說,這是爲了防止潛在的競爭條件。 設置緩衝區屬性後,您的代碼依賴於對AudioBuffer底層數組緩衝區的修改。希望這可以幫助。 – ehsan

相關問題