监控视频片段合并完整视频|FFmpeg将多个视频片段拼接完整视频|PHP自动批量拼接合并视频

本文介绍了一个PHP脚本,用于在服务器上批量使用FFmpeg将B站视频(M4S格式)转换为MP4,并管理缓存文件。脚本遍历指定目录,对每个文件夹中的M4S文件进行转码,并生成list.txt文件记录转换过程。
摘要由CSDN通过智能技术生成

关于环境配置ffmpeg安装使用的看之前文章 哔哩哔哩缓存转码|FFmpeg将m4s文件转为mp4|PHP自动批量转码B站视频

<?php
date_default_timezone_set("PRC");
header("Content-type: text/html; charset=utf-8");
set_time_limit(0);

// 遍历获取文件
function getDirFile($path = null, $deep = true)
{
    if (empty($path)) {
        return [];
    }
    $files = scandir($path);
    $fileItem = [];
    foreach ($files as $v) {
        $newPath = $path . DIRECTORY_SEPARATOR . $v;
        if ($deep && is_dir($newPath) && $v != '.' && $v != '..') {
            if (is_numeric($deep)) {
                $deep--;
            }
            $fileItem = array_merge($fileItem, getDirFile($newPath, $deep));
        } else if (is_file($newPath)) {
            $fileItem[] = $newPath;
        }
    }
    return $fileItem;
}

// 遍历获取文件夹
function getDir($path = null, $deep = true)
{
    if (empty($path)) {
        return [];
    }
    $files = scandir($path);
    $dirList = [];
    foreach ($files as $v) {
        $newPath = $path . DIRECTORY_SEPARATOR . $v;
        if (is_dir($newPath) && $v != '.' && $v != '..') {
            $dirList[] = $newPath;
            if ($deep) {
                if (is_numeric($deep)) {
                    $deep--;
                }
                $dirList = array_merge($dirList, getDir($newPath, $deep));
            }
        }
    }
    return $dirList;
}

//判断文件夹是否存在,没有则新建。
if (!function_exists('mkdirs')) {
    function mkdirs($dir, $mode = 0777)
    {
        if (is_dir($dir) || @mkdir($dir, $mode)) {
            return true;
        }
        if (!mkdirs(dirname($dir), $mode)) {
            return false;
        }
        return @mkdir($dir, $mode);
    }
}

// 删除指定文件
function deleteFile($filename)
{
    // 检查文件是否存在
    if (file_exists($filename)) {
        // 尝试删除文件
        if (unlink($filename)) {
            return null;
        } else {
            return "文件删除失败";
        }
    } else {
        return "文件不存在";
    }
}

/**
 * 操作文件夹
 * addtime 2020年7月17日
 * @param [type] $dirname 文件夹路径
 * @param boolean $self  是否删除文件夹本身[true是 false否] 具体看需求
 * @return void
 */
function do_rmdir($dirname, $self = false)
{
    # 检查文件或目录是否存在
    if (!file_exists($dirname)) {
        return false;
    }
    # 是文件进行删除
    if (is_file($dirname) || is_link($dirname)) {
        return unlink($dirname);
    }
    # 开始读取目录
    $dir = dir($dirname);
    if ($dir) {
        while (false !== $entry = $dir->read()) {
            if ($entry == '.' || $entry == '..') {
                continue;
            }
            # 进行文件删除
            do_rmdir($dirname . '/' . $entry);
        }
    }
    # 关闭目录
    $dir->close();
    # 是否删除本身文件夹
    $self && rmdir($dirname);
    # 成功返回
    return ['code' => 200];
}

// 命令参数字段映射
$cmdFiledMap = array(
    'P' => 'path',
    'D' => 'debug',
    'H' => 'help',
);
// 命令行参数变量
$console = array();
if (preg_match_all('/--(\w+)(=(.*?)(?=\s--|$))?/u', implode(' ', array_slice($_SERVER['argv']/*获取命令行参数的完整字符串*/, 1)), $matches)) {
    $console = [];
    for ($i = 0; $i < count($matches[0]); $i++) {
        $key = $matches[1][$i];
        $value = $matches[3][$i];
        $console[$key] = $value;
    }
    foreach ($cmdFiledMap as $key => $item) {
        if (isset($console[$key])) {
            if (empty($console[$item]) && !empty($console[$key])) {
                $console[$item] = $console[$key];
            }
            unset($console[$key]);
        }
    }
}
// 判断是否要获取使用方法
if (empty($console) || isset($console['help']) || empty($console['path'])) {
    $errMsg = array(
        'help:',
        '  as => php index.php --path=your_resource_path --debug=0',
        'OR',
        '  as => php index.php --F=your_resource_path --D=1',
        '',
        '',
    );
    die(implode(PHP_EOL . PHP_EOL, $errMsg));
}

$outputDir = dirname(__FILE__) . DIRECTORY_SEPARATOR . $console['path'] . 'Mp4';
do_rmdir($outputDir, true);
mkdirs($outputDir);
$isDebug = !empty($console['debug']);

$list = getDir($console['path'], false);
if (empty($list)) {
    die(PHP_EOL . '空文件夹。。。');
}
$startTime = time();
foreach ($list as $key => $item) {
    $itemDirName = basename($item); // 目录名
    $fileList = getDirFile($item);
    $listText = array();
    foreach ($fileList as $keyx => $itemx) {
        $itemxInfo = pathinfo($itemx);
        $midifyTime = filemtime($itemx); // 最后一次修改时间

        $ext = $itemxInfo['extension'];
        if ($ext == 'mp4') {
            $listText[$midifyTime] = "file '" . basename($itemx) . "'";
        }
    }
    ksort($listText);
    $listTextPath = $item . DIRECTORY_SEPARATOR . 'list.txt';
    file_put_contents($listTextPath, implode(PHP_EOL, $listText));
    $outputFileName = $outputDir . DIRECTORY_SEPARATOR . $itemDirName . '.mp4';
    $cmd = "ffmpeg " . ($isDebug ? "" : "-loglevel quiet") . " -f concat -safe 0 -i {$listTextPath} -c copy {$outputFileName}";
    echo $cmd . PHP_EOL;
    shell_exec($cmd); // cmd可执行
    // 删除list.txt 临时文件
    deleteFile($listTextPath);
}

echo PHP_EOL . '处理完成, 耗时:' . (time() - $startTime) . '秒';

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值