import tkinter as tk


import aubio
import numpy as num
import pyaudio
import sys


import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
from tkinter import Tk, Text, TOP, BOTH, X, N, LEFT
# Some constants for setting the PyAudio and the
# Aubio.
BUFFER_SIZE             = 2048
CHANNELS                = 1
FORMAT                  = pyaudio.paFloat32
METHOD                  = "default"
SAMPLE_RATE             = 44100
HOP_SIZE                = BUFFER_SIZE//2
PERIOD_SIZE_IN_FRAME    = HOP_SIZE


counter = 0
counter1 = 0 
def counter_label(label):
  def count():
    global counter
    counter += 1
    label.config(text=str(counter))
    label.after(1000, count)
  count()


def pitch_label(label):
   def pitch():
     global counter1,data,samples,tvec
     counter1 += 1    


# Open the microphone stream.
     mic = pA.open(format=FORMAT, channels=CHANNELS,
      rate=SAMPLE_RATE, input=True,
      frames_per_buffer=PERIOD_SIZE_IN_FRAME)
# Initiating Aubio's pitch detection object.
     pDetection = aubio.pitch(METHOD, BUFFER_SIZE,HOP_SIZE, SAMPLE_RATE)
# Set unit.
     pDetection.set_unit("Hz")
# Frequency under -40 dB will considered
# as a silence.
     pDetection.set_silence(-40)
     
# Infinite loop!
#   while True:
     # Always listening to the microphone.
     data = mic.read(PERIOD_SIZE_IN_FRAME)
     # Convert into number that Aubio understand.
     samples = num.fromstring(data,dtype=aubio.float_type)
     # Finally get the pitch.
#     print(samples[45],counter1)
     pitch1 = pDetection(samples)[0]
  #   pitch1 = "{0:2f}".format(pitch1)
     pitch1 = round(pitch1,2)
     # Compute the energy (volume)
     # of the current frame.
     volume = num.sum(samples**2)/len(samples)
     # Format the volume output so it only
     # displays at most six numbers behind 0.
     volume = "{:3f}".format(volume)

     # Finally print the pitch and the volume.
     #print(str(pitch1) + " " + str(volume))
#     t1 = (str(pitch1) + " " + str(volume))
     t1 = (str(pitch1) + " Hz")
     label.config(text=str(t1))
     label.after(1000, pitch)
     mic.close()
     ax.cla()
     dpts = samples[0:1024]
     tvec=num.arange(0,1024/44100,1/44100)
     #ax.plot(tvec, dpts, marker='o', color='blue')
     c=343
     lamb=c/pitch1
     x=np.arange(0,0.86,0.01)
     y=np.cos(2*np.pi*x/lamb)
    
     #     print("xxxxxxxxxx",y)
     #ax.plot(x, y, marker='o', color='blue')  
     ax.plot(tvec, samples, marker='o', color='blue')
    
     graph.draw()


   pitch()
     
#############################################



  

######### main ##############
# Initiating PyAudio object.
pA = pyaudio.PyAudio()


root = tk.Tk()
root.title("Pitch")
#root.geometry("1000x700")


###w = Label(root, text="Hello, world!")
root.overrideredirect(True)
root.geometry("{0}x{1}+0+0".format(root.winfo_screenwidth(), root.winfo_screenheight()))
root.focus_set()  # <-- move focus to this widget
root.bind("<Escape>", lambda e: e.widget.quit())
##w.pack()






fig = Figure(figsize=(15,5))

ax = fig.add_subplot(111)

ax.set_xlabel("X axis")
ax.set_ylabel("Y axis")
ax.grid()

graph = FigureCanvasTkAgg(fig, master=root)

graph.draw()

#########################
label = tk.Label(root, fg="blue")
label.config(width=20)
label.pack()
label.config(font=("Courier", 96))
pitch_label(label)

########################
#graph.get_tk_widget().pack(side="top",fill='both',expand=True)
graph.get_tk_widget().pack(fill=X, padx=5, pady=10,expand=True)







#######################
button = tk.Button(root, text='Stop', width=25, command=root.destroy)
button.pack()






root.mainloop()



  
##########################################


######################
  
