[英]Write or stream audio (live-voice) file to variable as a binary in Node.js
我正在使用 Node.js 中的音頻流。 至於現在,我的代碼沒有utils.promisfy
並且我有 3 個階段。 因此,在第二個.pipe
之后,我正在使用所需參數以wav
音頻格式將文件寫入磁盤。
下面的代碼示例:
import { FileWriter } from 'wav';
const filename = `./${Date.now()}-${userId}.wav`;
const encoder = new OpusEncoder(16000, 1);
receiver
.subscribe(userId, {
end: {
behavior: EndBehaviorType.AfterSilence,
duration: 100,
},
})
// OpusDecodingStream is a custom class, which convert audio, like a gzip stage for file.
.pipe(new OpusDecodingStream({}, encoder))
.pipe(
// Writes wav file to disk, also can be replaces with FileRead, part of wav module
new FileWriter(filename, {
channels: 1,
sampleRate: 16000,
}),
);
問題是:我需要通過axios
POST 方法以二進制格式傳輸(而不是流式傳輸!)生成的音頻文件。 所以我想,在磁盤上寫入文件而不是在變量中寫入文件有點錯誤,並且在流結束后,將其正確發送到所需的 URL。 我想看到的東西(按邏輯):
// other code
const fileStringBinary = await receiver
.subscribe(userId, {
end: {
behavior: EndBehaviorType.AfterSilence,
duration: 100,
},
})
.pipe(new OpusDecodingStream({}, encoder))
.pipe(
return new FileWriter(filename, {
channels: 1,
sampleRate: 16000,
}),
);
await axios.post('https://url.com', {
data: fileStringBinary
});
不幸的是,我不太擅長流媒體,尤其是音頻流,所以我正在尋求一些幫助,或者任何有用的建議對我來說都是受歡迎的。
我知道,我可以將我的文件寫入目錄,在那里找到它,使用
node:steam
createReadStream 再次讀取,然后將其發布到所需的 URL。 這不是我需要的。 我想通過寫作和閱讀跳過這個無用的階段。 我相信有一種方法可以將 steam 轉換為二進制格式並將其寫入 js 變量。
畢竟這有點古怪,但我想我明白了:
const stream = receiver
.subscribe(userId, {
end: {
behavior: EndBehaviorType.AfterSilence,
duration: 100,
},
})
.pipe(
new opus.OggLogicalBitstream({
opusHead: new opus.OpusHead({
channelCount: 2,
sampleRate: 48000,
}),
pageSizeControl: {
maxPackets: 10,
},
crc: false,
}),
);
const data = [];
stream.on('data', (chunk) => {
data.push(chunk);
});
stream.on('end', async () => {
try {
const response = await axios.post(
`https://url.com${postParams}`,
Buffer.concat(data),
{
headers: {
Authorization: `Api-Key ${token}`,
'Content-Type': 'application/x-www-form-urlencoded',
},
},
);
console.log(response);
} catch (e) {
console.log(e);
}
});
不幸的是,我還沒有找到更好的解決方案,然后使用帶有data
和 on end
的老式events
模型。 我的工作案例與 Discord.js 無文件錄音和使用流進行語音識別有關。
如果有人能提供更好的語法解決方案,我會很高興,在這種情況下,我會接受這個答案為已solved
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.