twilio - 有什么方法可以将来自 twilio 的 mulaw 音频流保存在文件中
问题描述
我正在使用 Twilio 语音流功能,我不想使用 Twilio 记录功能。当 Twilio 开始向我的服务器发送语音流时,我想将其作为音频文件实时存储到磁盘中。
解决方案
我今天遇到了同样的问题,并想出了一种为 mu-law 标头生成 WAVE 标头的方法:
如果您正在关注Twilio 的博客文章,那么这就是我最终实现的代码:
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;
}
});
});
推荐阅读
- c# - Unity Prefab 脚本被禁用
- amazon-web-services - aws lambda上的FFmpeg-NAL单元大小无效
- javascript - 如何使数组可编辑
- r - 每年最大数据
- vb.net - 如何使用 WebBrowser 控件下载文件
- javascript - 如何重构javascript函数以在不同函数中输出数据
- delphi - DropDownCount 不适用于 OwnerDrawFixed 样式
- javascript - 一个Diagram可以有多个linktemplates Gojs吗?
- extjs - 缩放 ExtJs 后面板不改变大小
- c++ - 用 C++ 中的对象填充列表时出现奇怪的问题?