Text To Speech Using Google API In PHP

In Text To Speech tutorial, I have explained how to convert text to speech (mp3) using unofficial Google Speech API.
You need to send HTTP GET request to Google Speech URL to convert text as MP3.

Google Speech API URL :

http://translate.google.com/translate_tts

Parameters supported:
q -> query string. You need to do URL encoding, if the string contains special characters.
tl -> Translation Language ar(Arabic),en-us(English).
You can get the list of language from here :Google Documentation
ie -> encoding Format. Default: UTF-8

Note: To encode UTF-8 string, you can use this:http://www.url-encode-decode.com

Sample URL:(English)

http://translate.google.com/translate_tts?ie=UTF-8&q=This%20is%20Ravishanker&tl=en-us

Spanish:

http://translate.google.com/translate_tts?ie=UTF-8&q=Hola+%C2%BFC%C3%B3mo+est%C3%A1s.+Este+es+Ravishanker&tl=es

Hindi:

http://translate.google.com/translate_tts?ie=UTF-8&q=%E0%A4%A8%E0%A4%AE%E0%A4%B8%E0%A5%8D%E0%A4%95%E0%A4%BE%E0%A4%B0.+%E0%A4%86%E0%A4%AA+%E0%A4%95%E0%A5%88%E0%A4%B8%E0%A5%87+%E0%A4%B9%E0%A5%88%E0%A4%82&&tl=hi

Speech API supports only 100 characters, If the text is more than 100 characters it gives an error.
Now I am going to show how to convert long text to speech using PHP.

Text To Speech usin Google API In PHP

Follow the below steps:
Step 1). Split the long text into sub strings, So that each string is lesser than 100 characters.

Note: This function is not so optimized.

function splitString($str)
{
	$ret=array();
	$arr=explode(" ",$str);
	$constr='';
	for($i=0;$i<count($arr);$i++)
	{
		if(strlen($constr.$arr[$i]." ") < 98)
		{
			$constr =$constr.$arr[$i]." ";
		}
		else
		{
			$ret[] =$constr;
			$constr='';
			$i--; //add the word back.
		}

	}
	$ret[]=$constr;
	return $ret;
}

Step 2). For each sub string prepare a URL and download using CURL

function downloadMP3($url,$file)
{
    $ch = curl_init();  
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    $output=curl_exec($ch);
    curl_close($ch);
    if($output === false)	
    return false;

	$fp= fopen($file,"wb");
	fwrite($fp,$output);
	fclose($fp);

	return true;
}

Step 3). Join all the MP3 files using PHP getid3 library.

function CombineMultipleMP3sTo($FilenameOut, $FilenamesIn) {

	foreach ($FilenamesIn as $nextinputfilename) {
		if (!is_readable($nextinputfilename)) {
			echo 'Cannot read "'.$nextinputfilename.'"<BR>';
			return false;
		}
	}

	ob_start();
	if ($fp_output = fopen($FilenameOut, 'wb')) {

		ob_end_clean();
		// Initialize getID3 engine
		$getID3 = new getID3;
		foreach ($FilenamesIn as $nextinputfilename) {

			$CurrentFileInfo = $getID3->analyze($nextinputfilename);
			if ($CurrentFileInfo['fileformat'] == 'mp3') {

				ob_start();
				if ($fp_source = fopen($nextinputfilename, 'rb')) {

					ob_end_clean();
					$CurrentOutputPosition = ftell($fp_output);

					// copy audio data from first file
					fseek($fp_source, $CurrentFileInfo['avdataoffset'], SEEK_SET);
					while (!feof($fp_source) && (ftell($fp_source) < $CurrentFileInfo['avdataend'])) {
						fwrite($fp_output, fread($fp_source, 32768));
					}
					fclose($fp_source);

					// trim post-audio data (if any) copied from first file that we don't need or want
					$EndOfFileOffset = $CurrentOutputPosition + ($CurrentFileInfo['avdataend'] - $CurrentFileInfo['avdataoffset']);
					fseek($fp_output, $EndOfFileOffset, SEEK_SET);
					ftruncate($fp_output, $EndOfFileOffset);

				} else {

					$errormessage = ob_get_contents();
					ob_end_clean();
					echo 'failed to open '.$nextinputfilename.' for reading';
					fclose($fp_output);
					return false;

				}

			} else {

				echo $nextinputfilename.' is not MP3 format';
				fclose($fp_output);
				return false;

			}

		}

	} else {

		$errormessage = ob_get_contents();
		ob_end_clean();
		echo 'failed to open '.$FilenameOut.' for writing';
		return false;

	}

	fclose($fp_output);
	return true;
}

Step 4). Below is the API to convert long text to speech.

function converTextToMP3($str,$outfile)
{
	$base_url='http://translate.google.com/translate_tts?tl=en-us&ie=UTF-8&q=';
	$words = splitString($str);
	$files=array();
	foreach($words as $word)
	{
		$url= $base_url.urlencode($word);
		$filename =md5($word).".mp3";
		echo ".";
		if(!downloadMP3($url,$filename))
		{
			echo "Failed to Download URL.".$url."n";
		}
		else
		{
			$files[] = $filename;
		}

	}

	if(count($files) == count($words)) //if all the strings are converted
		CombineMultipleMP3sTo($outfile,$files);
	else
		echo "ERROR. Unable to convert n";

	foreach($files as $file)
	{
		unlink($file);
	}
}

Step 5). How to Use it

$str ='Hello World';
converTextToMP3($str,"outfile.mp3");