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);

?>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM