laubonghaudoi's picture
重構並增加水滸傳 1-40 集數據
69d51ce
import csv
import os
import pysrt
from pydub import AudioSegment
def srt_to_segments_with_metadata(srt_file, episode, audio_file, output_dir, metadata_file):
# Load the SRT file
subs = pysrt.open(srt_file)
# Load the audio file
audio = AudioSegment.from_wav(audio_file)
# Ensure the output directory exists
os.makedirs(output_dir, exist_ok=True)
# Prepare the metadata file
with open(metadata_file, mode='a', newline='', encoding='utf-8') as csvfile:
csvwriter = csv.writer(csvfile)
# csvwriter.writerow(['id', 'episode_id', 'file_name', 'audio_duration',
# 'transcription'])
for index, sub in enumerate(subs):
# Get start and end times in milliseconds
start_time = sub.start.ordinal
end_time = sub.end.ordinal
# Calculate duration in seconds
duration = (end_time - start_time) / 1000
# Extract the audio segment
segment = audio[start_time:end_time]
# Define output filenames
segment_filename = f"{episode}_{index + 1:03d}.wav"
segment_id = f"{episode}_{index + 1:03d}"
audio_filename = os.path.join(output_dir, segment_filename)
# Export the audio segment
segment.export(audio_filename, format="wav")
# Write to the metadata CSV file
csvwriter.writerow(
[segment_id, episode, f'{episode}/{segment_filename}', f'{duration:.3f}', sub.text])
print("Segmentation complete. Files saved to:", output_dir)
print("Metadata saved to:", metadata_file)
if __name__ == "__main__":
# subset = "saamgwokjinji"
subset = "seoiwuzyun"
# ffmpeg -i "webm/saamgwokjinji/034.webm" -vn -ar 44100 -c:a pcm_s16le "034.wav"
for episode in range(1, 41):
episode = f'{episode:03d}'
srt_file = f'srt/{subset}/{episode}.srt'
audio_file = f'{episode}.wav'
output_dir = f'wav/{subset}/{episode}'
srt_to_segments_with_metadata(
srt_file, episode, audio_file, output_dir, f'{episode}.csv')