Skip to content

Instantly share code, notes, and snippets.

@jthatch
Created October 10, 2016 11:28
Show Gist options
  • Save jthatch/921643103a7eca2c968222d166feea0f to your computer and use it in GitHub Desktop.
Save jthatch/921643103a7eca2c968222d166feea0f to your computer and use it in GitHub Desktop.
PHP Script to convert mp4's to mpeg using ffmpeg from the command line
<?php
/**
* Created by PhpStorm.
* User: jamest
* Date: 02/11/15
* Time: 10:14
*/
class Convert {
private $commandLine, $path;
private $command = "ffmpeg -y -i \"{input_file}\" -f mpeg1video -b:v 500k \"{output_file}\"";
private $regex = "/\\.mp4\$/i";
function __construct()
{
global $argv;
$this->commandLine = (php_sapi_name() == 'cli' || empty($_SERVER['REMOTE_ADDR']));
$this->path = $this->path ? $this->path : dirname(__FILE__);
if ($this->commandLine && sizeof($argv) > 1)
{
//$this->convert($argv[1]);
$this->setup($argv[1]);
}
}
public function setup($path = '')
{
$this->log("Scanning $path for mp4's");
try {
$dir = new DirectoryIterator($path);
}
catch (UnexpectedValueException $e)
{
$this->log("Error: {$e->getMessage()}");
die;
}
$it = new RegexIterator($dir, $this->regex);
$total = sizeof(iterator_to_array($it));
if ( $total < 1 )
{
$this->log("No files found regex {$this->regex}");
die;
}
$this->log("Found {$total} files matching regex {$this->regex}");
chdir($path);
$mpegs_dir = 'mpegs';
if ( !file_exists($mpegs_dir) )
mkdir($mpegs_dir);
$this->log("Creating mpegs directory");
foreach($it as $filename)
{
$this->convert($filename);
}
/*
drwxr-xr-x 3 root root 4096 Sep 29 06:36 .
drwx--xr-x 4 root root 4096 Sep 29 06:52 .
*/
}
public function convert($filename = '')
{
$file = pathinfo($filename);
$cmd = str_replace(
["{input_file}", "{output_file}"],
[$filename, './mpegs/' . $file['filename'] . '.mpg'],
$this->command
);
$this->log($cmd);
$log = exec($cmd, $val);
//echo $val;
//print_r($file);
}
private function log($msg)
{
echo $msg . "\n";
}
}
$convert = new Convert();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment