<?php
// Programmed By Litedownload.ir
class PHP_Text2Speech {
/** Max text characters
* @varInteger
*/
var $maxStrLen = 100;
/** Text len
* @varInteger
*/
var $textLen = 0;
/** No of words
* @varInteger
*/
var $wordCount = 0;
var $lang = 'en';
/** Text to speak
* @varString
*/
var $text = NULL;
/** File name format
* @varString
*/
var $mp3File = "%s.mp3";
/** Directory to store audio file
* @varString
*/
var $audioDir = "audio/";
function speak($text, $lang = NULL) {
$this->text = $text;
// Can not handle more than 100 characters
$this->text = substr($this->text, 0, $this->maxStrLen);
// Text lenght
$this->textLen = strlen($this->text);
// Words count
$this->wordCount = str_word_count($this->text);
// Encode string
$this->text = urlencode($this->text);
// Create dir if not exists
if (!is_dir($this->audioDir)) {
mkdir($this->audioDir, 777) or die('Could not create audio dir: ' . $this->audioDir);
}
// Generate unique mp3 file name
$this->mp3File = sprintf($this->mp3File, $this->audioDir . md5($this->text));
// Download new file or use existing
if (!file_exists($this->mp3File)) {
$this->download("http://translate.google.com/translate_tts?ie=UTF-8&q={$this->text}&tl={$this->lang}&total={$this->wordCount}&idx=0&textlen={$this->textLen}", $this->mp3File);
}
// Returns mp3 file path
return $this->mp3File;
}
function download($url, $path){
// Is curl installed?
if (!function_exists('curl_init')){ // 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($this->mp3File, $output);
}
}
?>
<b> Example:</b>
<br /><br />
<?php
/**
* PHP EXAMPLE:::
* Author: Litedownload.ir
*/
$t2s = new PHP_Text2Speech;
?>
<audio controls="controls" autoplay="autoplay">
<source src="<?php echo $t2s->speak('Hello, this text for test writed.'); ?>" type="audio/mp3" />
</audio>