我在wav中有一堆文件。我制作了一个简单的脚本将它们转换为flac,以便我可以将它与google speech api一起使用。这是python代码:
import urllib2
url = "https://www.google.com/speech-api/v1/recognize?client=chromium&lang=en-US"
audio = open('somefile.flac','rb').read()
headers={'Content-Type': 'audio/x-flac; rate=16000', 'User-Agent':'Mozilla/5.0'}
request = urllib2.Request(url, data=audio, headers=headers)
response = urllib2.urlopen(request)
print response.read()
但是我收到了这个错误:
Traceback (most recent call last):
File "transcribe.py", line 7, in <module>
response = urllib2.urlopen(request)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 392, in open
response = self._open(req, data)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 410, in _open
'_open', req)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 370, in _call_chain
result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1194, in https_open
return self.do_open(httplib.HTTPSConnection, req)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1161, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error [Errno 32] Broken pipe>
我起初认为这是因为文件太大了。但我记录了自己5秒钟,它仍然是一样的。
我不认为google ha发布了api,所以很难理解为什么它失败了。
是否还有其他可以在Python或Node中使用的良好的语音到文本api?
-----编辑我的请求尝试:
import json
import requests
url = 'https://www.google.com/speech-api/v1/recognize?client=chromium&lang=en-US'
data = {'file': open('file.flac', 'rb')}
headers = {'Content-Type': 'audio/x-flac; rate=16000', 'User-Agent':'Mozilla/5.0'}
r = requests.post(url, data=data, headers=headers)
# r = requests.post(url, files=data, headers=headers) ## does not work either
# r = requests.post(url, data=open('file.flac', 'rb').read(), headers=headers) ## does not work either
print r.text
产生与上述相同的问题。
答案 0 :(得分:0)
API接受HTTP POST请求。您在此处使用HTTP GET请求。这可以通过将代码中的URI直接加载到浏览器中来确认:
HTTP method GET is not supported by this URL
Error 405
另外,我建议使用requests
python库。见http://www.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file
最后,似乎API只接受长达15秒的段。也许你的错误是文件太大了?如果你可以上传一个示例flac文件,也许我们可以进一步诊断。