Google TTS(文字转语音)api 2

上一次只是说了Google TTS API 的原理,这次自己用php实现了下,主要就一个函数参数为两个,第一个是需要朗读的文字,第二个参数是语言,另外发现一个问题,如果在语言为zh-cn的时候,里面包含的英文,朗读出来都是逐字母朗读的。而如果是en-us语言却包含中文的话中文部分将不会有任何声音。下面是实现代码,可直接运行。

将这段代码加入到微信公众平台中,你发送消息,将会自动将你刚刚说的汉字翻译成mp3音乐回传给用户,用户点击将会播放,要是将小i机器人或者小黄鸡的聊天机器人API接上,就可以根据用户发送的内容智能回复相关信息,要是再引入Google的语音识别(目前还没找到Google提供的api),微信显示效果图:

php code :

<?php
class GoogleTTS
{
    public function getGoogleTTS($key,$tl='zh-cn'){
    $post_data =
       array(
            'idx=0',
            'ie=UTF-8',
            'q='.$key,
            'tl='.$tl,
            'total=1',
            'textlen='.(string)mb_strlen($key,"UTF-8")
       );
       $post_data = implode('&',$post_data);
        
       
       $url="http://translate.google.com/translate_tts";

       $ch = curl_init();

       curl_setopt($ch, CURLOPT_URL, $url);
       curl_setopt( $ch, CURLOPT_REFERER, "http://translate.google.com" ); 
       curl_setopt( $ch, CURLOPT_HEADER, true ); 
       curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); 
       curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 5.1; rv:20.0) Gecko/20100101 Firefox/20.0" );  
       curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: translate.google.com'));        //host
       curl_setopt( $ch, CURLOPT_POST, true ); 
       curl_setopt( $ch, CURLOPT_POSTFIELDS, $post_data );
       //curl_setopt($ch, CURLOPT_COOKIE, $matches[1][0]);
       $content = curl_exec($ch);
       curl_close($ch);
       $response_msg=trim($content);
       return $content;
   }
}
$obj=new GoogleTTS;
$ContentString = $obj->getGoogleTTS("who are you?你是誰?");
$randfilestring = time().'_'.sprintf('%02d', rand(0,999)).".mp3";
file_put_contents($randfilestring,$ContentString);

?>

 

posted @ 2013-05-08 12:58  重庆Debug  阅读(3905)  评论(2编辑  收藏  举报