0
//=======Text to Speech==================
function tts($sentence)
{
     $fragment = array();
     $tmp = explode(" ",$sentence); 
     $tmp_ = ""; 
     $last_word = "";
     foreach ($tmp as $value) { 
          $tmp_.= "$value "; 
          $last_word = $value;
          if (strlen($tmp_) > 100) { 
               $last_tmp_.= ""; 
               array_push($fragment, $last_tmp_);
               $tmp_ = $last_word." ";
               $last_tmp_ = "";               
          } 
          $last_tmp_ = $tmp_; 
     } 
     array_push($fragment, $last_tmp_);
     foreach ($fragment as &$value)
     {
          $value = str_replace(" ","+",$value);
     }

//     $sentence = str_replace(" ","+",$sentence);
     $name = 0;
     foreach($fragment as $value)
     {
          $url = "https://translate.google.com/translate_tts?tl=en&q=".$value;
          if ($name == 0)
               $fp = fopen("sound/combined.mp3","w");
          else
               $fp = fopen("sound/temp".$name.".mp3","w");
          $ch = curl_init($url);
          curl_setopt($ch, CURLOPT_FILE, $fp);
          $data = curl_exec($ch);
          curl_close($ch);
          fclose($fp);

          file_get_contents($url) or die("oops\n");
          $name++;
     }
     $count = 1;
     while ($count < $name)
     {
          file_put_contents('sound/combined.mp3',
                            file_get_contents('sound/combined.mp3') .
                            file_get_contents('sound/temp'.$count.'.mp3'));
          $count++;
     }
     $count = 1;
     while ($count < $name)
     {
          unlink("sound/temp".$count.".mp3");
          $count++;
     }
}
//=========IN=============
if($tts == 'in'){
tts($alias.'.');
$sound = '<embed src="database/sound/inbeep.mp3" width="0" height="0" ><embed src="database/sound/combined.mp3" width="0" height="0" >';
}

当我运行代码时,我转到错误代码“oops”,这意味着它无法创建文件,昨天它工作正常,我没有更改代码中的任何内容,我不知道谷歌是否阻止使用API 或我的代码有问题。

4

1 回答 1

1

您需要添加用户代理字符串,这样您就不会被告知来自 CURL。你在循环中的代码应该是这样的:

$url = "https://translate.google.com/translate_tts?tl=en&q=".$value;
if ($name == 0)
  $fp = fopen("sound/combined.mp3","w");
else
  $fp = fopen("sound/temp".$name.".mp3","w");
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36');
$data = curl_exec($ch);
curl_close($ch);
fclose($fp);
于 2013-09-25T03:35:08.347 回答