Generate tone frequency using au file
1 2 from struct import pack 3 from math import sin, pi 4 5 def au_file(name='out.au', freq=400, length=2, A=0.5): 6 f = open(name, 'wb') 7 f.write('.snd') 8 f.write(pack('>5L', 24, -1, 2, 8000, 1)) 9 T = 8000./freq 10 for i in range(length*8000): 11 angle = 2*pi*i/T 12 val = pack('b', A*sin(angle)*127) 13 f.write(val) 14 f.close()
The reason that I use '.au' instead of '.wav' is that
the format is much simpler. Both are supported on my 6600 phone.
Here's the second step, after removing some bug.
(data size can't be -1, I must calculate it too)
1 2 from struct import pack 3 from math import pi, sin 4 import e32, audio 5 6 def tone(freq=440, duration=1000, volume=0.5): 7 f = open('D:\\out.au', 'wb') # temp file 8 f.write('.snd' + pack('>5L', 24, 8*duration, 2, 8000, 1)) #header 9 for i in range(duration*8): 10 sin_i = sin(i * 2*pi*freq/8000) # sine wave 11 f.write(pack('b', volume*127*sin_i)) 12 f.close() 13 # now play the file 14 s = audio.Sound.open('D:\\out.au') 15 s.play() 16 while s.state()==2: # playing 17 e32.ao_yield() 18 s.close()
The code is still quite slow. I'm not sure why (haven't test).
Either because of sin() or pack() or f.write()
A solution could be using a smaller file and play it multiple times.
But this small code should be enough to demonstrate an idea.