首先需要安装FFmpeg,Windows系统下需要将FFmpeg的bin加入环境变量。

Windows下的批处理代码如下:

@echo off & setlocal enabledelayedexpansion
set "s1=00:00:36"
set "s2=00:00:31"
for /f "tokens=1-4delims=:." %%a in ("%s2%") do (
    set /a "t2=(1%%a %% 100 *3600 + 1%%b %% 100 * 60 + 1%%c %% 100) * 1000 + 1%%d %% 1000"
)

md NEW 2>nul
for %%i in (*.avi *.mkv *.mp4 *.flv *.m4a) do (
    for /f "tokens=2-5delims=:., " %%a in ('ffmpeg -i "%%i" 2^>^&1 ^| find "Duration:"') do (
        set /a "t=(1%%a%%100*3600+1%%b%%100*60+1%%c%%100)*1000+1%%d0%%1000,t-=t2,ms=t%%1000,t/=1000"
        set /a h=t/3600,m=t%%3600/60,s=t%%60,h+=100,m+=100,s+=100,ms+=1000
        set "t=!h:~1!:!m:~1!:!s:~1!.!ms:~1!"
        ffmpeg -i "%%i" -ss !s1! -to !t! -vcodec copy -acodec copy "NEW\%%i" -y
    )
)
pause

Linux下的Bash代码如下:

#!/bin/bash
ss=00:01:00
minus=00:02:00
h1=$(echo $minus | cut -f1 -d:)
m1=$(echo $minus | cut -f2 -d:)
s1=$(echo $minus | cut -f3 -d:)
t1=$(( $h1 * 3600 + $m1 * 60 + $s1 ))

for i in *mp4
do
duration=$(ffmpeg -i "$i" 2>&1|grep Duration|cut -d ' ' -f 4 |sed s/,//)
h2=$(echo $duration |cut -f1 -d:)
m2=$(echo $duration |cut -f2 -d:)
s2=$(echo $duration |cut -f3 -d:)
t2=$(( $h2 * 3600 + $m2 * 60 + ${s2%.*} ))
to=$(( $t2 - $t1 ))
ffmpeg -i "$i" -ss $ss -to $to -c copy ~/"$i"
done