计算机技术

Google TTS API 文字转语音 继续谈

上一次只是说了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);

?>

原文地址:http://www.cnblogs.com/hyb1/archive/2013/05/08/3066558.html

对这篇文章感觉如何?

太棒了
0
不错
0
爱死了
0
不太好
0
感觉很糟
0

You may also like

Leave a reply

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据

计算机技术

Firebug 与 DevTools 的集成

你可能已经听说过我们对统一 Firefox 的本地开发人员工具(DevTools)和 Firebug 的努力。我们一直在努力地将的所有最喜欢的 Firebug 功能添加到本地 DevTools 中,使 […]
计算机技术

判断Linux服务器架构是32位/64位

作为一个 Unix 系统的新手用户,我可以怎么判断我的 Unix 服务器安装的是32位或者64位的操作系统呢?你可以使用如下的命令来获取关于 Unix 内核和 CPU 架构的信息。