2014年5月13日 星期二

PHP 文字轉語音(Text To Speech,TTS) Google Translation 下載成mp3檔案

      今天終於解決困擾我整個下午的程式問題,語音轉文字(TTS)問題,問題如標題所說,我想把這個網址(http://translate.google.com/translate_tts?tl=zh_TW&q=你好 )存成mp3檔案,但你如果是使用這個網址(http://translate.google.com/translate_tts?tl=en&q=hello), 透過php 的file_get_contents(url網址)函數下載是可行,而使用繁體中文就不行(會出現錯誤的語音),一開始想說是編碼上出了錯誤,但是不管我怎麼試(轉UTF-8、big5、UTF-16)都還是不行,最後我終於爬到我要的資料~原因出在少了一個query參數ie=utf-8。
程式碼如下:
<?php
 //http get query參數設定 tl設定國家語言(ex:en、zh_TW)  q設定要語音的 內容
$qs = http_build_query(array("ie" => "utf-8","tl" => 'zh_TW', "q" => '你好'));
$ctx = stream_context_create(array("http"=>array("method"=>"GET","header"=>"Referer: \r\n")));
$soundfile = file_get_contents("http://translate.google.com/translate_tts?".$qs, false, $ctx);
  //設定檔頭為影音檔
header("Content-type: audio/mpeg");
header("Content-Transfer-Encoding: binary");
header('Pragma: no-cache');
header('Expires: 0');
 
echo($soundfile);
?>