首页 > 解决方案 > 使用 ffmpeg 合并多个视频和音频

问题描述

我已经使用程序youtube-dl下载了一个 Youtube 播放列表,我选择单独下载视频和音频,我现在有一个文件夹,里面有我希望与 ffmpeg 合并的视频及其相应的音频。

我需要使用批处理脚本来执行此操作,但问题是 youtube-dl 在原始文件的标题之后添加了随意的字母,因此视频与其相应的音频名称不同,文件名如下所示:

First title in the playlist 5J34JG.mp4
First title in the playlist H3826D.webm
Second title in the playlist 3748JD.mp4
Second title in the playlist 6SHJFZ.webm

如何使用 Windows 批处理脚本和 ffmpeg 合并这些多个视频/音频文件?

编辑:我忘了提到 .webm 文件是音频文件,我有多个文件,我不能一个一个地重命名它们。

标签: batch-fileffmpegvideo-processing

解决方案


@echo off
setlocal

set "outdir=muxed"
if not exist "%outdir%" md "%outdir%" || exit /b 1

:: Get each mp4 file and call the label to mux with webm file.
for %%A in (*.mp4) do call :mux "%%~A"
exit /b

:mux
setlocal
set "videofile=%~1"
set "name=%~n1"

:: Last token of the name is the pattern to remove.
for %%A in (%name:-=- %) do set "pattern=-%%~A"

:: Remove the pattern from the name.
call set "name=%%name:%pattern%=%%"

:: Get the webm filename.
for %%A in ("%name%-*.webm") do set "audiofile=%%~A"

:: Mux if webm file exist and output file does not exist.
if exist "%audiofile%" if not exist "%outdir%\%name%.mp4" (
    ffmpeg -i "%videofile%" -i "%audiofile%" -c copy "%outdir%\%name%.mkv"
)
exit /b

该脚本将首先创建输出目录以保存 mp4 文件,以便输出不会成为输入。

for循环将获取每个 mp4 文件名。使用:mux mp4 文件名作为参数调用标签。

变量videofile存储 mp4 文件名,变量name仅存储不带扩展名的名称。

的最后一个标记name将是YTID模式,而 for循环会将最后一个标记设置为pattern.

call set用名称中的“”替换模式。这将给出一个可以与通配符一起使用以查找 webm 文件名的名称。for循环将获取 webm 文件名。

如果目标确实存在而不是输出文件,则 ffmpeg 会将 2 个文件混合到一个输出文件中。

输出文件容器格式为 mkv。


推荐阅读