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) |