Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pyaudio
- import numpy as np
- import librosa
- # Function to capture audio
- def capture_audio(duration=3, sample_rate=22050):
- p = pyaudio.PyAudio()
- stream = p.open(format=pyaudio.paFloat32,
- channels=1,
- rate=sample_rate,
- input=True,
- frames_per_buffer=1024)
- print("Recording...")
- frames = []
- for _ in range(0, int(sample_rate / 1024 * duration)):
- data = stream.read(1024)
- frames.append(np.frombuffer(data, dtype=np.float32))
- print("Finished recording.")
- stream.stop_stream()
- stream.close()
- p.terminate()
- audio_data = np.hstack(frames)
- return audio_data, sample_rate
- # Function to detect pitch
- def detect_pitch(audio_data, sample_rate):
- pitches, magnitudes = librosa.core.piptrack(y=audio_data, sr=sample_rate)
- pitch = []
- for t in range(pitches.shape[1]):
- index = magnitudes[:, t].argmax()
- pitch.append(pitches[index, t])
- pitch = np.array(pitch)
- pitch = pitch[pitch > 0] # Remove zero values
- return pitch
- # Function to determine if the note is high or low
- def classify_pitch(pitch):
- average_pitch = np.mean(pitch)
- if average_pitch > 300: # Threshold for high note (in Hz)
- return "High Note"
- else:
- return "Low Note"
- # Main function
- def main():
- audio_data, sample_rate = capture_audio()
- pitch = detect_pitch(audio_data, sample_rate)
- note_classification = classify_pitch(pitch)
- print(f"The detected note is a {note_classification}.")
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement