Last active
January 28, 2022 02:42
-
-
Save defensem3ch/5a40a25e8ddf11213b5c3602b473f0d8 to your computer and use it in GitHub Desktop.
Concatenate wav files into one evenly-spaced wav file (128-file limit)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Concatenate wav files into one evenly spaced wav file | |
# Requires sox and PySox https://github.com/rabitt/pysox | |
# License: Public domain | |
import sox, os | |
def combine_files(folder, files, out_filename, sample_rate, channels, bit_depth): | |
combine = sox.Combiner() | |
combine.convert(sample_rate, channels, bit_depth) | |
out_files = [f"{folder}/{file}" for file in files] | |
combine.build(out_files, out_filename, 'concatenate') | |
print(f"{out_filename} created") | |
return | |
folders = next(os.walk('.'))[1] | |
for folder in folders: | |
sample_rate = 44100 | |
channels = 2 | |
bit_depth = 16 | |
all_files = next(os.walk(folder))[2] | |
one_shots = [file for file in all_files if ".wav" in file.lower()] | |
one_shots.sort() | |
out_filename = "" | |
concat_files = [] | |
max_samples = 0 | |
for file in one_shots: | |
try: | |
file_test = sox.core.soxi(f"{folder}/{file}", "D") | |
if sox.file_info.num_samples(f"{folder}/{file}") > max_samples: | |
max_samples = sox.file_info.num_samples(f"{folder}/{file}") | |
if one_shots.index(file) == 0: | |
sample_rate = sox.file_info.sample_rate(f"{folder}/{file}") | |
if sample_rate < 44100: | |
sample_rate = 44100 | |
channels = sox.file_info.channels(f"{folder}/{file}") | |
if one_shots.index(file) >= 127: | |
print(f"Folder exceeds 128 files. {file} will not be included.") | |
one_shots.remove(file) | |
except sox.core.SoxiError: | |
one_shots.remove(file) | |
os.mkdir(f"{folder}_temp") | |
for file in one_shots: | |
samples_to_add = max_samples - sox.file_info.num_samples(f"{folder}/{file}") | |
tfm = sox.Transformer() | |
if samples_to_add > 0: | |
tfm.pad(0.0, samples_to_add / sample_rate) | |
tfm.norm(0.0) | |
tfm.build(f"{folder}/{file}", f"{folder}_temp/{file}") | |
concat_files.append(file) | |
out_filename = f"{folder}_{len(concat_files)}slices.wav" | |
combine_files(f"{folder}_temp", concat_files, out_filename, sample_rate, channels, bit_depth) | |
for file in all_files: | |
try: | |
os.remove(f"{folder}_temp/{file}") | |
except FileNotFoundError: | |
continue | |
os.rmdir(f"{folder}_temp") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment