Skip to content

Instantly share code, notes, and snippets.

@m4tthumphrey
Last active September 5, 2020 07:17
Show Gist options
  • Save m4tthumphrey/a863aa64dd541cfb4472 to your computer and use it in GitHub Desktop.
Save m4tthumphrey/a863aa64dd541cfb4472 to your computer and use it in GitHub Desktop.
php-ffmpeg concat audio filter - an incredibly simple filter to concat multiple audio files together. Should be easily tweaked to allow for videos too.
<?php
use FFMpeg\Media\Audio;
use FFMpeg\Format\AudioInterface;
use FFMpeg\Filters\Audio\AudioFilterInterface;
class ConcatAudioFilter implements AudioFilterInterface
{
private $files;
private $priority;
public function __construct(array $files = [], $priority = 0)
{
$this->files = $files;
$this->priority = $priority;
}
/**
* {@inheritdoc}
*/
public function getPriority()
{
return $this->priority;
}
public function addFile($file)
{
$this->files[] = $file;
return $this;
}
public function addFiles(array $files)
{
foreach ($files as $file) {
$this->addFile($file);
}
return $this;
}
public function deleteFile($fileToDelete)
{
$this->files = array_values(array_filter($this->files, function($file) use ($fileToDelete) {
return $fileToDelete !== $file;
}));
}
/**
* {@inheritdoc}
*/
public function apply(Audio $audio, AudioInterface $format)
{
$params = [];
$count = count($this->files) + 1;
foreach ($this->files as $i => $file) {
$params[] = '-i';
$params[] = $file;
}
$params[] = '-filter_complex';
$params[] = 'concat=n='.$count.':v=0:a=1 [a]';
$params[] = '-map';
$params[] = '[a]';
return $params;
}
}
<?php
$ffmpeg = FFMpeg\FFMpeg::create();
$audio = $ffmpeg->open('file1.mp3');
$filter = new ConcatAudioFilter();
$filter->addFiles([
'file_to_append1.mp3',
'file_to_append2.mp3'
]);
$format = new FFMpeg\Format\Audio\Mp3();
$audio->addFilter($filter);
$audio->save($format, 'output.mp3');
@guivazcabral
Copy link

Hi 😄
I tried to tweak this filter to apply to video but I doesn't work. It says
Class 'ConcatVideoFilter' not found
I edited your code and put the file in the video filters folder, as shown here: http://imgur.com/9olFY5T

What am I doing wrong?

EDIT: Same thing happens if I don't change your code at all and put the file in the audio filters folder.

EDIT2: I made it. A few bit changes in the code and I was able to apply your code to concatenate two video files. Forked.

@jack-fdrv
Copy link

The best!
Thank you!

Any idea how to show progress? =)

@Write
Copy link

Write commented May 21, 2016

Hey @guivazcabral, would it mind you to help me with that, i'm trying too, to concatenate videos :/
Thanks !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment