import math
import gsim

def spectrum(specfile, cutoff = 64, volume = 255):
    """
    Read an Audacity spectrum file as a list of (frequency, amplitude)
    pairs, loudest first.  Length of the list is ``cutoff``, total
    amplitude is ``volume``.
    """
    snd = [[float(t) for t in l.split()] for l in open(specfile) if not "Freq" in l]
    snd = [(f,db) for (f,db) in snd if 40 < f < 8192]
    snd = sorted(snd, reverse=True, key=lambda t:t[1])
    top = snd[:cutoff]
    amps = [(f,math.pow(2, .1 * db)) for (f, db) in top]
    samps = sum([a for (f,a) in amps])
    return [(f, int(volume * a / samps)) for (f, a) in amps]

gd = gsim.Gameduino()

if 0:
    # deep note
    for (i, (f, a)) in enumerate(spectrum("thx.txt")):
        gd.voice(i, 0, int(4 * f), a, a)
    gd.dump(gsim.VOICES, 256)
    gd.writewave(3, "deepnote.wav")

if 1:
    gd.wr(gsim.RING_START, 10)
    gd.wr(gsim.RING_END, 20)
    gd.voice(5, 0, 4 * 660, 255, 255)
    gd.voice(15, 0, 4 * 440, 255, 255)
    gd.writewave(1, "ringdemo.wav")
