Skip to content

Instantly share code, notes, and snippets.

@Psirus
Created December 14, 2018 07:21
Show Gist options
  • Save Psirus/4eeebfd0993bcd38d6c7a467d6b73560 to your computer and use it in GitHub Desktop.
Save Psirus/4eeebfd0993bcd38d6c7a467d6b73560 to your computer and use it in GitHub Desktop.
Record audio

Install pyaudio

sudo apt install python3-pyaudio

Make script executable

chmod +x record.py

Open in your favourite editor and adjust RECORD_SECONDS and OUTPUT_FOLDER accordingly

vim record.py

Run:

./record.py
#!/usr/bin/env python3
"""Record audio input and write it to a wav file named to current local time."""
from datetime import datetime
import os
import wave
import pyaudio
RECORD_SECONDS = 5
OUTPUT_FOLDER = "recordings"
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
def record():
"""Record audio using the currently selected input of the OS."""
p = pyaudio.PyAudio()
stream = p.open(
format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK
)
print("start recording")
frames = []
for _ in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print("end recording")
stream.stop_stream()
stream.close()
p.terminate()
return (frames, p.get_sample_size(FORMAT))
def write_file(frames, samplesize):
"""Write `frames` to a wav file named according to current local file."""
if not os.path.exists(OUTPUT_FOLDER):
os.makedirs(OUTPUT_FOLDER)
filename = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ".wav"
wavefile = wave.open(os.path.join(OUTPUT_FOLDER, filename), "wb")
wavefile.setnchannels(CHANNELS)
wavefile.setsampwidth(samplesize)
wavefile.setframerate(RATE)
wavefile.writeframes(b"".join(frames))
wavefile.close()
if __name__ == "__main__":
frames, samplesize = record()
write_file(frames, samplesize)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment