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)

这是项目结构:

相关推荐
xiao5kou4chang6kai44 分钟前
Python-GEE遥感云大数据分析与可视化(如何建立基于云计算的森林监测预警系统)
python·数据分析·云计算·森林监测·森林管理
presenttttt11 分钟前
用Python和OpenCV从零搭建一个完整的双目视觉系统(四)
开发语言·python·opencv·计算机视觉
木头左3 小时前
逻辑回归的Python实现与优化
python·算法·逻辑回归
quant_19864 小时前
R语言如何接入实时行情接口
开发语言·经验分享·笔记·python·websocket·金融·r语言
失败又激情的man9 小时前
python之requests库解析
开发语言·爬虫·python
打酱油的;9 小时前
爬虫-request处理get
爬虫·python·django
开开心心_Every10 小时前
便捷的电脑自动关机辅助工具
开发语言·人工智能·pdf·c#·电脑·音视频·sublime text
用什么都重名11 小时前
MinerU:高效智能PDF文档解析工具完全指南
人工智能·python·pdf·mineru·makedown
倔强青铜三11 小时前
苦练Python第4天:Python变量与数据类型入门
前端·后端·python
这我可不懂11 小时前
Python 项目快速部署到 Linux 服务器基础教程
linux·服务器·python