FFMPEG - batch extracting media duration and writi

2019-02-20 05:41发布

问题:

I have ten media files in a folder. I want to create a text file containing two columns - filename and its duration (seconds):

video1.mp4|300 seconds 
video2.mp4|360 seconds 
video3.mp4|420 seconds 
... 
audio10.wav|120 seconds 

I did not find any similar question on the Web, so I don't have any hint of how to do this...

回答1:

Enumerate the media files and parse Duration: line in the output of ffmpeg -i:

@echo off
>output.txt (
    for %%F in (*.mpg *.mp4 *.mkv *.avi *.m4a *.flac *.mp3 *.wav) do (
        for /f "tokens=2-5 delims=:., " %%a in (
            'ffmpeg -i "%%F" 2^>^&1 ^| find "Duration:"'
        ) do (
            set /p =%%~nxF^|<nul
            setlocal enableDelayedExpansion
            set /a "duration=1%%a*3600 + 1%%b*60 + 1%%c - 366100"
            echo !duration!.%%d seconds
            endlocal
        )
    )
)
pause

With ffprobe (a part of ffmpeg package) the durations will have microsecond precision:

@echo off
>output.txt (
    for %%F in (*.mpg *.mp4 *.mkv *.avi *.m4a *.flac *.mp3 *.wav) do (
        for /f "tokens=2 delims==" %%a in (
            'ffprobe "%%F" -show_entries format^=duration -v quiet -of compact'
        ) do (
            echo %%~nxF^|%%a seconds
        )
    )
)
pause

Alternatively you can use a much faster MediaInfo CLI to output duration in milliseconds:

>output.txt "C:\Program Files (x86)\MediaInfo\MediaInfoCLI.exe" ^
    --output=General;%%FileName%%.%%FileExtension%%^|%%Duration%%\r\n ^
    *.mpg *.mp4 *.mkv *.avi *.m4a *.flac *.mp3 *.wav