如何将timbre.js缓冲区导出为.wav或任何其他音频文件格式?

时间:2015-03-02 07:08:27

标签: javascript web-audio waveform

到目前为止,我想出了如何使用T("rec") Recorder。但是如何将timbre.js缓冲区导出为wav或任何其他音频文件格式?

var rec = T("rec", {timeout:1000}, t).on("ended", function(buffer) {
  // export buffer?
});

1 个答案:

答案 0 :(得分:2)

你能检查一下这是否有效,
我刚刚修改了source,将其更改为单通道并删除了工作位。

    var rec = T("rec", {timeout:1000}, t).on("ended", function(buffer) {
      // export buffer?

      // I am assuming that buffer is of format {buffer: bufferArray, samplerate: samplerate}


      var buf = buffer.buffer[0],      // buf = a Float32Array of data
          sr = buffer.samplerate    //sample rate of the data
      ;

      var dataview = encodeWAV(buf, sr);
      var audioBlob = new Blob([dataview], { type: 'audio/wav' });

      // do something with audioBlob, may be provide it as link to be downloaded
    });


    function encodeWAV(buf, sr){
      var buffer = new ArrayBuffer(44 + buf.length * 2);
      var view = new DataView(buffer);

      /* RIFF identifier */
      writeString(view, 0, 'RIFF');
      /* chunk size (= file length - 8) */
      view.setUint32(4, 36 + buf.length * 2, true);
      /* RIFF type */
      writeString(view, 8, 'WAVE');
      /* format chunk identifier */
      writeString(view, 12, 'fmt ');
      /* format chunk length */
      view.setUint32(16, 16, true);
      /* sample format (raw) */
      view.setUint16(20, 1, true);
      /* channel count */
      view.setUint16(22, 1, true);
      /* sample rate */
      view.setUint32(24, sr, true);
      /* byte rate (sample rate * block align) */
      view.setUint32(28, sr *2 , true);
      /* block align (channel count * bytes per sample) */
      view.setUint16(32, 2, true);
      /* bits per sample */
      view.setUint16(34, 16, true);
      /* data chunk identifier */
      writeString(view, 36, 'data');
      /* data chunk length */
      view.setUint32(40, buf.length * 2, true);

      floatTo16BitPCM(view, 44, buf);

      return view;
    }    

    function floatTo16BitPCM(output, offset, input){
      for (var i = 0; i < input.length; i++, offset+=2){
        var s = Math.max(-1, Math.min(1, input[i]));
        output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);
      }
    }

    function writeString(view, offset, string){
      for (var i = 0; i < string.length; i++){
        view.setUint8(offset + i, string.charCodeAt(i));
      }
    }

小提琴demo