Google Speech to Text API 使用 Python 转录音频数据 - 解码错误

问题描述

我正在尝试按照本教程 https://cloud.google.com/speech-to-text/docs/async-recognize 使用 Google Speech to Text API 转录音频数据。

我有一个允许用户录制音频的表单。我正在使用此代码从表单中请求音频数据:

f = request.files['audio_data'].read()

我想出了如何将音频数据 (f) 保存到 GCS 存储桶并通过将文件位置传递给教程中的函数(也在下面复制)来获取转录。但是,我想避免创建/上传 .wav 文件的步骤,并让 API 直接使用录制的音频数据。

我拥有的音频数据采用这种格式:

b'RIFF$\x00\x04\x00WAVEfmt \x10\x00\x00\x00\x01\x00\x01\x00\x80\xbb\x00\x00\x00\xee\x02\ (...) x00\x00\x00\x00\x00'

我收到以下错误消息:

UnicodeDecodeError: 'utf-8' 编解码器无法解码字节 0x80 的位置 24:无效的起始字节

这是 Python 函数

def transcribe_file(speech_file):
    """Transcribe the given audio file asynchronously."""
    from google.cloud import speech

    client = speech.SpeechClient()

    with io.open(speech_file,"rb") as audio_file:
        content = audio_file.read()

    """
     Note that transcription is limited to a 60 seconds audio file.
     Use a GCS file for audio longer than 1 minute.
    """
    audio = speech.RecognitionAudio(content=content)

    config = speech.RecognitionConfig(
        encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,sample_rate_hertz=16000,language_code="en-US",)


    operation = client.long_running_recognize(config=config,audio=audio)

    print("Waiting for operation to complete...")
    response = operation.result(timeout=90)

    # Each result is for a consecutive portion of the audio. Iterate through
    # them to get the transcripts for the entire audio file.
    for result in response.results:
        # The first alternative is the most likely one for this portion.
        print(u"Transcript: {}".format(result.alternatives[0].transcript))
        print("Confidence: {}".format(result.alternatives[0].confidence))

我尝试了几种编码/解码建议,例如此处:UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 3131: invalid start byte 但这些解决方案似乎都不适合我。

我做错了什么?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)