50fdb6e5a450d71c27104ab265fc8a23f9b97d54
[aubio.git] / python / demos / demo_create_test_sounds.py
1 #! /usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 import sys, os
5 import numpy as np
6 from aubio import fvec, sink, float_type
7
8 if __name__ == '__main__':
9     if len(sys.argv) < 1:
10         print('usage: %s' % sys.argv[0])
11         sys.exit(1)
12
13     samplerate = 44100
14     hop_size = 256
15
16     # create python/tests/sounds if needed
17     output_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
18     output_dir = os.path.join(output_dir, 'tests', 'sounds')
19     if not os.path.isdir(output_dir):
20         os.makedirs(output_dir)
21
22     filenames = ['44100Hz_1f_silence.wav',
23                  '22050Hz_5s_brownnoise.wav',
24                  '32000Hz_127f_sine440.wav',
25                 ]
26     samplerates = [44100, 22050, 32000]
27     durations = [1, 5*22050, 127]
28
29     for fname, samplerate, duration in zip(filenames, samplerates, durations):
30         output_name = os.path.join(output_dir, fname)
31         g = sink(output_name, samplerate)
32         total_frames = 0
33         while total_frames < duration:
34             write = min(hop_size, duration - total_frames)
35             if 'brownnoise' in fname:
36                 vec = np.random.rand(write).astype(float_type) * 2. - 1.
37             elif 'sine' in fname:
38                 freq = 440
39                 t = np.arange(write).astype(float_type) + total_frames
40                 vec = np.sin(2. * np.pi * freq * t / float(samplerate))
41             else:
42                 # silence
43                 vec = fvec(write)
44             g(vec, write)
45             total_frames += write
46         outstr = "wrote {:2f}s".format(total_frames / float(samplerate))
47         outstr += " ({:d} frames".format(total_frames)
48         outstr += " at {:d}Hz)".format(g.samplerate)
49         outstr += " to {:s}".format(g.uri)
50         print outstr