批量修改视频播放速度的脚本

wen 实用脚本 2

本文目录导读:

批量修改视频播放速度的脚本

  1. 方案1:使用 FFmpeg(推荐)
  2. 方案2:FFmpeg Shell 脚本(Linux/Mac)
  3. 方案3:Windows Batch 脚本
  4. 安装和使用说明

我来帮你创建一个批量修改视频播放速度的脚本,这里提供几个不同实现方式的脚本:

方案1:使用 FFmpeg(推荐)

批量处理脚本(Python)

#!/usr/bin/env python3
"""
批量修改视频播放速度脚本
支持:加速/减速,保持音频正常播放
"""
import os
import subprocess
import argparse
from pathlib import Path
def change_speed(input_file, output_file, speed, use_audio_pitch=True):
    """
    修改视频播放速度
    Args:
        input_file: 输入视频文件路径
        output_file: 输出视频文件路径
        speed: 速度倍数 (0.5-2.0)
        use_audio_pitch: 是否保持音频音调不变
    """
    # 视频和音频的滤镜参数
    video_filter = f"setpts={1/speed}*PTS"
    if use_audio_pitch:
        # 保持音调不变(使用 atempo)
        audio_filter = f"atempo={speed}"
    else:
        # 允许音调变化
        audio_filter = f"atempo={speed}"
    cmd = [
        'ffmpeg',
        '-i', input_file,
        '-filter_complex', f'{video_filter}[v];{audio_filter}[a]',
        '-map', '[v]', '-map', '[a]',
        '-c:v', 'libx264',
        '-preset', 'medium',
        '-crf', '23',
        '-c:a', 'aac',
        '-b:a', '128k',
        '-y',  # 覆盖已存在文件
        output_file
    ]
    try:
        subprocess.run(cmd, check=True, capture_output=True, text=True)
        print(f"✓ 处理完成: {input_file} -> {output_file}")
    except subprocess.CalledProcessError as e:
        print(f"✗ 处理失败: {input_file}")
        print(f"错误信息: {e.stderr}")
def process_directory(input_dir, output_dir, speed, use_audio_pitch=True):
    """
    批量处理目录中的所有视频文件
    Args:
        input_dir: 输入目录
        output_dir: 输出目录
        speed: 速度倍数
        use_audio_pitch: 是否保持音频音调不变
    """
    # 支持的视频格式
    video_extensions = {'.mp4', '.avi', '.mov', '.mkv', '.flv', '.wmv', '.webm'}
    # 创建输出目录
    output_path = Path(output_dir)
    output_path.mkdir(parents=True, exist_ok=True)
    # 遍历输入目录
    input_path = Path(input_dir)
    files = []
    for ext in video_extensions:
        files.extend(input_path.glob(f'*{ext}'))
        files.extend(input_path.glob(f'*{ext.upper()}'))
    if not files:
        print(f"在 {input_dir} 中未找到视频文件")
        return
    print(f"找到 {len(files)} 个视频文件")
    print(f"处理速度: {speed}x, 保持音调: {use_audio_pitch}")
    print("-" * 50)
    # 处理每个文件
    for file in files:
        output_file = output_path / f"{file.stem}_speed{str(speed).replace('.', '_')}x{file.suffix}"
        if output_file.exists():
            print(f"跳过已存在的文件: {output_file}")
            continue
        print(f"处理: {file.name}")
        change_speed(str(file), str(output_file), speed, use_audio_pitch)
def main():
    parser = argparse.ArgumentParser(description='批量修改视频播放速度')
    parser.add_argument('input_dir', help='输入视频目录路径')
    parser.add_argument('output_dir', help='输出视频目录路径')
    parser.add_argument('-s', '--speed', type=float, required=True, 
                       help='播放速度倍数 (0.25 - 4.0)')
    parser.add_argument('--no-pitch', action='store_true',
                       help='不保持音频音调(允许音调变化)')
    args = parser.parse_args()
    if args.speed < 0.25 or args.speed > 4.0:
        print("错误:速度倍数应在 0.25 到 4.0 之间")
        return
    use_audio_pitch = not args.no_pitch
    process_directory(args.input_dir, args.output_dir, 
                     args.speed, use_audio_pitch)
if __name__ == "__main__":
    main()

方案2:FFmpeg Shell 脚本(Linux/Mac)

#!/bin/bash
# batch_speed.sh - 批量修改视频速度的Shell脚本
# 使用方式:
# ./batch_speed.sh input_directory output_directory speed
INPUT_DIR="$1"
OUTPUT_DIR="$2"
SPEED="$3"
# 检查参数
if [ $# -ne 3 ]; then
    echo "使用方法: $0 input_dir output_dir speed"
    echo "示例: $0 ./videos ./fast_videos 2.0"
    exit 1
fi
# 创建输出目录
mkdir -p "$OUTPUT_DIR"
# 支持的视频格式
EXTENSIONS="mp4 avi mov mkv flv wmv webm"
# 计数器
processed=0
failed=0
echo "开始批量处理视频..."
echo "输入目录: $INPUT_DIR"
echo "输出目录: $OUTPUT_DIR"
echo "速度倍数: ${SPEED}x"
echo "=============================="
# 遍历所有支持的格式
for ext in $EXTENSIONS; do
    for file in "$INPUT_DIR"/*."$ext" "$INPUT_DIR"/*."${ext^^}"; do
        # 检查文件是否存在
        [ -f "$file" ] || continue
        filename=$(basename "$file")
        name="${filename%.*}"
        extension="${filename##*.}"
        output_file="$OUTPUT_DIR/${name}_${SPEED}x.${extension}"
        # 检查输出文件是否已存在
        if [ -f "$output_file" ]; then
            echo "跳过已存在的文件: $output_file"
            continue
        fi
        echo "处理: $filename"
        # FFmpeg命令
        ffmpeg -i "$file" \
               -filter_complex "[0:v]setpts=${SPEED}*PTS[v];[0:a]atempo=${SPEED}[a]" \
               -map "[v]" -map "[a]" \
               -c:v libx264 -preset medium -crf 23 \
               -c:a aac -b:a 128k \
               -y "$output_file" 2>/dev/null
        if [ $? -eq 0 ]; then
            echo "✓ 成功: $output_file"
            ((processed++))
        else
            echo "✗ 失败: $file"
            ((failed++))
        fi
    done
done
echo "=============================="
echo "处理完成!"
echo "成功: $processed 个文件"
echo "失败: $failed 个文件"

方案3:Windows Batch 脚本

@echo off
REM batch_speed.bat - Windows批量修改视频速度
setlocal enabledelayedexpansion
REM 检查FFmpeg是否安装
where ffmpeg >nul 2>nul
if %ERRORLEVEL% NEQ 0 (
    echo 错误:未找到FFmpeg,请先安装FFmpeg
    pause
    exit /b 1
)
REM 设置参数
set /p INPUT_DIR=请输入视频目录路径: 
set /p OUTPUT_DIR=请输入输出目录路径: 
set /p SPEED=请输入速度倍数(2.0): 
REM 创建输出目录
if not exist "%OUTPUT_DIR%" mkdir "%OUTPUT_DIR%"
echo 开始处理视频文件...
echo 输入目录: %INPUT_DIR%
echo 输出目录: %OUTPUT_DIR%
echo 速度倍数: %SPEED%
echo.
set processed=0
set failed=0
REM 遍历所有视频文件
for %%f in ("%INPUT_DIR%\*.mp4" "%INPUT_DIR%\*.avi" "%INPUT_DIR%\*.mov" "%INPUT_DIR%\*.mkv" "%INPUT_DIR%\*.flv") do (
    if exist "%%f" (
        set filename=%%~nxf
        set name=%%~nf
        set ext=%%~xf
        set "output_file=%OUTPUT_DIR%\!name!_%SPEED%x!ext!"
        if exist "!output_file!" (
            echo 跳过已存在的文件: !output_file!
        ) else (
            echo 处理: !filename!
            ffmpeg -i "%%f" ^
                   -filter_complex "[0:v]setpts=1/%SPEED%*PTS[v];[0:a]atempo=%SPEED%[a]" ^
                   -map "[v]" -map "[a]" ^
                   -c:v libx264 -preset medium -crf 23 ^
                   -c:a aac -b:a 128k ^
                   -y "!output_file!" 2>nul
            if !ERRORLEVEL! EQU 0 (
                echo ✓ 成功
                set /a processed+=1
            ) else (
                echo ✗ 失败
                set /a failed+=1
            )
        )
    )
)
echo.
echo 处理完成!
echo 成功: %processed% 个文件
echo 失败: %failed% 个文件
pause

安装和使用说明

安装 FFmpeg

Windows:

  • 下载 FFmpeg: https://ffmpeg.org/download.html
  • 添加到系统环境变量 PATH

Mac:

brew install ffmpeg

Linux:

sudo apt-get install ffmpeg  # Ubuntu/Debian
sudo yum install ffmpeg      # CentOS/RHEL

使用示例

Python 脚本:

# 安装依赖
pip install -r requirements.txt  # 不需要额外依赖
# 基本使用
python batch_speed.py ./input_videos ./output_videos -s 2.0
# 保持音调不变(默认)
python batch_speed.py ./input_videos ./output_videos -s 1.5
# 不保持音调
python batch_speed.py ./input_videos ./output_videos -s 2.0 --no-pitch

Shell 脚本:

# 添加执行权限
chmod +x batch_speed.sh
# 使用
./batch_speed.sh ./input_videos ./output_videos 2.0

常见速度推荐

  • 5x: 慢动作效果
  • 25x: 轻微加速(教学视频)
  • 5x: 适中加速
  • 0x: 快速浏览
  • 0x: 极速播放

注意事项

  1. 确保输出目录有足够磁盘空间
  2. 视频格式需要使用 FFmpeg 支持的格式
  3. 速度倍数建议在 0.25-4.0 之间
  4. 处理大文件可能需要较长时间

需要其他功能(如裁剪、合并等)或调整参数,可以告诉我!

抱歉,评论功能暂时关闭!