有没有办法将twilio的mulaw音频流保存到文件中

问题描述 投票:0回答:1

我正在使用Twilio语音流功能,并且我不想使用Twilio录音功能。当Twilio开始将​​语音流发送到我的服务器时,我想将其作为音频文件实时存储到磁盘中。

twilio audio-streaming nodejs-stream twilio-programmable-voice
1个回答
0
投票

我今天遇到了同一问题,并找到了一种为mu-law标头生成WAVE标头的方法:

如果您遵循Twilio's blog post,那就是我结束实现的代码:

wss.on('connection', (socket) => {
  socket.on('message', (msg) => {
    const { event, ...message } = JSON.parse(msg);
    switch (event) {
      case 'start':
        let streamSid = message.start.streamSid;
        socket.wstream = fs.createWriteStream(__dirname + `/${Date.now()}.wav`, { encoding: 'binary' });
        // This is a mu-law header for a WAV-file compatible with twilio format
        socket.wstream.write(Buffer.from([
          0x52,0x49,0x46,0x46,0x62,0xb8,0x00,0x00,0x57,0x41,0x56,0x45,0x66,0x6d,0x74,0x20,
          0x12,0x00,0x00,0x00,0x07,0x00,0x01,0x00,0x40,0x1f,0x00,0x00,0x80,0x3e,0x00,0x00,
          0x02,0x00,0x04,0x00,0x00,0x00,0x66,0x61,0x63,0x74,0x04,0x00,0x00,0x00,0xc5,0x5b,
          0x00,0x00,0x64,0x61,0x74,0x61,0x00,0x00,0x00,0x00, // Those last 4 bytes are the data length
        ]));
        break;
      case 'media':
        // decode the base64-encoded data and write to stream
        socket.wstream.write(Buffer.from(message.media.payload, 'base64'));
        break;
      case 'stop':
        // Now the only thing missing is to write the number of data bytes in the header
        socket.wstream.write("", () => {
          let fd = fs.openSync(socket.wstream.path, 'r+'); // `r+` mode is needed in order to write to arbitrary position
          let count = socket.wstream.bytesWritten;
          count -= 58; // The header itself is 58 bytes long and we only want the data byte length
          console.log(count)
          fs.writeSync(
            fd,
            Buffer.from([
              count % 256,
              (count >> 8) % 256,
              (count >> 16) % 256,
              (count >> 24) % 256,
            ]),
            0,
            4, // Write 4 bytes
            54, // starts writing at byte 54 in the file
          );
        });
        break;
    }
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.