Created
February 6, 2021 06:53
-
-
Save seanli1/c7c1a406dda6e0285f774de8e6d961fd to your computer and use it in GitHub Desktop.
Like a dashcam but with a microphone. See other gist for source reference
This file contains hidden or 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 wave | |
import datetime | |
# Settings | |
output_dir = 'path/to/destination' | |
record_secs = 600 # seconds to record | |
dev_index = 2 # device index found by p.get_device_info_by_index(ii) | |
form_1 = pyaudio.paInt16 # 16-bit resolution | |
chans = 1 # 1 channel | |
samp_rate = 44100 # 44.1kHz sampling rate | |
chunk = 4096 # 2^12 samples for buffer | |
# Record loop | |
while True: | |
date_time = datetime.datetime.now().strftime("%y%m%d_%H-%M-%S") | |
wav_output_filename = f'{output_dir}/{date_time}.wav' | |
# create pyaudio instance | |
audio = pyaudio.PyAudio() | |
# create pyaudio stream | |
stream = audio.open(format = form_1, rate = samp_rate, channels = chans, input_device_index = dev_index, input = True, frames_per_buffer = chunk) | |
print("Recording segment...") | |
frames = [] | |
# loop through stream and append audio chunks to frame array | |
for ii in range(0,int((samp_rate/chunk)*record_secs)): | |
data = stream.read(chunk) | |
frames.append(data) | |
print("Ending segment") | |
# stop the stream, close it, and terminate the pyaudio instance | |
stream.stop_stream() | |
stream.close() | |
audio.terminate() | |
# save the audio frames as .wav file | |
wavefile = wave.open(wav_output_filename,'wb') | |
wavefile.setnchannels(chans) | |
wavefile.setsampwidth(audio.get_sample_size(form_1)) | |
wavefile.setframerate(samp_rate) | |
wavefile.writeframes(b''.join(frames)) | |
wavefile.close() | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment