blob: fb992a95946499185a578de59e9bec468c54a827 [file] [log] [blame]
Guido van Rossumc6360141990-10-13 19:23:40 +00001import audio
2
3RATE = 8192
4
5# Initialize the audio stuff
6audio.setrate(3)
7audio.setoutgain(100) # for speaker
8
9play = audio.write
10
11def samp(n):
12 savegain = audio.getoutgain()
13 try:
14 audio.setoutgain(0)
15 x = raw_input('Hit Enter to sample ' + `n` + ' seconds: ')
16 return audio.read(n*RATE)
17 finally:
18 audio.setoutgain(savegain)
19
20def echo(s, delay, gain):
21 return s[:delay] + audio.add(s[delay:], audio.amplify(s, gain, gain))
22
23def save(s, file):
24 f = open(file, 'w')
25 f.write(s)
26
27def load(file):
28 return loadfp(open(file, 'r'))
29
30def loadfp(fp):
31 s = ''
32 while 1:
33 buf = fp.read(16*1024)
34 if not buf: break
35 s = s + buf
36 return s
37
38def unbias(s):
39 if not s: return s
40 a = audio.chr2num(s)
41 sum = 0
42 for i in a: sum = sum + i
43 bias = (sum + len(a)/2) / len(a)
44 print 'Bias value:', bias
45 if bias:
46 for i in range(len(a)):
47 a[i] = a[i] - bias
48 s = audio.num2chr(a)
49 return s
50
51# Stretch by a/b.
52# Think of this as converting the sampling rate from a samples/sec
53# to b samples/sec. Or, if the input is a bytes long, the output
54# will be b bytes long.
55#
56def stretch(s, a, b):
57 y = audio.chr2num(s)
58 m = len(y)
59 out = []
60 n = m * b / a
61 # i, j will walk through y and out (step 1)
62 # ib, ja are i*b, j*a and are kept as close together as possible
63 i, ib = 0, 0
64 j, ja = 0, 0
65 for j in range(n):
66 ja = ja+a
67 while ib < ja:
68 i = i+1
69 ib = ib+b
70 if i >= m:
71 break
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000072 if ib == ja:
Guido van Rossumc6360141990-10-13 19:23:40 +000073 out.append(y[i])
74 else:
75 out.append((y[i]*(ja-(ib-b)) + y[i-1]*(ib-ja)) / b)
76 return audio.num2chr(out)
77
78def sinus(freq): # return a 1-second sine wave
79 from math import sin, pi
80 factor = 2.0*pi*float(freq)/float(RATE)
81 list = range(RATE)
82 for i in list:
83 list[i] = int(sin(float(i) * factor) * 127.0)
84 return audio.num2chr(list)
85
86def softclip(s):
87 if '\177' not in s and '\200' not in s:
88 return s
89 num = audio.chr2num(s)
90 extremes = (-128, 127)
91 for i in range(1, len(num)-1):
92 if num[i] in extremes:
93 num[i] = (num[i-1] + num[i+1]) / 2
94 return audio.num2chr(num)
95
96def demo():
97 gday = load('gday')[1000:6000]
98 save(gday, 'gday0')
99 gg = [gday]
100 for i in range(1, 10):
101 for g in gg: play(g)
102 g = stretch(gday, 10, 10-i)
103 save(g, 'gday' + `i`)
104 gg.append(g)
105 while 1:
106 for g in gg: play(g)