欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > python源码分享:视频srt字幕文件生成

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

2024/10/24 11:22:38 来源:https://blog.csdn.net/G541788_/article/details/140299579  浏览:    关键词: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 = 1for (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 timedeltadef 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 = 1for (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 += 1def generate_subtitles_from_last_five_seconds(video_file, output_file):clip = VideoFileClip(video_file)try:duration = clip.durationstart_time = max(0, duration - 5)end_time = durationtext = "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)

         这是项目结构:

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com