谷歌云语音API python代码示例可能存在错误

谷歌云语音API python代码示例可能存在错误,python,google-speech-api,Python,Google Speech Api,我正在使用谷歌语音API提供的代码片段。代码应足以将.wav文件转换为转录文本 感兴趣的区块如下: def transcribe_file(speech_file): """Transcribe the given audio file.""" from google.cloud import speech speech_client = speech.Client() with io.open(speech_file, 'rb') as audio_file:

我正在使用谷歌语音API提供的代码片段。代码应足以将.wav文件转换为转录文本

感兴趣的区块如下:

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

    with io.open(speech_file, 'rb') as audio_file:
        content = audio_file.read()
        audio_sample = speech_client.sample(
            content=content,
            source_uri=None,
            encoding='LINEAR16',
            sample_rate_hertz=16000)

    alternatives = audio_sample.recognize('en-US')
    for alternative in alternatives:
        print('Transcript: {}'.format(alternative.transcript))
首先,我认为代码可能很旧,必须将
sample\u rate\u hertz=16000
更改为
sample\u rate=16000

在那之后,我得到了这一行的错误:
alternatives=audio\u sample.recognize('en-US')

哪个读到了
AttributeError:“Sample”对象没有属性“recognize”


我很好奇如何纠正这一点。我似乎找不到关于这种方法的任何文档。也许它也需要更换

您使用的是github quickstart.py示例,因此我怀疑它与文档不同步。但它仍然是BETA版

假设
isinstance(音频样本)==True

然后
。在您的

alternatives = audio_sample.recognize('en-US')
应该是其中之一

async_recognize, streaming_recognize, sync_recognize

您需要将文件读取为二进制文件,然后将
service.speech().syncrecognize
body参数(dict)一起使用,该参数包含所有必需的参数,如:

  • 编码
  • 采样器
  • (语言)
你可以试试这样的东西吗

with open(speech_file, 'rb') as speech:
    speech_content = base64.b64encode(speech.read())

service = get_speech_service()
service_request = service.speech().syncrecognize(
    body={
        'config': {
            'encoding': 'LINEAR16',  # raw 16-bit signed LE samples
            'sampleRate': 16000,  # 16 khz
            'languageCode': 'en-US',  # a BCP-47 language tag
        },
        'audio': {
            'content': speech_content.decode('UTF-8')
            }
        })
response = service_request.execute()
print(json.dumps(response))
请看一看,因为有一个类似的工作示例。

请看一看,因为有一个类似的工作示例