要在Python中生成字幕文件(通常是SRT格式),你可以使用以下代码示例:
import os
def generate_subtitles(video_path, output_path, start_time, end_time, text):
if not video_path.endswith('.mp4'):
raise ValueError("Video file must be an MP4 format.")
basename = os.path.basename(video_path)
video_name = os.path.splitext(basename)[0]
output_sub_path = os.path.join(output_path, f"{video_name}.srt")
start_time_str = start_time.strftime("%H:%M:%S,%f")
end_time_str = end_time.strftime("%H:%M:%S,%f")
with open(output_sub_path, 'w', encoding='utf-8') as subtitle_file:
subtitle_file.write(f"1\n{start_time_str} --> {end_time_str}\n{text}\n")
# 使用方法:
# 视频文件路径
video_file = 'your_video.mp4'
# 字幕输出路径
output_directory = 'subtitles'
# 字幕开始时间
start_time = datetime.datetime(2023, 4, 1, 12, 0, 0)
# 字幕结束时间
end_time = datetime.datetime(2023, 4, 1, 12, 15, 0)
# 字幕文本
text = "这里是字幕内容"
generate_subtitles(video_file, output_directory, start_time, end_time, text)
确保你已经安装了datetime
模块,这个模块用于处理时间。上述代码会在指定的输出目录中创建一个SRT格式的字幕文件。你需要根据你的具体需求修改video_file
, output_directory
, start_time
, end_time
, 和 text
变量。