When working with pyaudio, the following OSError occurred: [Errno -9988] Stream closed

24 Views Asked by At

When working with pyaudio, the following OSError occurred: [Errno -9988] Stream closed, please help me figure it out. Here's all my code.

q = queue.Queue()

model = vosk.Model('model_small')

device = sd.default.device

samplerate = int(sd.query_devices(device[0], 'input')['default_samplerate'])

def callback(indata, frames, time, status):

q.put(bytes(indata))
def recognize(data, vectorizer, clf): # get the vector of the received text # compare with the options, getting the most suitable answer text_vector = vectorizer.transform([data]).toarray()[0] answer = clf.predict([text_vector] )[0]

getting function name from response from data_set
func_name = answer.split()[0]

voice response from the data_set model
vois_pyttsx3.speaker(answer.replace(func_name, ''))

running a function from skills
exec(func_name + '()')
def maun(): # Create an instance of a Porcupine object with the path to the activation phrase model porcupine = pvporcupine.create( access_key=words.accessKey, keyword_paths=[words.KEYWORD_PATH], model_path=words.modelPath )

Getting audio stream parameters
pa = pyaudio.PyAudio()

Defining audio stream parameters
stream = pa.open(
rate=porcupine.sample_rate,
channels=1,
format=pyaudio.paInt16,
input=True,
frames_per_buffer=porcupine.frame_length
)

while True:
pcm = stream.read(porcupine.frame_length)
pcm = struct.unpack_from("h" * porcupine.frame_length, pcm)

# Check if input audio is included in the activation phrase
keyword_index = porcupine.process(pcm)

# If the activation phrase is recognized, perform the necessary actions
if keyword_index >= 0:
print("Action associated with activation phrase")
vois_pyttsx3.speaker('yes sir')
main(pa, stream)
pa.terminate()
def main(pa, stream): vectorizer = CountVectorizer()

vectors = vectorizer.fit_transform(list(words.data_set.keys()))

clf = LogisticRegression()
clf.fit(vectors, list(words.data_set.values()))

del words.data_set

recognizer = vosk.KaldiRecognizer(model, 16000)

print("Recording...")
frames = []

for i in range(0, int(16000 / 8000 * 5)): # Record for 5 seconds
data = stream.read(8000)
frames.append(data)


print("Recording finished.")
stream.stop_stream()
stream.close()
pa.terminate()


data = b''.join(frames)
if recognizer.AcceptWaveform(data):
data = json.loads(recognizer.Result())['text']
recognize(data, vectorizer, clf)
if name == 'main': maun()

Initially, I wanted to recognize the activation phrase in the maun function, and in the main function record the voice in five-second segments with further processing. and the first command everything works well, but then it doesn’t.

0

There are 0 best solutions below