2016-07-26 106 views
0

我試圖播放來自使用Chrome 51的獲取API的無限流。(作爲微軟PCM,16位,單聲道11025赫茲的攝像頭音頻流)WebAudio流與提取:DOMException:無法解碼音頻數據

的代碼可與MP3音樂文件幾乎確定,除了一些小問題,但它不會由於某種原因WAV文件在所有的工作我得到「拋出:DOMException:無法解碼音頻數據」

的代碼是從該調整回答Choppy/inaudible playback with chunked audio through Web Audio API

任何想法,如果它可能使其工作與WAV流?

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(); 
    function read() { 
     return reader.read().then(({ value, done })=> { 
     context.decodeAudioData(value.buffer, function(buffer) { 
      audioStack.push(buffer); 
      if (audioStack.length) { 
       scheduleBuffers(); 
      } 
     }, function(err) { 
      console.log("err(decodeAudioData): "+err); 
     }); 
     if (done) { 
      console.log('done'); 
      return; 
     } 
     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.01; /// 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 
     }; 
    } 
} 

只要使用play('/ path/to/mp3')來測試代碼。 (服務器需要啓用CORS,或者與您的運行腳本位於同一個域中)

回答

0

使wav流正確播放意味着要像Raymond建議的那樣向WAV文件頭添加WAV標題,加上一些webaudio魔術和paquet訂購檢查;

一些酷哥幫我安裝該模塊只是處理這一點,它精美的作品在Chrome:https://github.com/revolunet/webaudio-wav-stream-player

現在能在Firefox 57+與一些配置上的標誌:https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/getReader#Browser_compatibility

+0

爲什麼不能在Firefox上使用這個代碼? –

+1

支持以下標誌:https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/getReader#Browser_compatibility – jujule

1

AudioContext.decodeAudioData僅用於解碼部分文件;它旨在用於「短」(但完整)的文件。由於MP3的分塊設計,它有時適用於MP3流,但不適用於WAV文件。在這種情況下,你需要實現你自己的解碼器。

+1

或預先準備一個WAV頭在調用'decodeAudioData'之前對每個PCM數據塊。 WAV頭文件非常簡單。 –

+0

謝謝Raymond ...這對我來說聽起來是一個很好的解決方法...任何想法如何定義該標題並將其添加到塊? – jujule

+0

試驗這個想法在這裏:https://gist.github.com/revolunet/46d4187c3b6f28632a91421c1f2a9fad – jujule