2016-07-26 31 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