我想使用Python的
Google-cloud-speech
API从Web流式传输音频并将其转换为文本。我已经在我的Django channels代码中集成了它。对于前端,我直接复制了这个代码,后端有这个代码(请参见下面)。现在,问题来了,我没有得到任何异常或错误,但是我没有从谷歌API得到任何结果。
我尝试过:
我在
process
函数的循环内设置了调试点,但控制权从未进入循环内。我已经阅读了这里的Java代码here并试图理解它。我已经在本地安装并调试了java代码。我理解的一件事是,在java代码中,方法
onWebSocketBinary
接收一个整数数组,我们从前端发送它。
socket.send(Int16Array.from(floatSamples.map(function (n) {return n * MAX_INT;})));
在Java中,他们将其转换为bytestring然后发送到Google。 而在Django中,我设置了调试点并注意到我得到的是二进制字符串数据。 因此,我觉得我不需要对此进行任何处理。 但是,我尝试了几种将其转换为整数数组的方法,但那行不通,因为Google期望的就是字节本身(您可以在下面的注释代码中看到)。
Django代码:
import json
from channels.generic.websocket import WebsocketConsumer
# Imports the Google Cloud client library
from google.cloud import speech
from google.cloud.speech import enums
from google.cloud.speech import types
# Instantiates a client
client = speech.SpeechClient()
language_code = "en-US"
streaming_config = None
class SpeechToTextConsumer(WebsocketConsumer):
def connect(self):
self.accept()
def disconnect(self, close_code):
pass
def process(self, streaming_recognize_response: types.StreamingRecognitionResult):
for response in streaming_recognize_response:
if not response.results:
continue
result = response.results[0]
self.send(text_data=json.dumps(result))
def receive(self, text_data=None, bytes_data=None):
global streaming_config
if text_data:
data = json.loads(text_data)
rate = data["sampleRate"]
config = types.RecognitionConfig(
encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,
sample_rate_hertz=rate,
language_code=language_code,
)
streaming_config = types.StreamingRecognitionConfig(
config=config, interim_results=True, single_utterance=False
)
types.StreamingRecognizeRequest(streaming_config=streaming_config)
self.send(text_data=json.dumps({"message": "processing..."}))
if bytes_data:
# bytes_data = bytes_data[math.floor(len(bytes_data) / 2) :]
# bytes_data = bytes_data.lstrip(b"\x00")
# bytes_data = int.from_bytes(bytes_data, "little")
stream = [bytes_data]
requests = (
types.StreamingRecognizeRequest(audio_content=chunk) for chunk in stream
)
responses = client.streaming_recognize(streaming_config, requests)
self.process(responses)