Skip to content

Instantly share code, notes, and snippets.

@SqyD
Created May 18, 2021
Embed
What would you like to do?
Quick and dirty Python script to allow a handsfree recording, based on https://pimylifeup.com/raspberry-pi-porcupine/
#!/usr/bin/env python3
import struct
import pyaudio
import pvporcupine
import wave
import time
porcupine = None
pa = None
audio_stream = None
wav_data = []
recording = 0
try:
porcupine = pvporcupine.create(keywords=["picovoice", "blueberry"])
pa = pyaudio.PyAudio()
audio_stream = pa.open(
# input_device_index=3,
rate=porcupine.sample_rate,
channels=1,
format=pyaudio.paInt16,
input=True,
frames_per_buffer=porcupine.frame_length)
while True:
voice_pcm = audio_stream.read(porcupine.frame_length)
wake_pcm = struct.unpack_from("h" * porcupine.frame_length, voice_pcm)
keyword_index = porcupine.process(wake_pcm)
if keyword_index >= 0:
if recording == 0:
print("Hotword Detected, recording started.")
recording = time.time()
wav_data = []
if time.time() > recording + 3:
print("Hotword Detected, recording stopped.")
recording = 0
timestr = time.strftime("%Y%m%d-%H%M%S")
wave_file_name = "/tmp/showermic_" + timestr + ".wav"
wave_file = wave.open(wave_file_name, 'wb')
wave_file.setnchannels(1)
wave_file.setsampwidth(pa.get_sample_size(pyaudio.paInt16))
wave_file.setframerate(porcupine.sample_rate)
wave_file.writeframes(b''.join(wav_data))
wave_file.close()
print("Recording save as " + wave_file_name)
if recording > 0:
wav_data.append(voice_pcm)
finally:
if porcupine is not None:
porcupine.delete()
if audio_stream is not None:
audio_stream.close()
if pa is not None:
pa.terminate()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment