当前位置: 首页 > 知识库问答 >
问题:

音频流Python上的Google流语音识别

印曜灿
2023-03-14

我已经搜索了Google的所有可用文档,但我找不到Python音频流上的流式语音识别示例。

目前,我正在Django中使用Python语音识别从用户那里获取音频,然后收听音频。然后,我可以保存文件并运行google语音识别,或者直接从创建的音频实例中运行。

有人能指导我如何对音频流执行流式语音识别吗?

共有3个答案

欧阳楚
2023-03-14

如果您使用React web app来流式传输客户端的音频,那么您可以参考此存储库以获取代码示例(或者您可以克隆它并添加您的专有代码)https://github.com/saharmor/realtime-transcription-playground

子车俊哲
2023-03-14

这是上述要求的工作代码。

代码:

import asyncio
import websockets
import json
import threading
from six.moves import queue
from google.cloud import speech
from google.cloud.speech import types


IP = '0.0.0.0'
PORT = 8000

class Transcoder(object):
    """
    Converts audio chunks to text
    """
    def __init__(self, encoding, rate, language):
        self.buff = queue.Queue()
        self.encoding = encoding
        self.language = language
        self.rate = rate
        self.closed = True
        self.transcript = None

    def start(self):
        """Start up streaming speech call"""
        threading.Thread(target=self.process).start()

    def response_loop(self, responses):
        """
        Pick up the final result of Speech to text conversion
        """
        for response in responses:
            if not response.results:
                continue
            result = response.results[0]
            if not result.alternatives:
                continue
            transcript = result.alternatives[0].transcript
            if result.is_final:
                self.transcript = transcript

    def process(self):
        """
        Audio stream recognition and result parsing
        """
        #You can add speech contexts for better recognition
        cap_speech_context = types.SpeechContext(phrases=["Add your phrases here"])
        client = speech.SpeechClient()
        config = types.RecognitionConfig(
            encoding=self.encoding,
            sample_rate_hertz=self.rate,
            language_code=self.language,
            speech_contexts=[cap_speech_context,],
            model='command_and_search'
        )
        streaming_config = types.StreamingRecognitionConfig(
            config=config,
            interim_results=False,
            single_utterance=False)
        audio_generator = self.stream_generator()
        requests = (types.StreamingRecognizeRequest(audio_content=content)
                    for content in audio_generator)

        responses = client.streaming_recognize(streaming_config, requests)
        try:
            self.response_loop(responses)
        except:
            self.start()

    def stream_generator(self):
        while not self.closed:
            chunk = self.buff.get()
            if chunk is None:
                return
            data = [chunk]
            while True:
                try:
                    chunk = self.buff.get(block=False)
                    if chunk is None:
                        return
                    data.append(chunk)
                except queue.Empty:
                    break
            yield b''.join(data)

    def write(self, data):
        """
        Writes data to the buffer
        """
        self.buff.put(data)


async def audio_processor(websocket, path):
    """
    Collects audio from the stream, writes it to buffer and return the output of Google speech to text
    """
    config = await websocket.recv()
    if not isinstance(config, str):
        print("ERROR, no config")
        return
    config = json.loads(config)
    transcoder = Transcoder(
        encoding=config["format"],
        rate=config["rate"],
        language=config["language"]
    )
    transcoder.start()
    while True:
        try:
            data = await websocket.recv()
        except websockets.ConnectionClosed:
            print("Connection closed")
            break
        transcoder.write(data)
        transcoder.closed = False
        if transcoder.transcript:
            print(transcoder.transcript)
            await websocket.send(transcoder.transcript)
            transcoder.transcript = None

start_server = websockets.serve(audio_processor, IP, PORT)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
赵景曜
2023-03-14

Google在这里提供了一个流式Python API的示例。

不要打开音频文件来创建流(如该示例的第34行所示),而是将流直接传递给音频样本对象(如第36行所示)。

 类似资料:
  • 我已经实现了云语音API流识别服务。我能够通过FLAC文件并获得输出,但它不能连续识别,也不能发出放着还在说话。一旦我的录音完成,那么只有我从云API得到响应。请建议我如何从谷歌语音API获得连续识别。请帮助我

  • 我想开发一个模块,它将使用Android中的语音到文本支持。我发现了许多与RecogenerIntent等相关的文档和演示。但我发现所有这些演示都只是在10秒左右的时间里播放声音。但我想让我的演示运行5-10分钟以上。如果不是离线运行,我不会有任何问题,因为我的应用程序总是在线运行。 我也看过Android上的Pocketsphinx,但效果不太好。此外,它只支持Android Studio,而不

  • 我目前正在从事一个Android AppEngine项目,使用语音作为主要输入方法。在android上,您可以使用语音包将语音命令转换为纯文本。语音识别不是在设备本身上完成的,而是发送到一个谷歌服务器,该服务器返回文本。 供您参考:http://developer.android.com/resources/articles/speech-input.html 我的目标是使用相同的google服务

  • 这里我有记录音频流文件的代码。问题是我想保存这个文件与正确的文件扩展名(主要是. mp3和. aac)。我该如何实现这一点?

  • 代码: 如果无法流式传输,是否可以在/tmp文件夹中开始下载并边下载边播放?

  • 需要您的帮助,我检查音频流是否当您按下按钮或当程序启动的时刻,当您按下按钮,音频流是不可用的,然后没有发生,音乐没有播放,没有任何响应从程序没有我想让您认识到如何这样的响应尽可能做吗?