简体   繁体   English

如何从 HTTP 响应中保存音频(mp3)

[英]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.

相关问题 NodeJS - 从固定的 HTTP 端点流式传输 MP3 音频播放列表 - NodeJS - Stream MP3 Audio Playlist from fixed HTTP endpoint 如何在javascript中将音频(mp3)文件转换为二进制文件? - how to convert an audio (mp3) file into a binary file in javascript? 如何修改MP3元数据并按Node.js保存? - How to modify a MP3 metadata and save by Node.js? 如何 stream 从服务器到客户端的媒体文件,例如我在环回 4 nodejs 中的 mp3 音频文件? - How to stream a media file from server to client side for example an mp3 audio file in my case in loopback 4 nodejs? 如何循环播放MP3? - How to loop an MP3? Node.js将Mp3流传输到http,而无需保存文件 - Node.js Stream Mp3 to http without having to save file Angular2 ExpressJs-音频mp3上载到服务器(音频mp3小于16MB) - Angular2 ExpressJs - audio mp3 upload to the server (audio mp3 less than 16MB) fluent-ffmpeg将音频块转换为mp3并将其附加到mp3文件 - fluent-ffmpeg to convert audio chunks to mp3 and append them to an mp3 file 如何捕获通过HTTP流式传输的mp3的前10秒 - How to capture the first 10 seconds of an mp3 being streamed over HTTP binaryjs - nodejs mp3音频流和播放 - binaryjs - nodejs mp3 audio stream and play back
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM