a44c0d1f0ac7b7552769161ef9d9a965c95d9219
[aubio.git] / tests / create_tests_source.py
1 #! /usr/bin/env python
2
3 """ Create a simple stereo file containing a sine tone at 441 Hz, using only
4 numpy and python's native wave module. """
5
6 import wave
7 import numpy as np
8
9
10 def create_sine_wave(freq, samplerate, nframes, nchannels):
11     """ create a pure tone """
12     # samples indices
13     _t = np.tile(np.arange(nframes), (nchannels, 1))
14     # sine wave generation
15     _x = 0.7 * np.sin(2. * np.pi * freq * _t / float(samplerate))
16     # conversion to int and channel interleaving
17     return (_x * 32767.).astype(np.int16).T.flatten()
18
19
20 def create_test_sound(pathname, freq=441, duration=None,
21                       sampwidth=2, framerate=44100, nchannels=2):
22     """ create a sound file at pathname, overwriting exiting file """
23     nframes = duration or framerate  # defaults to 1 second duration
24     fid = wave.open(pathname, 'w')
25     fid.setnchannels(nchannels)
26     fid.setsampwidth(sampwidth)
27     fid.setframerate(framerate)
28     fid.setnframes(nframes)
29     frames = create_sine_wave(freq, framerate, nframes, nchannels)
30     fid.writeframes(frames.tobytes())
31     fid.close()
32     return 0
33
34
35 if __name__ == '__main__':
36     import sys
37     if len(sys.argv) < 2:
38         sys.exit(2)
39     sys.exit(create_test_sound(sys.argv[1]))