Skip to content

Instantly share code, notes, and snippets.

@iamaaditya
Forked from anonymous/specturm.py
Created September 2, 2012 13:38

Revisions

  1. @invalid-email-address Anonymous created this gist Apr 18, 2010.
    57 changes: 57 additions & 0 deletions specturm.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    import ossaudiodev as oss
    from numpy import fft
    import math
    import pygame
    import pygame.surfarray as surfarray


    d = oss.open('rw')
    d.setfmt(oss.AFMT_U16_LE)
    d.channels(1)
    d.speed (44100)

    buf_size = 4096
    bins = 256

    WIDTH = 500

    pygame.init()
    screen = pygame.display.set_mode((WIDTH, bins))
    surf = pygame.display.get_surface()
    px = surfarray.pixels2d(surf)


    def power(c):
    return c.real * c.real + c.imag * c.imag

    X = 0

    while 1:
    x = d.read(buf_size)
    v = [-0.5 + (ord(x[2*i]) | ord(x[2*i+1])<<8) / 65536.0 for i in range(0,len(x)/2)]
    f = fft.fft(v)
    p = [power(c) for c in f]

    b = [0] * bins
    for i in range(0,bins):
    for j in range(0,buf_size/(4*bins)):
    b[i] += p[buf_size * i / (4*bins) + j]

    Xn = (X+1) % WIDTH

    for i in range(0,bins):
    k = int(255 * math.log(b[i]+1))
    if (k >= 255):
    k = 255
    px[X,bins-i-1] = k << 8
    k = 64
    px[Xn,bins-i-1] = (k<<16) | (k<<8) | k

    surfarray.blit_array(surf, px)

    pygame.display.flip()

    X += 1
    if (X >= WIDTH):
    X = 0
    d.write(x)