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)

这是项目结构:

相关推荐
亿牛云爬虫专家20 分钟前
优化数据的抓取规则:减少无效请求
python·数据采集·多线程·爬虫代理·数据抓取·代理ip·房价
程序媛堆堆22 分钟前
解决NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+问题
python
中关村科金23 分钟前
中关村科金推出得助音视频鸿蒙SDK,助力金融业务系统鸿蒙化提速
华为·音视频·harmonyos
DreamByte24 分钟前
Python Tkinter小程序
开发语言·python·小程序
Python极客之家26 分钟前
基于深度学习的眼部疾病检测识别系统
人工智能·python·深度学习·毕业设计·卷积神经网络
Bigcrab__32 分钟前
Python3网络爬虫开发实战(15)Scrapy 框架的使用(第一版)
爬虫·python·scrapy
DisonTangor1 小时前
上海人工智能实验室开源视频生成模型Vchitect 2.0 可生成20秒高清视频
人工智能·音视频
美狐美颜sdk1 小时前
探索视频美颜SDK与直播美颜工具的开发实践方案
人工智能·计算机视觉·音视频·直播美颜sdk·视频美颜sdk
易辰君1 小时前
Python编程 - 协程
开发语言·python
宇宙第一小趴菜2 小时前
探索网络世界:TCP/IP协议、Python Socket编程及日常生活比喻
网络·python·tcp/ip