You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP实现FFmpeg转码进度百分比获取的技术问询

Solution for Tracking FFmpeg Transcode Progress Percentage in PHP

Let's break this down step by step to enhance your existing scripts and get accurate progress percentages without changing core terminology or code structure.

1. Update ffmpeg.php for Structured Progress Output

Your original command redirects output to progress.txt, but FFmpeg's default console logs aren't ideal for parsing progress. Instead, use FFmpeg's built-in -progress flag to write machine-readable, key-value progress data directly to your log file. This keeps your core execution logic intact while making parsing far simpler:

<?php
$image = "input.jpg"; // Replace with your actual image path
$music = "audio.mp3"; // Replace with your actual audio path

// Modified command to use FFmpeg's progress flag for structured log output
$sCmd = "ffmpeg -i ".$image." -i ".$music." -progress progress.txt video.avi";
$proc = popen($sCmd, "r");

// Keep the process running and capture any additional console output if needed
while (!feof($proc)) {
    fgets($proc);
}
pclose($proc);
?>

Note: The -progress flag tells FFmpeg to write real-time updates like total_duration and out_time to the specified file in a clean, parsable format—way better than sifting through raw console output.

2. Enhance progress.php to Calculate Progress Percentage

Now we'll read progress.txt, extract the critical timing values, and compute the progress percentage. Here's the refined script:

<?php
$progressFile = "progress.txt";

if (file_exists($progressFile)) {
    $logContent = file_get_contents($progressFile);
    $lines = explode("\n", $logContent);
    
    $totalDuration = 0;
    $currentTime = 0;
    
    // Parse each line to pull total video duration and current processed time
    foreach ($lines as $line) {
        $line = trim($line);
        if (str_starts_with($line, "total_duration=")) {
            $totalDuration = floatval(str_replace("total_duration=", "", $line));
        } elseif (str_starts_with($line, "out_time=")) {
            // Convert FFmpeg's HH:MM:SS.sss time format to total seconds
            $timeStr = str_replace("out_time=", "", $line);
            $currentTime = convertFFmpegTimeToSeconds($timeStr);
        }
    }
    
    // Calculate and display progress (cap at 100% to avoid edge-case inconsistencies)
    if ($totalDuration > 0 && $currentTime > 0) {
        $progressPercentage = min(round(($currentTime / $totalDuration) * 100, 2), 100);
        echo "Transcode Progress: {$progressPercentage}%";
    } else {
        echo "Transcode starting...";
    }
} else {
    echo "Progress file not found. Ensure the FFmpeg process is running.";
}

// Helper function to convert FFmpeg's time string to a numeric second value
function convertFFmpegTimeToSeconds($timeStr) {
    list($hours, $minutes, $seconds) = explode(":", $timeStr);
    return ($hours * 3600) + ($minutes * 60) + floatval($seconds);
}
?>

Key Details:

  • Structured Log Parsing: The -progress output gives us explicit total_duration (total video length in seconds) and out_time (current processed time in human-readable format).
  • Time Conversion: The convertFFmpegTimeToSeconds helper translates FFmpeg's formatted time into a numeric value we can use for percentage calculations.
  • Safe Calculation: Using min(..., 100) ensures we never display over 100% progress, even if log data has minor inconsistencies during transcode.

How It Works Together

  1. When ffmpeg.php runs, FFmpeg writes real-time progress updates to progress.txt.
  2. You can call progress.php (via AJAX for live updates, or a page refresh loop) to read the log, parse the values, and display the current transcode percentage.

内容的提问来源于stack exchange,提问作者Mr.ZZ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:17:12