import torchaudio import torchaudio.functional as F import glob from pathlib import Path from multiprocessing import Pool import os from functools import partial import torch import tqdm import torch.multiprocessing RESAMPLE_RATE = 32000 PATH = "original_audios" SAVE_PATH = f"audios_sr={RESAMPLE_RATE}" def resample(path, resample_rate, device): waveform, sample_rate = torchaudio.load(path, channels_first=False) waveform = waveform.to(device) if waveform.shape[0] != 4: waveform = waveform.T resampled_waveform = F.resample( waveform, sample_rate, resample_rate, lowpass_filter_width=64, rolloff=0.9475937167399596, resampling_method="sinc_interp_kaiser", beta=14.769656459379492, ) return resampled_waveform def resample_and_save(audio, resample_rate, device): resampled_audio = resample(audio, resample_rate, device) assert resampled_audio.shape[0] == 4, "Swap channel dimensions" file_name = Path(audio).stem file_ext = Path(audio).suffix save_file = f"{SAVE_PATH}/{file_name}{file_ext}" if not os.path.exists(save_file): torchaudio.save(save_file, resampled_audio.cpu(), resample_rate, channels_first=True) if __name__ == "__main__": torch.multiprocessing.set_start_method('spawn', force=True) os.makedirs(SAVE_PATH, exist_ok=True) device = torch.device("cpu" if not torch.cuda.is_available() else "cuda") audios = glob.glob(f"{PATH}/*.wav") audios = list(filter(lambda x: not os.path.exists(os.path.join(SAVE_PATH, Path(x).stem + ".wav")), audios)) print(f"Found {len(audios)} to resample") p = Pool(8) resample_and_save_partial = partial(resample_and_save, resample_rate = RESAMPLE_RATE, device = device) r = list(tqdm.tqdm(p.imap(resample_and_save_partial, audios), total=len(audios))) p.close() p.join()