16

我有一个 mp3 文件,我想使用 Google 的语音识别从该文件中获取文本。任何我能找到文档或示例的想法都将不胜感激。

4

1 回答 1

42

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

如何:

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

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

然后在 Cloud Platform Console 中,转到项目页面并选择或创建一个新项目。在您需要为项目启用计费后,请启用 Cloud Speech API

启用 Google Cloud Speech API 后,单击 Go to Credentials 按钮设置您的 Cloud Speech API 凭据

有关如何从您的代码授权 Cloud Speech API 服务的信息,请参阅设置服务帐户

您应该获取服务帐户密钥文件(JSON 格式)和 GOOGLE_APPLICATION_CREDENTIALS 环境变量,该变量将允许您对语音 API 进行身份验证

完成后,从谷歌下载音频原始文件,以及从谷歌下载语音发现_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
于 2016-08-05T12:10:15.113 回答