File size: 1,903 Bytes
a3ed455
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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()