zoengjyutgaai / trim_mp3_m4a.py
laubonghaudoi's picture
加入鹿鼎記音頻
8fcf91d
print("--- SCRIPT EXECUTION STARTED ---")
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)
audio_files = sorted([f for f in os.listdir(audio_dir) if f.endswith(('.mp3', '.m4a'))])
for audio_filename in audio_files:
basename = os.path.splitext(audio_filename)[0]
srt_filename = basename + '.srt'
srt_path = os.path.join(srt_dir, srt_filename)
if not os.path.exists(srt_path):
print(f"SRT file not found for {audio_filename}, skipping.")
continue
last_timestamp = get_last_timestamp(srt_path)
if last_timestamp is None:
print(f"Could not get timestamp from {srt_filename}, skipping.")
continue
audio_path = os.path.join(audio_dir, audio_filename)
try:
print(f"Processing {audio_filename}...")
# Determine the format from the file extension
file_format = os.path.splitext(audio_filename)[1][1:]
audio = AudioSegment.from_file(audio_path, format=file_format)
trimmed_audio = audio[:last_timestamp + 500]
output_path = os.path.join(output_dir, audio_filename)
trimmed_audio.export(output_path, format=file_format)
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/鹿鼎記mp3"
OUTPUT_DIRECTORY = "source/lukdinggei_trimmed_mp3"
trim_audio_files(SRT_DIRECTORY, AUDIO_DIRECTORY, OUTPUT_DIRECTORY)
print(f"\nTrimming complete. Trimmed files are saved in '{OUTPUT_DIRECTORY}'.")