2

I've been working lately on a project which takes a webm file and converts it to mp3 server side. So far I was getting the file, convert it in my server and then send a link to the user from which they could download the file. The user had to wait until the conversion was done.

Recently I came with the idea of streaming the file to the client-side and save it at the same time.

What I want to achieve is this: Stream the file to the client-side (chunk by chunk) and once the file stream has finished which means the conversion on the server has finished as well I can save the file.

I've tried this:

const { PassThrough } = require("stream");
const ffmpeg = require("fluent-ffmpeg");
const { writeFile } = require("fs");

let buffers = [];
const passThrough = new PassThrough();
res.setHeader("Content-Type", "`audio/mpeg");

ffmpeg(stream)
            .noVideo()
            .format("mp3")
            .audioBitrate(256)
            .on("error", (error) => console.log(error))
            .on("end", () => {
              res.end();
              buffers = buffers.join("");
              writeFile(`./files/test.mp3`, buffers, (err) => {
                if (err) console.log(err);
              });
            })
            .writeToStream(passThrough);

          passThrough.on("data", (chunk) => {
            buffers.push(chunk);
            res.write(chunk);
          });

What the issue is? Let's say I convert a 2.50min webm video.

The file is streamed to the client side successfully and it is being saved as it should. It is also playable and the size of the file is around 5MB.

The file saved on the server though is around 9MB, it is saved as an mp3 file but when I try to listen to it, it gives me this error:

Audacity: "Audacity did not recognize the type of the file. Try installing FFmpeg."

Browser: "No video with supported format and MIME type found."

Windows Media Player: "We cannot open test.mp3. This may be because the file type is unsupported, the file extension is incorrect or the file is corrupt."

Ioannis L.
  • 21
  • 2

0 Answers0