rename constant
[naja.git] / tools / gen_sound.py
1 # Generate imperfect sine waves
2
3 # Design notes. Produces ~= (user requested) s of raw audio
4 # We're aiming for an 8-bit'ish effect, so we're going with
5 # 8125 Hz, 8 bit sampling, but faking it out to
6 # CDDA output (44100 Hz, 16 bit signed) for easier conversion to ogg
7 # by multiply the value by 256 (after roundin) and repeating it 4 times.
8
9 import sys
10 import math
11 import struct
12
13 OUTPUT_RATE = 8125
14 DEFAULT_VOL = 95
15
16 def gen_sine(freq, secs, volume):
17     filename = 'beep%s.pcm' % freq
18     # We generate freq cycles and sample that OUTPUT_RATE times
19     per_cycle = OUTPUT_RATE / freq
20     data = []
21     for x in range(per_cycle):
22         rad = float(x) / per_cycle * 2 * math.pi
23         y = 256 * int(volume * math.sin(rad))
24         data.extend([struct.pack('<i', y)] * 4)
25     output = open(filename, 'w')
26     # This is correct because OUTPUT_RATE = CDDA rate / 4 and we repeat
27     # the samples 4 times, so this works out to CDDA rate
28     for x in range(int(freq * secs)):
29         output.write(''.join(data))
30     output.close()
31     print 'Wrote output to %s' % filename
32
33
34 def usage():
35     print 'Unexpected input'
36     print 'Usage gen_sound <freq> [<length>] [<volume>]'
37     print ' where <freq> is the frequency in Hz (int)'
38     print ' [<length>] is the time in seconds (float) - default 0.25'
39     print ' and [<volume>] is the volume (integer between 0 and 127) - default %s' % DEFAULT_VOL
40
41
42 if __name__ == "__main__":
43     try:
44        freq = int(sys.argv[1])
45        if len(sys.argv) > 2:
46           secs = float(sys.argv[2])
47        else:
48           secs = 0.25
49        if len(sys.argv) > 3:
50           volume = int(sys.argv[3])
51        else:
52           volume = DEFAULT_VOL
53     except Exception, exc:
54        usage()
55        print 'Error was', exc
56        sys.exit(1)
57
58     if volume > 128 or volume < 0:
59         usage()
60         print 'Invalid volume: %s' % volume
61         sys.exit(1)
62
63     if freq > 2000 or freq < 100:
64         usage()
65         print 'Invalid freq: %s' % volume
66         sys.exit(1)
67
68
69     gen_sine(freq, secs, volume)
70