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)

这是项目结构:

相关推荐
HAPPY酷1 分钟前
构建即自由:一份为创造者设计的 Windows C++ 自动化构建指南
开发语言·c++·ide·windows·python·策略模式·visual studio
瑶池酒剑仙3 分钟前
Libvio.link爬虫技术解析大纲
爬虫·python
喵手9 分钟前
Python爬虫实战:构建 Steam 游戏数据库:requests+lxml 实战游戏列表采集与价格监控(附JSON导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集steam商店游戏列表数据·sqlite数据库存放采集数据·价格监控游戏推荐市场分析
老蒋每日coding19 分钟前
LangGraph:从入门到Multi-Agent超级智能体系统进阶开发
开发语言·python
岚天start29 分钟前
Python HTTP服务器添加简单用户名密码认证的三种方案
服务器·python·http
cuber膜拜38 分钟前
Weaviate 简介与基本使用
数据库·python·docker·向量数据库·weaviate
HealthScience43 分钟前
DNA具体怎么转为蛋白质的?
python
知秋一叶1231 小时前
Miloco v0.1.6 :米家摄像头清晰度配置 + RTSP 音频传输
人工智能·音视频·智能家居
PacosonSWJTU1 小时前
mac-python解释器理解与python安装
开发语言·python
urkay-1 小时前
Android 中实现 HMAC-SHA256
android·开发语言·python