Heim > php教程 > PHP源码 > 通过google语音翻译把给定的文本生成音频文件

通过google语音翻译把给定的文本生成音频文件

PHP中文网
Freigeben: 2016-05-25 17:00:18
Original
1817 Leute haben es durchsucht
  1. 音频demo

<?php
//mp3格式
echo "http://www.codepearl.com/files/212.html";
Nach dem Login kopieren

2.demo

<?php
/**
 * http://www.codepearl.com
 */
 
include &#39;PHP_Text2Speech.class.php&#39;;
 
$t2s = new PHP_Text2Speech;
 
?>
<audio controls="controls" autoplay="autoplay">
  <source src="<?php echo $t2s->speak(&#39;代码珠玑 , 提供编程中 需要的各种工具类 , 算法 , 函数 , 解决方案 , 技术文档 , 致力于做您最好的代码 , 分享平台&#39;,"zh-CN"); ?>" type="audio/mp3" />
</audio>
Nach dem Login kopieren

3.操作类

<?php
//http://www.codepearl.com
/******************************************************************
Example:
<?php 
$t2s = new PHP_Text2Speech;
?>
  
// Simple example
<audio controls="controls" autoplay="autoplay">
  <source src="<?php echo $t2s->speak(&#39;www.codepearl.com&#39;,&#39;en&#39;); ?>" type="audio/mp3" />
</audio>
  
// Example use of other language
<audio controls="controls" autoplay="autoplay">
  <source src="<?php echo $t2s->speak(&#39;代码珠玑&#39;, &#39;zh-CN&#39;); ?>" type="audio/mp3" />
</audio>
  
******************************************************************/
  
class PHP_Text2Speech {
      
    /** Max text characters
     * @var Integer 
     */
    var $maxStrLen = 100;
      
    /** Text len
     * @var Integer 
     */
    var $textLen = 0;
      
    /** No of words
     * @var Integer 
     */
    var $wordCount = 0;
      
    /** Language of text (ISO 639-1)
     * @var String 
     * @link https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
     */
    var $lang = &#39;en&#39;;
      
    /** Text to speak
     * @var String 
     */
    var $text = NULL;
      
    /** File name format
     * @var String 
     */
    var $mp3File = "%s.mp3";
      
    /** Directory to store audio file
     * @var String 
     */
    var $audioDir = "audio/";
      
    /** Contents
    * @var  String
    */
    var $contents = NULL;
      
    /** Function make request to Google translate, download file and returns audio file path
     * @param   String  $text       - Text to speak
     * @param   String  $lang       - Language of text (ISO 639-1)
     * @return  String  - mp3 file path
     * @link https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
     */
    function speak($text, $lang = NULL) {
          
        if ($lang !== NULL) {
            $this->lang = $lang;
        }
          
        // Create dir if not exists
        if (!is_dir($this->audioDir)) {
            mkdir($this->audioDir, 0755) or die(&#39;Could not create audio dir: &#39; . $this->audioDir);
        }
          
        // Try to set writing permissions for audio dir.
        if (!is_writable($this->audioDir)) { 
            chmod($this->audioDir, 0755) or die(&#39;Could not set appropriate permissions for audio dir: &#39; . $this->audioDir);
        }
          
        // Can not handle more than 100 characters so split text
        if (strlen($text) > $this->maxStrLen) {
            $this->text = $text;
              
            // Generate unique mp3 file name
            $file = sprintf($this->mp3File, $this->audioDir . md5($this->text));
            if (!file_exists($file)) {
                $texts = array();
                $words = explode(&#39; &#39;, $this->text);
                $i = 0;
                $texts[$i] = NULL;
                foreach ($words as $w) {
                    $w = trim($w);
                    if (strlen($texts[$i] . &#39; &#39; . $w) < $this->maxStrLen) {
                        $texts[$i] = $texts[$i] . &#39; &#39; . $w; 
                    } else {
                        $texts[++$i] = $w;
                    }
                }
                  
                // Get get separated files contents and marge them into one
                foreach ($texts as $txt) {
                    $pFile = $this->speak($txt, $this->lang);
                    $this->contents .= $this->stripTags(file_get_contents($pFile));
                    unlink($pFile);
                }
                unset($words, $texts);
                  
                // Save file
                file_put_contents($file, $this->contents);
                $this->contents = NULL;
            }
        } else {
              
            // Generate unique mp3 file name
            $file = sprintf($this->mp3File, $this->audioDir . md5($text));
              
            if (!file_exists($file)) {
                // Text lenght
                $this->textLen = strlen($text);
                  
                // Words count
                $this->wordCount = str_word_count($text);
                  
                // Encode string
                $text = urlencode($text);
  
                // Download new file
                $this->download("http://translate.google.com/translate_tts?ie=UTF-8&q={$text}&tl={$this->lang}&total={$this->wordCount}&idx=0&textlen={$this->textLen}", $file);
            }
        }
          
        // Returns mp3 file path
        return $file;
    }
      
    /** Function to find the beginning of the mp3 file
     * @param   String  $contents       - File contents
     * @return  Integer
     */
    function getStart($contents) {
        for($i=0; $i < strlen($contents); $i++){
            if(ord(substr($contents, $i, 1)) == 255){
                return $i;
            }
        }
    }
      
    /** Function to find the end of the mp3 file
     * @param   String  $contents       - File contents
     * @return  Integer
     */
    function getEnd($contents) {
        $c = substr($contents, (strlen($contents) - 128));
        if(strtoupper(substr($c, 0, 3)) == &#39;TAG&#39;){
            return $c;
        }else{
            return FALSE;
        }
    }
  
    /** Function to remove the ID3 tags from mp3 files
     * @param   String  $contents       - File contents
     * @return  String
     */
    function stripTags($contents) {
        // Remove start
        $start = $this->getStart($contents);
        if ($start === FALSE) {
            return FALSE;
        } else {
            return substr($contents, $start);
        }
        // Remove end tag
        if ($this->getEnd($contents) !== FALSE){
            return substr($contents, 0, (strlen($contents) - 129));
        }
    }
      
    /** Function to download and save file
     * @param   String  $url        - URL
     * @param   String  $path       - Local path
     */
    function download($url, $path) { 
        // Is curl installed?
        if (!function_exists(&#39;curl_init&#39;)){ // use file get contents 
            $output = file_get_contents($url); 
        }else{ // use curl 
            $ch = curl_init(); 
            curl_setopt($ch, CURLOPT_URL, $url); 
            curl_setopt($ch, CURLOPT_AUTOREFERER, true); 
            curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1"); 
            curl_setopt($ch, CURLOPT_HEADER, 0); 
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
            curl_setopt($ch, CURLOPT_TIMEOUT, 10); 
            $output = curl_exec($ch); 
            curl_close($ch); 
        }
        // Save file
        file_put_contents($path, $output);
    }
}
Nach dem Login kopieren
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Empfehlungen
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage