如何用脚本自动给视频加字幕?

wen 实用脚本 2

本文目录导读:

如何用脚本自动给视频加字幕?

  1. 方法一:使用 Whisper + FFmpeg(推荐)
  2. 方法二:使用命令行工具
  3. 方法三:使用阿里云/腾讯云API
  4. 方法四:使用MoviePy(适合简单场景)
  5. 安装依赖
  6. 完整自动化脚本
  7. 批量处理脚本
  8. 注意事项

使用 Whisper + FFmpeg(推荐)

这个方案最成熟,支持多种语言:

# 方法1: Python脚本
import whisper
import subprocess
import os
def add_subtitles(video_path, output_path):
    # 1. 语音识别
    model = whisper.load_model("base")  # 可选: tiny, base, small, medium, large
    result = model.transcribe(video_path)
    # 2. 保存为SRT字幕文件
    srt_path = video_path.replace('.mp4', '.srt')
    with open(srt_path, 'w', encoding='utf-8') as f:
        for i, segment in enumerate(result['segments'], start=1):
            start = format_time(segment['start'])
            end = format_time(segment['end'])
            f.write(f"{i}\n{start} --> {end}\n{segment['text']}\n\n")
    # 3. 用FFmpeg嵌入字幕
    cmd = f'ffmpeg -i "{video_path}" -vf "subtitles={srt_path}" "{output_path}"'
    subprocess.run(cmd, shell=True)
def format_time(seconds):
    h = int(seconds // 3600)
    m = int((seconds % 3600) // 60)
    s = int(seconds % 60)
    ms = int((seconds - int(seconds)) * 1000)
    return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"
# 使用示例
add_subtitles("input.mp4", "output.mp4")

使用命令行工具

#!/bin/bash
# Linux/macOS 脚本
# 安装依赖
pip install openai-whisper ffmpeg-python
# 使用whisper命令行
whisper input.mp4 --model base --output_format srt
# 嵌入字幕到视频
ffmpeg -i input.mp4 -vf "subtitles=input.srt" output_with_sub.mp4

使用阿里云/腾讯云API

# 使用阿里云语音识别API
import json
import requests
from aliyunsdkcore.client import AcsClient
def add_subtitles_with_cloud(video_path):
    # 1. 上传音频到OSS
    # 2. 调用语音识别API
    # 3. 获取字幕结果
    # 4. 合成到视频
    pass

使用MoviePy(适合简单场景)

from moviepy.editor import VideoFileClip, TextClip, CompositeVideoClip
def add_simple_subtitles(video_path, subtitles_list):
    """
    subtitles_list: [(start_time, end_time, text), ...]
    """
    video = VideoFileClip(video_path)
    txt_clips = []
    for start, end, text in subtitles_list:
        txt_clip = TextClip(text, fontsize=24, color='white', 
                           font='simhei.ttf', stroke_color='black')
        txt_clip = txt_clip.set_position(('center', 'bottom')).set_duration(end-start).set_start(start)
        txt_clips.append(txt_clip)
    final = CompositeVideoClip([video] + txt_clips)
    final.write_videofile("output.mp4")

安装依赖

# 安装FFmpeg (Mac)
brew install ffmpeg
# 安装FFmpeg (Ubuntu)
sudo apt-get install ffmpeg
# 安装Python包
pip install openai-whisper ffmpeg-python moviepy

完整自动化脚本

#!/usr/bin/env python3
import os
import sys
import subprocess
import whisper
from pathlib import Path
class AutoSubtitle:
    def __init__(self, model_size="base"):
        self.model = whisper.load_model(model_size)
    def process_video(self, video_path, language=None):
        # 1. 转音频
        audio_path = video_path.replace('.mp4', '.wav')
        subprocess.run([
            'ffmpeg', '-i', video_path, 
            '-vn', '-acodec', 'pcm_s16le', 
            '-ar', '16000', '-ac', '1', audio_path
        ])
        # 2. 语音识别
        options = {}
        if language:
            options['language'] = language
        result = self.model.transcribe(audio_path, **options)
        # 3. 生成SRT
        srt_path = video_path.replace('.mp4', '.srt')
        self._save_srt(result, srt_path)
        # 4. 嵌入字幕
        output_path = video_path.replace('.mp4', '_subtitled.mp4')
        subprocess.run([
            'ffmpeg', '-i', video_path,
            '-vf', f"subtitles={srt_path}",
            '-c:a', 'copy', output_path
        ])
        # 清理临时文件
        os.remove(audio_path)
        return output_path
    def _save_srt(self, result, srt_path):
        with open(srt_path, 'w', encoding='utf-8') as f:
            for i, segment in enumerate(result['segments'], 1):
                start = self._format_time(segment['start'])
                end = self._format_time(segment['end'])
                f.write(f"{i}\n{start} --> {end}\n{segment['text'].strip()}\n\n")
    def _format_time(self, seconds):
        h = int(seconds // 3600)
        m = int((seconds % 3600) // 60)
        s = int(seconds % 60)
        ms = int((seconds - int(seconds)) * 1000)
        return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"
# 使用
if __name__ == "__main__":
    subtitle = AutoSubtitle("base")
    output = subtitle.process_video("input.mp4", language="zh")
    print(f"字幕已添加到: {output}")

批量处理脚本

#!/bin/bash
# 批量处理所有MP4文件
for video in *.mp4; do
    echo "处理: $video"
    python3 -c "
import auto_subtitle
s = auto_subtitle.AutoSubtitle()
s.process_video('$video')
"
done

注意事项

  1. 模型选择tiny最快但准确度较低,large最准确但需要更多资源
  2. GPU加速:如果有NVIDIA GPU,加上--device cuda
  3. 语言指定:中文视频加--language zh
  4. 字幕样式:可以通过FFmpeg的subtitles滤镜调整样式

这个方案最适合中文视频,准确度能达到90%以上。

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