2017-09-12 10 views
0

私はこのコードを使用して、ユーザーの言葉を話し、Google Cloud Speech APIを使ってテキストに変換します。これはGoogleのこの例に基づいて書かれています:https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/speech/cloud-client/transcribe_streaming_mic.pyPythonどのように私はサーバーの応答を待っているブロックジェネレータから抜け出すのですか?

私は、インターネット接続の問題があるときはいつでも転写プロセスを停止するエラーハンドラを追加したかったのです。私は数秒ごとにインターネット接続をチェックする接続モニタスレッドを作成し、フラグ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 <url removed>. 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

Kennyの示唆したように、私は別のスレッドでジェネレータを実行するだけです。完璧に動作します

0

我々はリスナーとエミッタ上のWebSocketを通じて同じことを達成しましたWebページからJavaサービスへの音声テキストの接続

関連する問題