banshee
banshee

Reputation: 90

How to execute ffmpeg commands synchronously?

I have a video processing API and I want to run ffmpeg commands synchronously otherwise processed files are getting corrupted.

So far I tried the steps below:

var execute = (command) => {
  const ffmpeg = spawn("./bin/ffmpeg/ffmpeg", command);
  ffmpeg.stderr.on("data", (data) => {
    debug(data.toString());
  });

  ffmpeg.on("close", () => {
    console.log('DONE');
  });
};

var sourceFilePath = '/tmp/test.mp4';
var outputPath = '/tmp/test_processed.mp4';
var ss = 5;
var t = 10;

execute([
  "-i",
  sourceFilePath,
  "-ss",
  ss,
  "-t",
  t,
  outputPath,
]);

await uploadTos3(outputPath); // Helper function to upload processed file to s3

The uploaded file is not working.. It's getting corrupted.

Note: When I try to upload a working video it's working. So the problem is with the ffmpeg helper function.

Upvotes: 1

Views: 1781

Answers (1)

Murat Colyaran
Murat Colyaran

Reputation: 2189

I think you should convert your execute function to this:

exports.execute = async (command) => {

  return new Promise((resolve, reject) => {
    const ffmpeg = spawn("./bin/ffmpeg/ffmpeg", command);
    ffmpeg.once('error',reject);
    ffmpeg.stderr.on("data", (data) => {
      debug(data.toString(); //I'm not sure what debug is
    });

    ffmpeg.on("exit", (code,signal) => {
      if(signal)
        code = signal;
      if(code != 0) {
        reject(new Error(`Returned exit code ${code}`);
        console.log('Error');
      }
      else {
        resolve(); // Call resolve here
        console.log('DONE');
      }
    });
  });
};
await execute([  // Call function with `await`
  "-i",
  sourceFilePath,
  "-ss",
  ss,
  "-t",
  t,
  outputPath,
]);

Upvotes: 5

Related Questions