0

最近,我尝试创建一个程序,可以将实时音频流转换为文本并搜索关键字。然后我希望它激活另一个监听功能。我目前的代码如下(没有第二个监听功能):

from __future__ import print_function
import json
from os.path import join, dirname
from watson_developer_cloud import SpeechToTextV1
from watson_developer_cloud.websocket import RecognizeCallback, AudioSource
import threading

# If service instance provides API key authentication
# service = SpeechToTextV1(
#     ## url is optional, and defaults to the URL below. Use the correct URL for your region.
url='https://stream.watsonplatform.net/speech-to-text/api',
#     iam_apikey='your_apikey')

service = SpeechToTextV1(
    username='MY USERNAME',
    password='MY PASSWORD',
    url='https://stream.watsonplatform.net/speech-to-text/api')
"""
models = service.list_models().get_result()
print(json.dumps(models, indent=2))

model = service.get_model('en-US_BroadbandModel').get_result()
print(json.dumps(model, indent=2))

with open(join(dirname(__file__), 'audio-file.flac'),
          'rb') as audio_file:
    print(json.dumps(
        service.recognize(
            audio=audio_file,
            content_type='audio/flac',
            timestamps=True,
            word_confidence=True).get_result(),
        indent=2))
`"""
# Example using websockets
class MyRecognizeCallback(RecognizeCallback):
    def __init__(self):
        RecognizeCallback.__init__(self)

    def on_transcription(self, transcript):
        print(transcript)


    def on_connected(self):
        print('Connection was successful')

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

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

    def on_listening(self):
        print('Service is listening')

    def on_hypothesis(self, hypothesis):
        print(hypothesis)

    def on_data(self, data):
        print(data)

# Example using threads in a non-blocking way
mycallback = MyRecognizeCallback()
audio_file = open(join(dirname(__file__), 'audio-file.flac'), 'rb')
audio_source = AudioSource(audio_file)
recognize_thread = threading.Thread(
    target=service.recognize_using_websocket,
    args=(audio_source, "audio/wav; rate=44100", mycallback))
recognize_thread.start()

此代码当前返回以下错误:

Error received: unable to transcode data stream audio/wav -> audio/x-float-array 
Error received: 'NoneType' object has no attribute 'connected'

附件是python返回的所有内容:

错误截图

我目前正在使用 python 3.4.2 运行 x64 位 windows 10

编辑:

错误消息现在似乎已更改为以下内容:

Error received: unable to transcode data stream audio/wav -> audio/x-float-array 
Error received: [WinError 10014] The system detected an invalid pointer address in attempting to use a pointer argument in a call
4

1 回答 1

0

编辑:您的脚本不起作用,因为您正在将音频/wav 与音频/flac 混合。它们是不同的格式,不能互换。

使用此代码将起作用,尽管我尚未测试通过线程运行它。

with open("audio-file.flac", "rb") as audio_file:
    audio_source = AudioSource(audio_file)
    print("Sending file to Watson...")
    stt_auth.recognize_using_websocket( 
        audio=audio_source, 
        content_type="audio/flac", 
        recognize_callback=mycallback,
        interim_results=True, # Print all attempts, including not final responses.
    )

我会尝试使用文件名作为参数来设置线程。请注意,我自己没有对此进行测试,但它应该可以工作。

def play_audiofile(name):
    with open("audio-file.flac", "rb") as audio_file:
        audio_source = AudioSource(audio_file)
        print("Sending file to Watson...")
        stt_auth.recognize_using_websocket( 
            audio=audio_source, 
            content_type="audio/flac", 
            recognize_callback=mycallback,
            interim_results=True, # Print all attempts, including not final responses.
        )

play_file_in_background = Thread(target=play_audiofile, args="audio-file.flac")
play_file_in_background.start()

while play_file_in_background.isAlive():
    pass  # Don't end until it has finished
于 2019-03-23T15:10:18.037 回答