首页 > 解决方案 > 用 arrayBuffer 录制 mp3

问题描述

我用 Stackoverflow 尝试了很多东西,但我无法得到它。所以我尝试用 nodejs (1) 从树莓派录制音频。在此流通过 websocket 服务器之后(我没有放置此代码,因为它只是一个重定向)。最后一个 vuejs 中的 websocket 监听流。在我想用 mp3 (2) 录制这个流之后。但我有噪音或什么都没有。1 - 树莓派:

ai = new audio.AudioIO({
        inOptions: {
          channelCount: 1,
          sampleFormat: audio.SampleFormat16Bit,
          sampleRate: 44100,
          deviceId: 6, // Use -1 or omit the deviceId to select the default device
          closeOnError: true // Close the stream if an audio error is detected, if set false then just log the error
        }
      });

      ai.on('data', buf => {
      
      clientAudioWebsocket.send(buf)
      }
      );
      
     
      ai.start();  

2-部分vuejs

而且我不明白为什么我有 16384 大小的缓冲区的数组缓冲区。我真的对任何解决方案持开放态度,但我不想在服务器端这样做。谢谢

标签: javascriptnode.jsvue.jsaudiowebsocket

解决方案


所以我找到了解决方案,这是因为我没有创建一个 Int16Array :-( (有时最好在 1 小时之外,然后你会找到解决方案)

解决方案是:

let tmpResult = this.concatArrayBuffers(this.dataBuffer)
     
var samples = new Int16Array(tmpResult);
var buffer = [];
var mp3enc = new lamejs.Mp3Encoder(1, 44100, 128);
var remaining = samples.length;
var maxSamples = 1152;
for (var i = 0; remaining >= maxSamples; i += maxSamples) {
     var mono = samples.subarray(i, i + maxSamples);
     var mp3buf = mp3enc.encodeBuffer(mono);
     if (mp3buf.length > 0) {
         buffer.push(new Int8Array(mp3buf));
        }
        remaining -= maxSamples;
}
var d = mp3enc.flush();
if(d.length > 0){
 buffer.push(new Int8Array(d));
}

console.log('done encoding, size=', buffer.length);
var blob = new Blob(buffer, {type: 'audio/mp3'});

推荐阅读