Created
November 20, 2022 18:40
-
-
Save mohamed/e79f90f182a7019045848fb9e1205b4a to your computer and use it in GitHub Desktop.
Record and plot audio from microphone
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pyaudio | |
import matplotlib.pyplot as plt | |
import numpy | |
import wave | |
FORMAT = pyaudio.paInt16 # We use 16bit format per sample | |
CHANNELS = 1 | |
RATE = 44100 | |
CHUNK = 1024 # 1024bytes of data red from a buffer | |
RECORD_SECONDS = 5 | |
WAVE_OUTPUT_FILENAME = "file.wav" | |
audio = pyaudio.PyAudio() | |
# start Recording | |
stream = audio.open(format=FORMAT, | |
channels=CHANNELS, | |
rate=RATE, input=True, | |
frames_per_buffer=CHUNK) | |
frames = [] | |
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)): | |
data = stream.read(CHUNK) | |
frames.append(data) | |
frames = b"".join(frames) | |
stream.stop_stream() | |
stream.close() | |
audio.terminate() | |
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb') | |
wf.setnchannels(CHANNELS) | |
wf.setsampwidth(audio.get_sample_size(FORMAT)) | |
wf.setframerate(RATE) | |
wf.writeframes(frames) | |
wf.close() | |
fig = plt.figure() | |
s = fig.add_subplot(111) | |
amplitude = numpy.frombuffer(frames, numpy.int16) | |
s.plot(amplitude) | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment