我的 Azure 语音识别不会在识别文件时停止



我使用 Azure 提供的演示代码创建了一个 Azure 语音识别应用。但是,完成音频文件的语音识别后,除非我使用 ctrl-c,否则 Azure 语音不会关闭并显示以下内容。我想知道为什么它不停止。

CLOSING on SpeechRecognitionCanceledEventArgs(session_id=..., result=SpeechRecognitionResult(result_id=..., text="", reason=ResultReason.Canceled)) CLOSING on SessionEventArgs(session_id=...)

def printRecognizedData(speech_result):
json_obj = json.loads(speech_result.result.json)
print(json_obj["DisplayText"])
speech_recognizer.recognized.connect(lambda evt: printRecognizedData(evt))
speech_recognizer.session_stopped.connect(stop_cb)
speech_recognizer.canceled.connect(stop_cb)
speech_recognizer.start_continuous_recognition()
while not done:
time.sleep(.5)
speech_recognizer.stop_continuous_recognition()

您可以尝试以下代码在识别文件时停止

try:
while(True):
frames = wav_fh.readframes(n_bytes // 2)
print('read {} bytes'.format(len(frames)))
if not frames:
break
stream.write(frames)
time.sleep(.1)
finally:    
#Stop recognition and clean up
speech_recognizer.stop_continuous_recognition()
wav_fh.close()
stream.close()

参考资料: 认知服务-语音-sdk/speech_sample.py at dfe81687569e67a95bcaaad3184ca949dd2c5264 ·Azure-Samples/cognitive-services-speech-sdk ·GitHub

在 2022 年,Azure 语音演示识别代码仍然类似,并且在成功识别后也没有终止。这是由于以下回调代码:

def stop_cb(evt):
"""callback that stops continuous recognition upon receiving an event `evt`"""
print('CLOSING on {}'.format(evt))
speech_recognizer.stop_continuous_recognition()
nonlocal done
done = True

调用stop_continuous_recognition()时,控件不再在stop_cb范围内,因此未更新done标志。我将这一行移到了末尾,如下所示:

def stop_cb(evt):
print(f'CLOSING on {evt}')
nonlocal done
done = True
speech_recognizer.stop_continuous_recognition()

这可确保done被修改,并导致正确退出 while 循环。这是完整性的完整转录代码:

def recognised_cb(evt):
print(evt.result.text)
def from_file():
speech_config = speechsdk.SpeechConfig(subscription="mykey", region="myregion")
audio_input = speechsdk.AudioConfig(filename)
speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config, audio_config=audio_input)
done = False
def stop_cb(evt):
print(f'CLOSING on {evt}')
nonlocal done
done = True
speech_recognizer.stop_continuous_recognition()
speech_recognizer.recognized.connect(recognised_cb)
speech_recognizer.session_stopped.connect(stop_cb)
speech_recognizer.canceled.connect(stop_cb)
speech_recognizer.start_continuous_recognition()
while not done:
time.sleep(.5)

相关内容

  • 没有找到相关文章