import pyaudio
import numpy as np
# Define constants for audio processing
CHUNK_SIZE = 1024
SAMPLE_RATE = 44100
# Define frequency ranges for each note in the musical scale
NOTE_FREQS = {
'C4': 261.63,
'D4': 293.66,
'E4': 329.63,
'F4': 349.23,
'G4': 392.00,
'A4': 440.00,
'B4': 493.88
}
# Initialize PyAudio stream
audio = pyaudio.PyAudio()
stream = audio.open(format=pyaudio.paInt16, channels=1, rate=SAMPLE_RATE,
input=True, frames_per_buffer=CHUNK_SIZE)
print("Listening for audio...")
while True:
# Read audio data from stream
data = np.frombuffer(stream.read(CHUNK_SIZE), dtype=np.int16)
# Apply window function to audio data to improve frequency resolution
window = np.hamming(len(data))
data = data * window
# Perform FFT to extract frequency components
fft = np.fft.fft(data)
freqs = np.fft.fftfreq(len(data), 1.0/SAMPLE_RATE)
freqs = freqs[:len(data)//2]
fft = np.abs(fft[:len(data)//2])
# Find peak frequency component
peak_idx = np.argmax(fft)
peak_freq = freqs[peak_idx]
# Match peak frequency to note in musical scale
note = None
for n, f in NOTE_FREQS.items():
if abs(peak_freq - f) < 10:
note = n
break
# Print note if detected
if note:
print("Detected note: {}".format(note))
QA: John Nugent, Anthony Mendo, Jackie Fang
Back-end Developers: Gabriel Garcia, Winston Lei, Roshan Soni