正在等待语音服务器回应,Python如何突破正在等待服务器响应的阻塞生成器?

该博客讨论了如何在实时音频转文字过程中添加错误处理,特别是针对互联网连接问题。通过创建一个连接监测线程,当检测到连接错误时,会设置isConnectionError标志。主要关注的是在连接中断时如何终止音频录制和服务器响应的接收。同时,代码示例展示了如何监听和打印服务器的转录结果,并在检测到特定关键词时退出程序。
摘要由CSDN通过智能技术生成

我想添加一个错误处理程序,它可以在出现internet连接问题时停止转录过程。我创建了一个连接监视器线程,每隔几秒钟检查一次internet连接,并将设置一个标志isConnectionError = True。在

我设法停止音频录制生成器进程,但无法停止另一个阻止并等待服务器发送响应消息的生成器进程:def listen_print_loop(responses):

"""Iterates through server responses and prints them.

The responses passed is a generator that will block until a response

is provided by the server.

Each response may contain multiple results, and each result may contain

multiple alternatives; for details, see . Here we

print only the transcription for the top alternative of the top result.

In this case, responses are provided for interim results as well. If the

response is an interim one, print a line feed at the end of it, to allow

the next result to overwrite it, until the response is a final one. For the

final one, print a newline to preserve the finalized transcription.

"""

num_chars_printed = 0

for response in responses:

if not response.results:

continue

# The `results` list is consecutive. For streaming, we only care about

# the first result being considered, since once it's `is_final`, it

# moves on to considering the next utterance.

result = response.results[0]

if not result.alternatives:

continue

# Display the transcription of the top alternative.

transcript = result.alternatives[0].transcript

# Display interim results, but with a carriage return at the end of the

# line, so subsequent lines will overwrite them.

#

# If the previous result was longer than this one, we need to print

# some extra spaces to overwrite the previous result

overwrite_chars = ' ' * (num_chars_printed - len(transcript))

if not result.is_final:

sys.stdout.write(transcript + overwrite_chars + '\r')

sys.stdout.flush()

num_chars_printed = len(transcript)

else:

print(transcript + overwrite_chars)

# Exit recognition if any of the transcribed phrases could be

# one of our keywords.

if re.search(r'\b(exit|quit)\b', transcript, re.I):

print('Exiting..')

break

num_chars_printed = 0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值