• 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);
    
    ?>
  • 相关阅读:
    Windows10如何删除“极速输入法”?
    python 递归实现 冒泡排序
    leetcode 912
    python 快速排序
    python 选择排序
    python 使用递归法对整数进行因数分解
    用函数嵌套定义和递归实现帕斯卡公式C(n,i) = C(n-1, i) + C(n-1, i-1), 进行组合数C(n,i)的快速求解。
    L2-3 清点代码库 (25 分)- 2021 天梯赛
    L2-2 病毒溯源 (25 分)
    快速幂
  • 原文地址:https://www.cnblogs.com/hyb1/p/3066558.html
Copyright © 2020-2023  润新知