test_dataloader.py 1.63 KB
Newer Older
David Pollack's avatar
David Pollack committed
1
import unittest
2
import test.common_utils
David Pollack's avatar
David Pollack committed
3
4
5
6
7
8
9
10
11
12
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
import torchaudio
import math
import os


class TORCHAUDIODS(Dataset):

13
    test_dirpath, test_dir = test.common_utils.create_temp_assets_dir()
David Pollack's avatar
David Pollack committed
14
15
16

    def __init__(self):
        self.asset_dirpath = os.path.join(self.test_dirpath, "assets")
17
18
        sound_files = list(filter(lambda x: '.wav' in x or '.mp3' in x, os.listdir(self.asset_dirpath)))
        self.data = [os.path.join(self.asset_dirpath, fn) for fn in sound_files]
David Pollack's avatar
David Pollack committed
19
20
        self.si, self.ei = torchaudio.info(os.path.join(self.asset_dirpath, "sinewave.wav"))
        self.si.precision = 16
David Pollack's avatar
David Pollack committed
21
22
        self.E = torchaudio.sox_effects.SoxEffectsChain()
        self.E.append_effect_to_chain("rate", [self.si.rate])  # resample to 16000hz
23
        self.E.append_effect_to_chain("channels", [self.si.channels])  # mono signal
David Pollack's avatar
David Pollack committed
24
        self.E.append_effect_to_chain("trim", [0, "16000s"])  # first 16000 samples of audio
David Pollack's avatar
David Pollack committed
25
26
27
28
29
30
31
32
33
34

    def __getitem__(self, index):
        fn = self.data[index]
        self.E.set_input_file(fn)
        x, sr = self.E.sox_build_flow_effects()
        return x

    def __len__(self):
        return len(self.data)

35

36
class Test_DataLoader(unittest.TestCase):
37
38
39
40
41
42
43
44
    @classmethod
    def setUpClass(cls):
        torchaudio.initialize_sox()

    @classmethod
    def tearDownClass(cls):
        torchaudio.shutdown_sox()

David Pollack's avatar
David Pollack committed
45
46
47
48
49
    def test_1(self):
        expected_size = (2, 1, 16000)
        ds = TORCHAUDIODS()
        dl = DataLoader(ds, batch_size=2)
        for x in dl:
50
            self.assertTrue(x.size() == expected_size)
David Pollack's avatar
David Pollack committed
51
52
53

if __name__ == '__main__':
    unittest.main()