Skip to content

Instantly share code, notes, and snippets.

@lyleaf
Created November 10, 2019 07:14
Show Gist options
  • Save lyleaf/fa18a64217a0dbc7b4fe51e1032aa5a8 to your computer and use it in GitHub Desktop.
Save lyleaf/fa18a64217a0dbc7b4fe51e1032aa5a8 to your computer and use it in GitHub Desktop.
pyaudio_recorder.py
import pyaudio
import wave
sample_format = pyaudio.paFloat32 # 16 bits per sample
channels = 1
fs = 44100 # Record at 44100 samples per second
seconds = 10
filename = "output.wav"
chunk = 2048#fs*5 # Record in chunks of 1024 samples
p = pyaudio.PyAudio() # Create an interface to PortAudio
print('Recording')
stream = p.open(format=sample_format,
channels=channels,
rate=fs,
frames_per_buffer=chunk,
input=True)
frames = [] # Initialize array to store frames
# Store data in chunks for 3 seconds
for i in range(0, int(fs / chunk * seconds)):
data = stream.read(chunk, exception_on_overflow=False)
frames.append(data)
# Stop and close the stream
stream.stop_stream()
stream.close()
# Terminate the PortAudio interface
p.terminate()
print('Finished recording')
# Save the recorded data as a WAV file
wf = wave.open(filename, 'wb')
wf.setnchannels(channels)
wf.setsampwidth(p.get_sample_size(sample_format))
wf.setframerate(fs)
wf.writeframes(b''.join(frames))
wf.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment