forked from x4nth055/pythoncode-tutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
/
concatenate_audio_pydub.py
45 lines (39 loc) · 1.88 KB
/
concatenate_audio_pydub.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from pydub import AudioSegment
from tqdm import tqdm
import os
def concatenate_audio_pydub(audio_clip_paths, output_path, verbose=1):
"""
Concatenates two or more audio files into one audio file using PyDub library
and save it to `output_path`. A lot of extensions are supported, more on PyDub's doc.
"""
def get_file_extension(filename):
"""A helper function to get a file's extension"""
return os.path.splitext(filename)[1].lstrip(".")
clips = []
# wrap the audio clip paths with tqdm if verbose
audio_clip_paths = tqdm(audio_clip_paths, "Reading audio file") if verbose else audio_clip_paths
for clip_path in audio_clip_paths:
# get extension of the audio file
extension = get_file_extension(clip_path)
# load the audio clip and append it to our list
clip = AudioSegment.from_file(clip_path, extension)
clips.append(clip)
final_clip = clips[0]
range_loop = tqdm(list(range(1, len(clips))), "Concatenating audio") if verbose else range(1, len(clips))
for i in range_loop:
# looping on all audio files and concatenating them together
# ofc order is important
final_clip = final_clip + clips[i]
# export the final clip
final_clip_extension = get_file_extension(output_path)
if verbose:
print(f"Exporting resulting audio file to {output_path}")
final_clip.export(output_path, format=final_clip_extension)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Simple Audio file combiner using PyDub library in Python")
parser.add_argument("-c", "--clips", nargs="+",
help="List of audio clip paths")
parser.add_argument("-o", "--output", help="The output audio file, extension must be included (such as mp3, etc.)")
args = parser.parse_args()
concatenate_audio_pydub(args.clips, args.output)