zoengjyutgaai / trim_audio.py
laubonghaudoi's picture
加入鹿鼎記音頻
8fcf91d
import os
import pysrt
from pydub import AudioSegment
def get_last_timestamp(srt_file):
"""Gets the end time of the last subtitle in an SRT file."""
try:
subs = pysrt.open(srt_file)
if subs:
return subs[-1].end.ordinal
except Exception as e:
print(f"Error reading SRT file: {srt_file}")
print(f"Error message: {e}")
return None
def trim_audio_files(srt_dir, audio_dir, output_dir):
"""Trims audio files based on the last timestamp in corresponding SRT files."""
os.makedirs(output_dir, exist_ok=True)
srt_files = sorted([f for f in os.listdir(srt_dir) if f.endswith('.srt')])
for srt_filename in srt_files:
srt_path = os.path.join(srt_dir, srt_filename)
last_timestamp = get_last_timestamp(srt_path)
if last_timestamp is None:
print(f"Could not get timestamp for {srt_filename}, skipping.")
continue
audio_filename = os.path.splitext(srt_filename)[0] + '.opus'
audio_path = os.path.join(audio_dir, audio_filename)
if not os.path.exists(audio_path):
print(f"Audio file not found: {audio_path}, skipping.")
continue
try:
print(f"Processing {audio_filename}...")
audio = AudioSegment.from_file(audio_path, format="opus")
trimmed_audio = audio[:last_timestamp]
output_path = os.path.join(output_dir, audio_filename)
trimmed_audio.export(output_path, format="opus")
print(f" -> Trimmed and saved to {output_path}")
except Exception as e:
print(f"Error processing {audio_path}: {e}")
if __name__ == "__main__":
SRT_DIRECTORY = "./srt/lukdinggei"
AUDIO_DIRECTORY = "./source/lukdinggei"
OUTPUT_DIRECTORY = "./source/lukdinggei_trimmed"
trim_audio_files(SRT_DIRECTORY, AUDIO_DIRECTORY, OUTPUT_DIRECTORY)
print(f"\nTrimming complete. Trimmed files are saved in '{OUTPUT_DIRECTORY}'.")