Google的语音识别API,支持各种语言

要使用这个API,你得先有一些心理素质:面对倒霉的FLAC格式,因为这个API只支持FLAC格式的数据,杯具啊。

不过你找到了我的博客,那么你是幸福的,因为我已经为你准备了不少好东西了。(顺便说一句,如果要转载记得清楚地标注“来自http://blog.laobubu.net”,我信任你。)

现在看看如何请求数据:

  • 【URL】http://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&lang=zh-CN
  • 【方式】POST
  • 【请求头】Content-Type:audio/x-flac; rate=16000
  • 【POST】flac文件的数据
  • 【URL里可选参数】&maxresults=返回结果数

如果你人品大爆发,你成功了,可以得到类似这个的结果

{"status":0,"id":"54e1babccaa58682ffbb02ceb42aa47c-1",
"hypotheses":[{"utterance":"测试程序","confidence":0.8556527}]}

或者你的请求URL里设置了maxresults(比如 http://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&lang=zh-CN&maxresults=10 )你就会得到:

{"status":0,"id":"fbf23a887b9ac2bfb630aa40dd1a776c-1","hypotheses":
[
{"utterance":"欢迎访问过的网址","confidence":0.7275984},
{"utterance":"欢迎访问我的网站"},
{"utterance":"欢迎访问我的网址"},
{"utterance":"欢迎访问过的网站"},
{"utterance":"白云访问过的网址"},
{"utterance":"怀孕访问过的网址"},
{"utterance":"欢迎访问有的网址"},
{"utterance":"欢迎访问过的网址哦"},
{"utterance":"白云访问我的网站"},
{"utterance":"怀孕访问我的网站"}
]
}

不过不简单哦

实例

Python代码

  1. #By laobubu.net
  2. import  urllib2
  3. FILE= '1.flac'  #这里假设在当前文件夹下有一个叫1.flac的文件被识别
  4. url =  'http://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&lang=zh-CN'
  5. audio= open (FILE, 'rb' ). read ( )
  6. headers =  { 'Content-Type' :  'audio/x-flac; rate=16000' }
  7. req =  urllib2. Request (url, audio, headers )
  8. response =  urllib2. urlopen (req )
  9. print response. read ( ). decode ( 'UTF-8' )

PHP代码

  1.  
  2. <?php
  3. $ch  = curl_init ( ) ;
  4. curl_setopt ( $ch , CURLOPT_URL ,  "http://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&lang=zh-CN&maxresults=10" ) ;
  5. curl_setopt ( $ch , CURLOPT_VERBOSE ,  0 ) ;
  6. curl_setopt ( $ch , CURLOPT_HEADER ,  0 ) ;
  7. curl_setopt ( $ch , CURLOPT_POST ,  1 ) ;
  8. curl_setopt ( $ch , CURLOPT_RETURNTRANSFER ,  1 ) ;
  9. curl_setopt ( $ch , CURLOPT_POSTFIELDS ,  file_get_contents ( '1.flac' ) ) ;
  10. curl_setopt ( $ch , CURLOPT_HTTPHEADER ,  array ( "Content-Type: audio/x-flac; rate=16000" ) ) ;
  11. $data  = curl_exec ( $ch ) ;
  12. curl_close ( $ch ) ;
  13. if  ( $data =json_decode ( $data , true ) )  {
  14.   echo  "<ul>" ;
  15.   foreach ( $data [ 'hypotheses' ]  as  $i )  echo  "<li>" . $i [ 'utterance' ] . "</li>" ;
  16.   echo  "</ul>" ;
  17. }  else  {
  18.   echo  "<i>识别出错</i>" ;
  19. }
  20. ?>

头疼:FLAC文件格式

这里我长话短说,google的flac也有限制,22050 Hz+201kbps还正常,如果比这个大多了就不对了。

不过还有最要命的问题,怎么生成FLAC文件?

没关系,这里有救星:flac.exe包下载

http://datastorage.laobubu.net/FLAC.zip 

具体使用方法是【flac.exe 文件.wav】这样在命令行调用即可,测试得知:不支持MP3等格式,但是支持基本的wav格式。

至于其他环境下(如linux里)也有对应的flac下载。我没有怎么用过linux就不说啥了。

好了,你可以去制造你的app了,哈哈。

来自laobubu实验室自动转换API

为了方便,我写了一个python程序,放在Google App Engine上面,只要提交一个音频文件的URL(支持MP3、wav等常见格式),且文件不大,就可以得到结果了哦。

API入口:http://laobubumf.appspot.com/stt/
备用入口:http://glab.laobubu.net/stt/

猜你喜欢

转载自huaonline.iteye.com/blog/1890507