Last active
May 30, 2023 10:09
-
-
Save bygreencn/0f047342c337eee1e9938da873c414cb to your computer and use it in GitHub Desktop.
pyaudio record in thread
This file contains 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
# coding=utf-8 | |
# Python3.6 | |
# Class Record a wav in new thread | |
import threading | |
import pyaudio | |
import wave | |
from time import sleep | |
class RecordThread(threading.Thread): | |
def __init__(self, audiofile='record.wav'): | |
threading.Thread.__init__(self) | |
self.bRecord = True | |
self.audiofile = audiofile | |
self.chunk = 1024 | |
self.format = pyaudio.paInt16 | |
self.channels = 1 | |
self.rate = 16000 | |
def run(self): | |
audio = pyaudio.PyAudio() | |
wavfile = wave.open(self.audiofile, 'wb') | |
wavfile.setnchannels(self.channels) | |
wavfile.setsampwidth(audio.get_sample_size(self.format)) | |
wavfile.setframerate(self.rate) | |
wavstream = audio.open(format=self.format, | |
channels=self.channels, | |
rate=self.rate, | |
input=True, | |
frames_per_buffer=self.chunk) | |
while self.bRecord: | |
wavfile.writeframes(wavstream.read(self.chunk)) | |
wavstream.stop_stream() | |
wavstream.close() | |
audio.terminate() | |
def stoprecord(self): | |
self.bRecord = False | |
audio_record = RecordThread('record.wav') | |
audio_record.start() | |
sleep(2) | |
audio_record.stoprecord() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment