python源码分享:视频srt字幕文件生成

前言

最近有个项目需要使用srt字幕,我通过数分钟了解了它,并快速使用python完成了这一功能,现在分享此源码:

1、已知目标时间段的srt弹幕文件生成

2、自动识别视频的最后五秒钟,并添加提示弹幕

已知目标时间段的srt弹幕文件生成

复制代码
def generate_srt(subtitles, filename):
    """
    Generate .srt subtitle file from a list of tuples (start_time, end_time, text).

    Parameters:
    - subtitles: List of tuples in the format (start_time, end_time, text).
    - filename: Name of the output .srt file.
    """
    with open(filename, 'w', encoding='utf-8') as f:
        count = 1
        for (start_time, end_time, text) in subtitles:
            f.write(f"{count}\n")
            f.write(f"{start_time} --> {end_time}\n")
            f.write(f"{text}\n\n")
            count += 1


# Example usage:
subtitles = [
    ("00:00:01,000", "00:00:05,000", "Hello, world!"),
    ("00:00:10,000", "00:00:15,000", "This is a subtitle example."),
    ("00:00:20,000", "00:00:25,000", "Feel free to modify and use this script."),
]

generate_srt(subtitles, "srt/output.srt")

自动识别视频的最后五秒钟,并添加提示弹幕

复制代码
import os
from moviepy.video.io.VideoFileClip import VideoFileClip
from datetime import timedelta


def generate_srt(subtitles, filename):
    """
    Generate .srt subtitle file from a list of tuples (start_time, end_time, text).

    Parameters:
    - subtitles: List of tuples in the format (start_time, end_time, text).
    - filename: Name of the output .srt file.
    """
    with open(filename, 'w', encoding='utf-8') as f:
        count = 1
        for (start_time, end_time, text) in subtitles:
            f.write(f"{count}\n")
            f.write(f"{start_time} --> {end_time}\n")
            f.write(f"{text}\n\n")
            count += 1


def generate_subtitles_from_last_five_seconds(video_file, output_file):
    clip = VideoFileClip(video_file)
    try:
        duration = clip.duration
        start_time = max(0, duration - 5)
        end_time = duration
        text = "Subtitle text for the last five seconds."

        subtitles = [(format_timedelta(start_time), format_timedelta(end_time), text)]
        generate_srt(subtitles, output_file)
    finally:
        clip.close()  # 显式关闭视频文件处理


def format_timedelta(seconds):
    """
    Format seconds into HH:MM:SS,mmm format.
    """
    td = timedelta(seconds=seconds)
    mm, ss = divmod(td.seconds, 60)
    hh, mm = divmod(mm, 60)
    return f"{hh:02}:{mm:02}:{ss:02},000"


# srt字幕存储目录
srt_dir = 'srt/video'

# 视频存放目录
video_dir = 'F:\视频素材'

for root, dirs, files in os.walk(video_dir):
    for file in files:
        video_path = os.path.join(root, file)

        # 检测是否是MP4格式,并生成同名的srt字幕
        video_name, file_ext = os.path.splitext(file)
        if file_ext == '.mp4':
            output_file = f"srt/video/{video_name}.srt"
            print(video_path, output_file)
            generate_subtitles_from_last_five_seconds(video_path, output_file)

这是项目结构:

相关推荐
用户4093792713685 分钟前
并发编程
python
Eugene__Chen18 分钟前
java IO/NIO/AIO
java·python·nio
满怀101519 分钟前
【Python核心库实战指南】从数据处理到Web开发
开发语言·前端·python
北漂程序员学习1 小时前
如何避免被目标网站识别为爬虫?
爬虫·python·scrapy·flask·scipy
纪元A梦1 小时前
华为OD机试真题——数据分类(2025A卷:100分)Java/python/JavaScript/C++/C语言/GO六种最佳实现
java·javascript·c++·python·华为od·go·华为od机试题
EasyGBS1 小时前
室外摄像头异常自检指南+视频监控系统EasyCVR视频质量诊断黑科技
大数据·人工智能·音视频
Conan х1 小时前
第1 篇:你好,时间序列!—— 开启时间数据探索之旅
人工智能·python·神经网络·机器学习·信息可视化
AI糊涂是福1 小时前
详细的PyCharm安装教程
ide·python·pycharm
站大爷IP1 小时前
Python中__init__方法的深度解析:构造对象的艺术
python
~在杰难逃~2 小时前
DB-Day10笔记-数据库事务问题补充&Python与MySQL的交互
数据库·笔记·python