from scipy.io import wavfile
import numpy as np
import OpenGL 
OpenGL.ERROR_ON_COPY = True 

from OpenGL.GLUT import *
from OpenGL.GL import *
from OpenGL.GLU import *

j=0
freq,audio=wavfile.read('signal/02 Does Anybody Really Know What Time It Is-.wav')
audio=audio[:,0]

def init2D(r,g,b):
    glClearColor(r,g,b,0.0)    
    glMatrixMode (GL_PROJECTION)
    gluOrtho2D (0.0, 120000.0, -1400.0, 12000.0)

def fourier(k):
    global audio, freq
    s1=audio[k:k+2000]
    #s1=s1/(2.**15)
    n=len(s1)
    p=np.fft.rfft(s1)
    p=abs(p)
    p=p/float(n)
    freqArray=np.fft.rfftfreq(n,1./freq)
    return p,freqArray,s1

def display():
    p,freq,sig=fourier(j)
    
    glClear(GL_COLOR_BUFFER_BIT)

    glColor3f(.5,1.0,.5)
    glRectf(j,1200,j+2000,-1200)

    glColor3f(0.0,1.0,0.0)
    
    glBegin(GL_LINES)
    for i in range(1000):
        glVertex2i(int(freq[i]*2+500),1500)
        glVertex2i(int(freq[i]*2+500),int(p[i]*30+1500))
    '''
    glVertex2i(50,int(audio[0])-10)
    for i in range(len(audio)):
        glVertex2i(50+i,int(audio[i])-10)
        glVertex2i(50+i,int(audio[i])-10)
    glVertex2i(50+i,int(audio[i])-10)
    '''
    glVertex2i(60000,int(sig[0])+6500)
    for i in range(len(sig)):
        glVertex2i(60000+(i*29),int(sig[i])+6500)
        glVertex2i(60000+(i*29),int(sig[i])+6500)
    glVertex2i(60000+(i*29),int(sig[i])+6500)
    glEnd()

    glColor3f(1.0, 0.0, 0.0)
    
    glBegin(GL_LINES)
    glVertex2i(500,1500)   
    glVertex2i(500,11500)
    glVertex2i(500,1500)
    glVertex2i(58500,1500)
    glVertex2i(60000,1500)
    glVertex2i(60000,11500)
    glVertex2i(60000,6500)
    glVertex2i(119500,6500)
    glEnd()
    
    glFlush()

def animate():
    global j
    j+=1000
    if(j+2000>len(audio)):
        j=0
    glutPostRedisplay()

glutInit(sys.argv)
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB)
glutInitWindowSize (1000, 700)
glutInitWindowPosition (0, 0)
glutCreateWindow ('points and lines')
init2D(0.0,0.0,0.0)
glutDisplayFunc(display)
glutIdleFunc(animate)

glutMainLoop()
