如何在python中使用谷歌语音识别api?

时间:2016-08-01 16:34:38

标签: google-api google-speech-api

堆栈溢出可能不是问这个问题的最佳位置,但我需要帮助。我有一个mp3文件,我想使用谷歌的语音识别来获取该文件的文本。任何我可以找到文档或示例的想法都将不胜感激。

1 个答案:

答案 0 :(得分:41)

查看Google Cloud Speech API,使开发人员能够将音频转换为文本[...] API可识别80多种语言和变体[...] 您可以创建一个免费帐户来获取有限数量的API请求。

如何:

首先需要安装gcloud python module& google-api-python-client模块:

pip install --upgrade gcloud
pip install --upgrade google-api-python-client

然后在Cloud Platform控制台中,转到“项目”页面,选择或创建新项目。在您需要为项目启用结算后,请enable Cloud Speech API

启用Google Cloud Speech API后,点击转到凭据按钮以设置您的Cloud Speech API凭据

有关如何通过代码

授权Cloud Speech API服务的信息,请参阅Set Up a Service Account

您应该同时获得服务帐户密钥文件(使用JSON)和GOOGLE_APPLICATION_CREDENTIALS环境变量,以便您对Speech API进行身份验证

完成所有操作后,来自Google的download the audio raw file以及来自Google的speech-discovery_google_rest_v1.json

修改以前下载的JSON文件以设置您的凭据密钥 然后确保您已将GOOGLE_APPLICATION_CREDENTIALS环境变量设置为.json文件的完整路径:

export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service_account_file.json

确保您已将GCLOUD_PROJECT环境变量设置为您的Google Cloud项目的ID:

export GCLOUD_PROJECT=your-project-id

假设已完成,您可以创建一个 tutorial.py 文件,其中包含:

import argparse
import base64
import json

from googleapiclient import discovery
import httplib2
from oauth2client.client import GoogleCredentials


DISCOVERY_URL = ('https://{api}.googleapis.com/$discovery/rest?'
                 'version={apiVersion}')


def get_speech_service():
    credentials = GoogleCredentials.get_application_default().create_scoped(
        ['https://www.googleapis.com/auth/cloud-platform'])
    http = httplib2.Http()
    credentials.authorize(http)

    return discovery.build(
        'speech', 'v1beta1', http=http, discoveryServiceUrl=DISCOVERY_URL)


def main(speech_file):
    """Transcribe the given audio file.

    Args:
        speech_file: the name of the audio file.
    """
    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))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'speech_file', help='Full path of audio file to be recognized')
    args = parser.parse_args()
    main(args.speech_file)

然后运行:

python tutorial.py audio.raw
相关问题