esl-dialogue-tts / utils /merge_audio.py
abocha's picture
fix
b26f1ff
raw
history blame
3.95 kB
from pydub import AudioSegment
import os
def merge_mp3_files(file_paths, output_filename, pause_ms=500):
"""
Merges multiple MP3 files into a single MP3 file with a specified pause
between each segment.
"""
if not file_paths:
return None
combined = AudioSegment.empty()
pause_segment = AudioSegment.silent(duration=pause_ms) if pause_ms > 0 else AudioSegment.empty()
for i, file_path in enumerate(file_paths):
if not os.path.exists(file_path) or os.path.getsize(file_path) == 0:
print(f"Warning: File {file_path} is missing or empty. Skipping.")
continue
try:
segment = AudioSegment.from_mp3(file_path)
combined += segment
if i < len(file_paths) - 1: # Don't add pause after the last segment
combined += pause_segment
except Exception as e:
print(f"Error processing file {file_path}: {e}. Skipping.")
continue
if len(combined) == 0:
print("No valid audio segments found to merge.")
return None
try:
combined.export(output_filename, format="mp3")
return output_filename
except Exception as e:
print(f"Error exporting merged MP3 to {output_filename}: {e}")
return None
if __name__ == '__main__':
# Create dummy mp3 files for testing (requires ffmpeg to be installed and pydub)
# This test assumes you have some small MP3s or can generate them.
# For a self-contained test, you might need to generate silent MP3s.
print("This script is intended to be used as a module.")
print("To test, ensure you have some MP3 files and call merge_mp3_files directly.")
# Example:
# create_dummy_mp3("dummy1.mp3", duration_ms=1000)
# create_dummy_mp3("dummy2.mp3", duration_ms=1500)
# merge_mp3_files(["dummy1.mp3", "dummy2.mp3"], "merged_output.mp3", pause_ms=200)
# os.remove("dummy1.mp3")
# os.remove("dummy2.mp3")
# os.remove("merged_output.mp3")
# Helper to create dummy files if needed for a more robust test
def create_dummy_mp3(filename, duration_ms=1000):
try:
silence = AudioSegment.silent(duration=duration_ms)
silence.export(filename, format="mp3")
print(f"Created dummy file: {filename}")
except Exception as e:
print(f"Could not create dummy MP3 {filename}. Ensure ffmpeg is installed and accessible. Error: {e}")
# Create dummy files for testing
dummy_files_exist = True
try:
create_dummy_mp3("test_dummy1.mp3", 1000)
create_dummy_mp3("test_dummy2.mp3", 1500)
except Exception:
dummy_files_exist = False
print("Skipping merge test as dummy files could not be created (ffmpeg issue?).")
if dummy_files_exist:
print("\nTesting merge_mp3_files...")
files_to_merge = ["test_dummy1.mp3", "test_dummy2.mp3", "non_existent_file.mp3"]
output_merged = "test_merged_audio.mp3"
result_path = merge_mp3_files(files_to_merge, output_merged, pause_ms=300)
if result_path and os.path.exists(result_path):
print(f"Successfully merged audio to: {result_path}")
# Simple check: merged file should be larger than individual (roughly)
merged_size = os.path.getsize(result_path)
dummy1_size = os.path.getsize("test_dummy1.mp3")
print(f"Size of {result_path}: {merged_size} bytes (dummy1 was {dummy1_size})")
if merged_size > dummy1_size : # crude check
print("Merge test seems OK.")
else:
print("Merged file size issue.")
os.remove(result_path)
else:
print("Failed to merge audio.")
# Clean up dummy files
if os.path.exists("test_dummy1.mp3"): os.remove("test_dummy1.mp3")
if os.path.exists("test_dummy2.mp3"): os.remove("test_dummy2.mp3")