Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS 

Generate tone frequency using au file

The first part of my attempt to produce a tone sound.
from struct import pack
from math import sin, pi

def au_file(name='out.au', freq=400, length=2, A=0.5):
	f = open(name, 'wb')
	f.write('.snd')
	f.write(pack('>5L', 24, -1, 2, 8000, 1))
	T = 8000./freq
	for i in range(length*8000):
		angle = 2*pi*i/T
		val = pack('b', A*sin(angle)*127)
		f.write(val)
	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)
from struct import pack
from math import pi, sin
import e32, audio 

def tone(freq=440, duration=1000, volume=0.5):
    f = open('D:\\out.au', 'wb')    # temp file
    f.write('.snd' + pack('>5L', 24, 8*duration, 2, 8000, 1))  #header
    for i in range(duration*8):
        sin_i = sin(i * 2*pi*freq/8000)  # sine wave
        f.write(pack('b', volume*127*sin_i))
    f.close()
    # now play the file
    s = audio.Sound.open('D:\\out.au')
    s.play()
    while s.state()==2: # playing
        e32.ao_yield()
    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.

Counting frequency in a list

>>> alist = [ '1', '1', '2', '1', '3', '4', '1', '3']
>>> [(a, alist.count(a)) for a in set(alist)]
[('1', 4), ('3', 2), ('2', 1), ('4', 1)]
>>> sorted(_, key=lambda x: -x[1])  # rank them
[('1', 4), ('3', 2), ('2', 1), ('4', 1)]

MIDI Note number and frequency

Summary of MIDI Note Numbers
MIDI Note to Frequency

I can use them with my midi snippet.
# from http://logic-users.org/forums/L-OT/295
# Each note's frequency is 2^(1/12) times of the previous note.

freq = 440 * 2^((n-69)/12)
n = 69 + 12*log(freq/440)/log(2)

# Doe, ray, me, fa, sol, la, tee, doe
>>> play([(i, 100) for i in [60, 62, 64,65, 67, 69, 71,72]])

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS