Skip to content

Instantly share code, notes, and snippets.

@cmetz
Last active Feb 14, 2018
Embed
What would you like to do?
Simple Matrix creator recorder example - starts recording when it detects some sound (python)
import alsaaudio
import wave
import struct
import time
SAMPLE_RATE = 16000
mic = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, device='mic_channel8')
mic.setchannels(1)
mic.setrate(SAMPLE_RATE)
mic.setformat(alsaaudio.PCM_FORMAT_S16_LE)
mic.setperiodsize(160)
output = wave.open('test.wav', 'w')
output.setparams((1, 2, SAMPLE_RATE, 0, 'NONE', 'not compressed'))
# wait a secound, to not catch any unwanted noise e.g. keyboard
time.sleep(1)
print('listening ...')
recording = False
recording_idle = 0
while True:
length, data = mic.read()
sound_detected = True if max(struct.unpack('<%dh' % length, data)) > 20000 else False
if not recording and sound_detected:
print('started recording - waiting for 2 sec idle')
recording = True
if recording:
if sound_detected:
recording_idle = 0
else:
recording_idle += length
if recording_idle // SAMPLE_RATE >= 2:
print('stopped recording')
break
output.writeframesraw(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment