Node.js 如何从HTTP响应保存音频(mp3)
有一个获取音频的GET请求,当响应到达时,我想保存它。我试过两种方法,但两种方法都不管用 下面的问题是文件没有完全保存。它最多只保存文件的前16Kb。我完全需要它Node.js 如何从HTTP响应保存音频(mp3),node.js,http,Node.js,Http,有一个获取音频的GET请求,当响应到达时,我想保存它。我试过两种方法,但两种方法都不管用 下面的问题是文件没有完全保存。它最多只保存文件的前16Kb。我完全需要它 res.on('data', d => { this.writeFile(recordingID + ".mp3", "./recordings/", d); }); 下面是第二种方法,音频完全保存,但由于损坏而无法播放 let array = []; let str = &qu
res.on('data', d => {
this.writeFile(recordingID + ".mp3", "./recordings/", d);
});
下面是第二种方法,音频完全保存,但由于损坏而无法播放
let array = [];
let str = "";
let stringWithoutSpaces;
res.setEncoding('binary');
res.on('data', function (chunk) {
str += chunk;
array.push(chunk);
stringWithoutSpaces= array.join('');
});
res.on("end", () => {
try {
fs.promises
.writeFile(recordingID + ".mp3", stringWithoutSpaces, {
encoding: 'utf8'
})
.then(() => {
console.log('Done');
});
if (err) throw err
});
尝试一下,您只需要将所有块推送到一个数组中,然后使用缓冲区保存文件
let array = [];
res.on('data', function (chunk) {
array.push(chunk);
});
res.on("end", () => {
try {
fs.promises
.writeFile( `${recordingID}.mp3`, Buffer.concat(array), {
encoding: 'utf8'
})
.then(() => {
console.log('Done');
});
} catch (e) {
console.log(e);
}
});
编码:“utf8”
?对于二进制数据,我删除了二进制编码,保留了UTF-8编码,它工作得非常好。