將字幕檔 (SRT/ASS) 燒錄進影片(硬字幕)可確保所有播放器正確顯示。本文示範使用 mencoder 燒錄字幕並轉碼為 MP4 的完整流程,含批次掃描目錄、縮圖生成與字幕樣式調整。
<?php
function burnSubtitle(string $video, string $subtitle, string $output): bool {
// mencoder 燒錄字幕並轉碼
// -sub $subtitle 載入字幕檔
// -subfont-text-scale 3.0 字體縮放
// -subpos 99 字幕位置 (99=底部)
// -af volume=10 音量增益
// -ovc x264 H.264 編碼
// -oac mp3lame MP3 音訊
$cmd = sprintf(
'mencoder %s -o %s -sub %s -subfont-text-scale 3.0 -subpos 99 -af volume=10 -aspect 16:9 -of avi -noodml -ovc x264 -x264encopts bitrate=500:level_idc=41:bframes=3:frameref=2:nopsnr:nossim:pass=1:threads=auto -oac mp3lame',
escapeshellarg($video),
escapeshellarg($output),
escapeshellarg($subtitle)
);
shell_exec($cmd);
return file_exists($output) && filesize($output) > 0;
}
?>
<?php
$dir = __DIR__ . '/videos';
$iterator = new DirectoryIterator($dir);
foreach ($iterator as $fileInfo) {
if (!$fileInfo->isFile()) continue;
if (!preg_match('/\.avi$/i', $fileInfo->getFilename())) continue;
$videoPath = $fileInfo->getPathname();
$base = $fileInfo->getBasename('.avi');
$subPath = $dir . '/' . $base . '.srt';
$idxPath = $dir . '/' . $base . '.idx'; // VobSub 索引檔(可選)
$thumbPath = $dir . '/' . $base . '.jpg';
$outPath = $dir . '/' . $base . '.mp4';
if (!file_exists($subPath)) {
echo "跳過 $base: 找不到字幕檔\n";
continue;
}
// 1. 先擷取縮圖
$thumbCmd = sprintf(
'ffmpeg -v 0 -y -i %s -vframes 1 -ss 250 -vcodec mjpeg -f rawvideo -s 286x160 -aspect 16:9 %s',
escapeshellarg($videoPath),
escapeshellarg($thumbPath)
);
shell_exec($thumbCmd);
// 2. 燒錄字幕轉碼
$burnCmd = sprintf(
'mencoder %s -o %s -sub %s -subfont-text-scale 3.0 -subpos 99 -af volume=10 -aspect 16:9 -of avi -noodml -ovc x264 -x264encopts bitrate=500:level_idc=41:bframes=3:frameref=2:nopsnr:nossim:pass=1:threads=auto -oac mp3lame',
escapeshellarg($videoPath),
escapeshellarg($outPath),
escapeshellarg($subPath)
);
shell_exec($burnCmd);
echo "處理完成: $base\n";
}
?>
<?php
function burnSubtitleFFmpeg(string $video, string $subtitle, string $output): bool {
// FFmpeg subtitles 濾鏡燒錄
// 需編譯 --enable-libass
$cmd = sprintf(
'ffmpeg -y -i %s -vf "subtitles=%s:force_style=\'FontSize=24,Outline=1\'" -c:v libx264 -preset medium -crf 23 -c:a aac -b:a 128k %s',
escapeshellarg($video),
escapeshellarg($subtitle),
escapeshellarg($output)
);
shell_exec($cmd);
return file_exists($output) && filesize($output) > 0;
}
?>
| 格式 | MEncoder | FFmpeg (libass) |
|---|---|---|
| SRT | ✅ | ✅ |
| ASS/SSA | ⚠️ 有限 | ✅ 完整支援樣式 |
| VobSub (idx/sub) | ✅ | ✅ |