假期,Google 演讲 API

urlopen, Google speech API

我想使用下面的 Python 代码和 wav 文件(或其他格式的音频文件)来使用 Google 的语音 API。我现在收到一个损坏的管道错误,我不知道如何修复。一直在阅读一些关于改变 headers here, but feel I would need some guidance there if this is the way forward. Don't know if this is actually supposed to work, using the Google Web Speech API Demo:

我的代码:

#!/usr/bin/python
import sys
import urllib.request
import urllib.parse
import json
import scipy.io.wavfile

try:
    filename = sys.argv[1]
except IndexError:
    print('Usage: transcribe.py <file>')
    sys.exit(1)

rate, data = scipy.io.wavfile.read(filename)

url = 'https://www.google.com/intl/en/chrome/demos/speech.html'
headers = {'Content-type': 'audio/wav; rate=16000'}
# Possibly use this somehow later on...
# user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'
# values = {'name' : 'Michael Foord',
          'location' : 'Northampton',
          'language' : 'Python' }

req = urllib.request.Request(url, data, headers)

try:
    ret = urllib.request.urlopen(req)
except urllib.error.URLError as e:
    print(e.reason)
    sys.exit(1)

resp = ret.read()
text = json.loads(resp)['hypotheses'][0]['utterance']
print(text)

您使用的url不正确APIurl,v1语音API的url是https://www.google.com/speech-api/v1/recognize,但是,它已经被拒绝了很长一段时间。详见

Google speech Api v1 not working?

您可能想将流式传输 API v2 与 Google 一起使用,但这些需要 API 密钥,详情请参阅 https://github.com/gillesdemey/google-speech-v2

总的来说,我建议您改用现有的包装器,它将隐藏所有 API 复杂性。这个包装应该不错:

https://pypi.python.org/pypi/SpeechRecognition/

您仍然需要来自 google 的 API 密钥。

或者,您可以使用其他 API 端点,例如 Microsoft 的 Project Oxford。