Advertisement
STANAANDREY

py pitch detect

Dec 16th, 2024
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.63 KB | None | 0 0
  1. import pyaudio
  2. import numpy as np
  3. import librosa
  4.  
  5. # Function to capture audio
  6. def capture_audio(duration=3, sample_rate=22050):
  7.     p = pyaudio.PyAudio()
  8.     stream = p.open(format=pyaudio.paFloat32,
  9.                     channels=1,
  10.                     rate=sample_rate,
  11.                     input=True,
  12.                     frames_per_buffer=1024)
  13.    
  14.     print("Recording...")
  15.     frames = []
  16.     for _ in range(0, int(sample_rate / 1024 * duration)):
  17.         data = stream.read(1024)
  18.         frames.append(np.frombuffer(data, dtype=np.float32))
  19.    
  20.     print("Finished recording.")
  21.     stream.stop_stream()
  22.     stream.close()
  23.     p.terminate()
  24.    
  25.     audio_data = np.hstack(frames)
  26.     return audio_data, sample_rate
  27.  
  28. # Function to detect pitch
  29. def detect_pitch(audio_data, sample_rate):
  30.     pitches, magnitudes = librosa.core.piptrack(y=audio_data, sr=sample_rate)
  31.     pitch = []
  32.     for t in range(pitches.shape[1]):
  33.         index = magnitudes[:, t].argmax()
  34.         pitch.append(pitches[index, t])
  35.     pitch = np.array(pitch)
  36.     pitch = pitch[pitch > 0]  # Remove zero values
  37.     return pitch
  38.  
  39. # Function to determine if the note is high or low
  40. def classify_pitch(pitch):
  41.     average_pitch = np.mean(pitch)
  42.     if average_pitch > 300:  # Threshold for high note (in Hz)
  43.         return "High Note"
  44.     else:
  45.         return "Low Note"
  46.  
  47. # Main function
  48. def main():
  49.     audio_data, sample_rate = capture_audio()
  50.     pitch = detect_pitch(audio_data, sample_rate)
  51.     note_classification = classify_pitch(pitch)
  52.     print(f"The detected note is a {note_classification}.")
  53.  
  54. if __name__ == "__main__":
  55.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement