test.py 6.97 KB
Newer Older
David Pollack's avatar
David Pollack committed
1
import unittest
2
import torch
Soumith Chintala's avatar
Soumith Chintala committed
3
import torchaudio
David Pollack's avatar
David Pollack committed
4
import math
David Pollack's avatar
David Pollack committed
5
6
import os

Soumith Chintala's avatar
Soumith Chintala committed
7

David Pollack's avatar
David Pollack committed
8
9
class Test_LoadSave(unittest.TestCase):
    test_dirpath = os.path.dirname(os.path.realpath(__file__))
10
11
    test_filepath = os.path.join(test_dirpath, "assets",
                                 "steam-train-whistle-daniel_simon.mp3")
Soumith Chintala's avatar
Soumith Chintala committed
12

David Pollack's avatar
David Pollack committed
13
    def test_1_save(self):
David Pollack's avatar
David Pollack committed
14
        # load signal
David Pollack's avatar
David Pollack committed
15
        x, sr = torchaudio.load(self.test_filepath, normalization=False)
David Pollack's avatar
David Pollack committed
16
17
18
19
20
21
22
23
24
25
26
27
28
29

        # check save
        new_filepath = os.path.join(self.test_dirpath, "test.wav")
        torchaudio.save(new_filepath, x, sr)
        self.assertTrue(os.path.isfile(new_filepath))
        os.unlink(new_filepath)

        # check automatic normalization
        x /= 1 << 31
        torchaudio.save(new_filepath, x, sr)
        self.assertTrue(os.path.isfile(new_filepath))
        os.unlink(new_filepath)

        # test save 1d tensor
David Pollack's avatar
David Pollack committed
30
        x = x[0, :]  # get mono signal
Soumith Chintala's avatar
Soumith Chintala committed
31
        x.squeeze_()  # remove channel dim
David Pollack's avatar
David Pollack committed
32
33
34
35
36
37
        torchaudio.save(new_filepath, x, sr)
        self.assertTrue(os.path.isfile(new_filepath))
        os.unlink(new_filepath)

        # don't allow invalid sizes as inputs
        with self.assertRaises(ValueError):
David Pollack's avatar
David Pollack committed
38
            x.unsqueeze_(1)  # L x C not C x L
David Pollack's avatar
David Pollack committed
39
40
41
42
43
            torchaudio.save(new_filepath, x, sr)

        with self.assertRaises(ValueError):
            x.squeeze_()
            x.unsqueeze_(1)
Soumith Chintala's avatar
Soumith Chintala committed
44
            x.unsqueeze_(0)  # 1 x L x 1
David Pollack's avatar
David Pollack committed
45
46
47
48
            torchaudio.save(new_filepath, x, sr)

        # don't save to folders that don't exist
        with self.assertRaises(OSError):
49
50
            new_filepath = os.path.join(self.test_dirpath, "no-path",
                                        "test.wav")
David Pollack's avatar
David Pollack committed
51
            torchaudio.save(new_filepath, x, sr)
Soumith Chintala's avatar
Soumith Chintala committed
52

53
        # save created file
54
55
        sinewave_filepath = os.path.join(self.test_dirpath, "assets",
                                         "sinewave.wav")
56
57
58
59
        sr = 16000
        freq = 440
        volume = 0.3

60
        y = (torch.cos(
61
            2 * math.pi * torch.arange(0, 4 * sr).float() * freq / sr))
David Pollack's avatar
David Pollack committed
62
        y.unsqueeze_(0)
63
        # y is between -1 and 1, so must scale
David Pollack's avatar
David Pollack committed
64
        y = (y * volume * (2**31)).long()
65
66
        torchaudio.save(sinewave_filepath, y, sr)
        self.assertTrue(os.path.isfile(sinewave_filepath))
67

68
        # test precision
David Pollack's avatar
David Pollack committed
69
        new_precision = 32
70
        new_filepath = os.path.join(self.test_dirpath, "test.wav")
David Pollack's avatar
David Pollack committed
71
72
73
74
75
        si, ei = torchaudio.info(sinewave_filepath)
        torchaudio.save(new_filepath, y, sr, new_precision)
        si32, ei32 = torchaudio.info(new_filepath)
        self.assertEqual(si.precision, 16)
        self.assertEqual(si32.precision, new_precision)
76
77
        os.unlink(new_filepath)

David Pollack's avatar
David Pollack committed
78
79
80
81
82
83
    def test_2_load(self):
        # check normal loading
        x, sr = torchaudio.load(self.test_filepath)
        self.assertEqual(sr, 44100)
        self.assertEqual(x.size(), (2, 278756))

David Pollack's avatar
David Pollack committed
84
85
86
87
88
89
90
91
92
        # check no normalizing
        x, _ = torchaudio.load(self.test_filepath, normalization=False)
        self.assertTrue(x.min() <= -1.0)
        self.assertTrue(x.max() >= 1.0)

        # check offset
        offset = 15
        x, _ = torchaudio.load(self.test_filepath)
        x_offset, _ = torchaudio.load(self.test_filepath, offset=offset)
93
        self.assertTrue(x[:, offset:].allclose(x_offset))
David Pollack's avatar
David Pollack committed
94
95
96
97
98
99
100
101
102
103
104
105
106

        # check number of frames
        n = 201
        x, _ = torchaudio.load(self.test_filepath, num_frames=n)
        self.assertTrue(x.size(), (2, n))

        # check channels first
        x, _ = torchaudio.load(self.test_filepath, channels_first=False)
        self.assertEqual(x.size(), (278756, 2))

        # check different input tensor type
        x, _ = torchaudio.load(self.test_filepath, torch.LongTensor(), normalization=False)
        self.assertTrue(isinstance(x, torch.LongTensor))
David Pollack's avatar
David Pollack committed
107
108
109
110
111
112
113
114
115
116
117

        # check raising errors
        with self.assertRaises(OSError):
            torchaudio.load("file-does-not-exist.mp3")

        with self.assertRaises(OSError):
            tdir = os.path.join(
                os.path.dirname(self.test_dirpath), "torchaudio")
            torchaudio.load(tdir)

    def test_3_load_and_save_is_identity(self):
118
119
120
121
122
123
124
125
126
        input_path = os.path.join(self.test_dirpath, 'assets', 'sinewave.wav')
        tensor, sample_rate = torchaudio.load(input_path)
        output_path = os.path.join(self.test_dirpath, 'test.wav')
        torchaudio.save(output_path, tensor, sample_rate)
        tensor2, sample_rate2 = torchaudio.load(output_path)
        self.assertTrue(tensor.allclose(tensor2))
        self.assertEqual(sample_rate, sample_rate2)
        os.unlink(output_path)

David Pollack's avatar
David Pollack committed
127
    def test_4_load_partial(self):
David Pollack's avatar
David Pollack committed
128
129
        num_frames = 101
        offset = 201
130
131
132
133
        # load entire mono sinewave wav file, load a partial copy and then compare
        input_sine_path = os.path.join(self.test_dirpath, 'assets', 'sinewave.wav')
        x_sine_full, sr_sine = torchaudio.load(input_sine_path)
        x_sine_part, _ = torchaudio.load(input_sine_path, num_frames=num_frames, offset=offset)
134
        l1_error = x_sine_full[:, offset:(num_frames + offset)].sub(x_sine_part).abs().sum().item()
135
        # test for the correct number of samples and that the correct portion was loaded
David Pollack's avatar
David Pollack committed
136
        self.assertEqual(x_sine_part.size(1), num_frames)
137
138
139
140
141
142
143
        self.assertEqual(l1_error, 0.)
        # create a two channel version of this wavefile
        x_2ch_sine = x_sine_full.repeat(1, 2)
        out_2ch_sine_path = os.path.join(self.test_dirpath, 'assets', '2ch_sinewave.wav')
        torchaudio.save(out_2ch_sine_path, x_2ch_sine, sr_sine)
        x_2ch_sine_load, _ = torchaudio.load(out_2ch_sine_path, num_frames=num_frames, offset=offset)
        os.unlink(out_2ch_sine_path)
David Pollack's avatar
David Pollack committed
144
        l1_error = x_2ch_sine_load.sub(x_2ch_sine[:, offset:(offset + num_frames)]).abs().sum().item()
145
146
147
148
149
        self.assertEqual(l1_error, 0.)

        # test with two channel mp3
        x_2ch_full, sr_2ch = torchaudio.load(self.test_filepath, normalization=True)
        x_2ch_part, _ = torchaudio.load(self.test_filepath, normalization=True, num_frames=num_frames, offset=offset)
150
        l1_error = x_2ch_full[:, offset:(offset + num_frames)].sub(x_2ch_part).abs().sum().item()
David Pollack's avatar
David Pollack committed
151
        self.assertEqual(x_2ch_part.size(1), num_frames)
152
153
154
155
156
        self.assertEqual(l1_error, 0.)

        # check behavior if number of samples would exceed file length
        offset_ns = 300
        x_ns, _ = torchaudio.load(input_sine_path, num_frames=100000, offset=offset_ns)
David Pollack's avatar
David Pollack committed
157
        self.assertEqual(x_ns.size(1), x_sine_full.size(1) - offset_ns)
158
159
160
161
162

        # check when offset is beyond the end of the file
        with self.assertRaises(RuntimeError):
            torchaudio.load(input_sine_path, offset=100000)

David Pollack's avatar
David Pollack committed
163
    def test_5_get_info(self):
164
        input_path = os.path.join(self.test_dirpath, 'assets', 'sinewave.wav')
David Pollack's avatar
David Pollack committed
165
166
167
168
169
170
        channels, samples, rate, precision = (1, 64000, 16000, 16)
        si, ei = torchaudio.info(input_path)
        self.assertEqual(si.channels, channels)
        self.assertEqual(si.length, samples)
        self.assertEqual(si.rate, rate)
        self.assertEqual(ei.bits_per_sample, precision)
Soumith Chintala's avatar
Soumith Chintala committed
171

David Pollack's avatar
David Pollack committed
172
173
if __name__ == '__main__':
    unittest.main()