Christian Heilmann

Quick and dirty: Batch conversion of lots of video files on the command line with PHP and ffmpeg

Thursday, September 3rd, 2020 at 5:33 pm

I just found some old DVDs with lots of small videos I collected on the web of a long ago. They are in most dubious formats and some of them play not very well on my Mac because of it (even in VLC, we’re talking .asf, .3gp and lots of .mpeg here). So I wondered what I can do to batch convert them all.

Turns out, ffmpeg has an OK quality command for that and with a bit of PHP, I can let the machine churn through all of them and put them in an mp4 folder.

I am not too proud of this, but it works an may help you, too:

<?php
// Get all files in folder
$files = scandir('.');
// Create MP4 folder
exec('mkdir mp4');
 
// Filter out files starting with .,mp4, php files
// and folders
function thingstoskip($f) {
  if(is_dir($f)) {
    return false;
  } else {
    return !preg_match("/^\.|\.$|\.mp4$|.php$/",$f);
  }
}
$urls = array_filter($files, thingstoskip);
 
// Get number of all files and loop over them
$all = sizeof($urls);
foreach ($urls as $u) {
  echo $all.": ".$u."\n";
  // convert with ffmpeg, rename to mp4 and save in the mp4 folder
  exec(
    'ffmpeg -loglevel error -i "'. $u .
    '" -c:v libx264 -c:a libvo_aacenc -crf 20 -preset:v medium "./mp4/'.
    preg_replace("/\.[^\.]*$/",'.mp4',$u).'"'
  );
  $all = $all - 1;
}
?>

Share on Mastodon (needs instance)

Share on Twitter

Newsletter

Check out the Dev Digest Newsletter I write every week for WeAreDevelopers. Latest issues:

Dev Digest 146: 🥱 React fatigue 📊 Query anything with SQL 🧠 AI News

Why it may not be needed to learn React, why Deepfake masks will be a big problem and your spirit animal in body fat! 

Dev Digest 147: Free Copilot! Panel: AI and devs! RTO is bad! Pi plays!

Free Copilot! Experts discuss what AI means for devs. Don't trust containers. Mandated RTO means brain drain. And Pi plays Pokemon!

Dev Digest 148: Behind the scenes of Dev Digest & end of the year reports.

In 50 editions of Dev Digest we gave you 2081 resources. Join us in looking back and learn about all the trends this year.

Dev Digest 149: Wordpress break, VW tracking leak, ChatGPT vs Google.

Slowly starting 2025 we look at ChatGPT vs Google, Copilot vs. Cursor and the state of AI crawlers to replace web search…

Dev Digest 150: Shifting manually to AI.

Manual coding is becoming less of a skill. How can we ensure the quality of generated code? Also, unpacking an APK can get you an AI model.

My other work: