Created
July 14, 2014 16:09
-
-
Save TimBroddin/d7f6990d7391d4e099e3 to your computer and use it in GitHub Desktop.
TTS using Google Translate API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class TTS { | |
private $language; | |
public function __construct($lang='nl') { | |
$this->language = $lang; | |
} | |
public function toMP3($text, $file) { | |
$parts = $this->splitText($text); | |
$data = ''; | |
foreach($parts as $part) { | |
if($part) { | |
$url = "http://translate.google.com/translate_tts?tl=%s&q=%s"; | |
$data .= file_get_contents(sprintf($url, $this->language, urlencode($part))); | |
} | |
} | |
file_put_contents($file, $data); | |
} | |
private function splitText($text) { | |
$parts = array(); | |
$p = explode("\n", $text); | |
foreach($p as $part) { | |
if(strlen($part) >= 100) { | |
$words = explode(' ', $part); | |
$word_count = 0; | |
$sentence = ''; | |
foreach($words as $i => $word) { | |
$sentence = $word . ' '; | |
if(isset($words[$i+1]) && strlen($word_count . $words[$i+1]) >= 100) { | |
$parts[] = $sentence; | |
$sentence = ''; | |
} | |
} | |
if(strlen($sentence)) { | |
$parts[] = $sentence; | |
} | |
} else { | |
$parts[] = $part; | |
} | |
} | |
return $parts; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment