[英]How to save an audio(mp3) from an HTTP response
There is a GET request which fetches an audio, and when the response arrives I want to save it.有一个获取音频的 GET 请求,当响应到达时,我想保存它。 I have tried two ways but both ways are not working great.
我尝试了两种方法,但两种方法都不是很好。
Below the problem is that the file is not saved entirely.下面的问题是文件没有完全保存。 It only saves at max the first 16Kb of the file.
它最多只保存文件的前 16Kb。 I need it entirely.
我完全需要它。
res.on('data', d => {
this.writeFile(recordingID + ".mp3", "./recordings/", d);
});
Below is the second method, the audio is saved entirely but it does not play because it is corrupted.下面是第二种方法,音频被完全保存,但由于损坏而无法播放。
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
});
Try this out, you just need to push all the chunk to an array and then use the buffer to save the file.试试这个,你只需要将所有块推送到一个数组中,然后使用缓冲区来保存文件。
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);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.