Failed to open WebSocket and AttributeError: 'SpeechToTextClient' error (Watson on Python)

Failed to open WebSocket and AttributeError: 'SpeechToTextClient' error (Watson on Python)

我正在尝试使用 Python v2.7

为 Watson 上的 Speech to text recognition 打开一个网络套接字连接

我的代码使用 API 键加上 url。我已经尝试了几种方法来使用它打开一个套接字,但是我得到一个带有流错误的网络套接字错误,如下所示:

Failed to open WebSocket.
Failed to open WebSocket.
Traceback (most recent call last): File "jasmineV3.py", line 78, in <module>
    SpeechToTextClient().close() File "jasmineV3.py", line 68, in close
    self.stream_audio_thread.join()
AttributeError: 'SpeechToTextClient' object has no attribute 'stream_audio_thread'

这是我正在尝试使用的代码:

#import os
#import time
#import json
import watson_developer_cloud
import speech_recognition as sr
from gtts import gTTS
from time import ctime
#from __future__ import print_function

from os.path import join, dirname
from watson_developer_cloud import SpeechToTextV1
from watson_developer_cloud.websocket import RecognizeCallback
from ws4py.client.threadedclient import WebSocketClient
import base64, json, ssl, subprocess, threading, time

class SpeechToTextClient(WebSocketClient):
    def __init__(self):

        speech_to_text = SpeechToTextV1(iam_api_key = 'xxxxxxxx', url = 'xxxxxxx')

        self.listening = False

        try:
            WebSocketClient.__init__(self, speech_to_text)
            self.connect()
        except: print "Failed to open WebSocket."

    def opened(self):
        self.send('{"action": "start", "content-type": "audio/l16;rate=16000"}')
        self.stream_audio_thread = threading.Thread(target=self.stream_audio)
        self.stream_audio_thread.start()

    def received_message(self, message):
        message = json.loads(str(message))
        if "state" in message:
            if message["state"] == "listening":
                self.listening = True
        print "Message received: " + str(message)

    def stream_audio(self):
        while not self.listening:
            time.sleep(0.1)

        reccmd = ["arecord", "-f", "S16_LE", "-r", "16000", "-t", "raw"]
        p = subprocess.Popen(reccmd, stdout=subprocess.PIPE)

        while self.listening:
            data = p.stdout.read(1024)

            try: self.send(bytearray(data), binary=True)
            except ssl.SSLError: pass

        p.kill()

    def close(self):
        self.listening = False
        self.stream_audio_thread.join()
        WebSocketClient.close(self)

try:
    stt_client = SpeechToTextClient()
    #raw_input()
    speech_to_text = SpeechToTextV1(
        iam_api_key = 'xxxxxxxxx',
        url = 'xxxxxxxx')
finally:
    SpeechToTextClient().close()

对于我的错误是什么,我有点迷茫。我该如何解决?

更新

因此,在对下面发布的答案进行反馈后,我想出了以下代码:

from watson_developer_cloud import SpeechToTextV1
from watson_developer_cloud.websocket import RecognizeCallback
from os.path import join, dirname

import watson_developer_cloud
import speech_recognition as sr
from gtts import gTTS
from time import ctime
from os.path import join, dirname
from watson_developer_cloud import SpeechToTextV1
from ws4py.client.threadedclient import WebSocketClient
import base64, json, ssl, subprocess, threading, time
import os
import json

speech_to_text = SpeechToTextV1(
    username='{username}',
    password='{password}',
    iam_api_key = 'B5AmAyElAbvr6Z6dvW-CufLPwYsmKndNtAiGp4btg6s3',
    url = 'https://gateway-wdc.watsonplatform.net/speech-to-text/api/v1/recognize')

class MyRecognizeCallback(RecognizeCallback):
    def __init__(self):
        RecognizeCallback.__init__(self)

    def on_data(self, data):
        print(json.dumps(data, indent=2))

    def on_error(self, error):
        print('Error received: {}'.format(error))

    def on_inactivity_timeout(self, error):
        print('Inactivity timeout: {}'.format(error))

myRecognizeCallback = MyRecognizeCallback()

with open(join(dirname(__file__), '/home/ironmantis7x/Documents/MaverickAITech/JasmineAI', 'audio.mp3'),
              'rb') as audio_file:
    speech_to_text.recognize_using_websocket(
        audio=audio_file,
        content_type='audio/mp3',
        model='en-US_BroadbandModel',
        recognize_callback=myRecognizeCallback,
        interim_results=False,
        keywords=['hello', 'hi', 'turn on', 'directions'],
        keywords_threshold=0.5,
        max_alternatives=3) 

但现在我得到以下错误:

Traceback (most recent call last):
  File "jasmineV7.py", line 37, in <module>
    speech_to_text.recognize_using_websocket(
AttributeError: 'SpeechToTextV1' object has no attribute 'recognize_using_websocket'

我尝试对错误进行网络搜索,但并不清楚问题是什么,也不清楚如何正确修复它。

你的方法opened还没有被调用,所以当你调用closeself.stream_audio_thread不存在。

可能是因为您的网络套接字创建失败。通过在 运行 上的方法之前检查 self.stream_audio_thread 是否存在,确保您的 close 方法安全,并确定您的套接字创建失败的原因。

def close(self):
    self.listening = False
    if self.stream_audio_thread:
        self.stream_audio_thread.join()
    WebSocketClient.close(self)

我最终重写了采用不同方法实现我需要的代码。

解决方案在这里:

谢谢。