Text to Speech with PHP & Google API

text to speech

In this tutorial we will see how to convert text to speech using Google API.It’s damn easy and you may use it to integrate it with your video or use it for your website.

Google API that we will be using is :
http://translate.google.com/translate_tts?tl=en&q=

Here the q variable is empty we need to pass our text separated by a ‘+’ sign.

Eg : http://translate.google.com/translate_tts?tl=en&q=My+name+is+Mukta+Chourishi
Try this on latest browsers.

I have written the complete code below.Try it out.

<?php
if($_POST){
//get the text
$text = substr($_POST['txttext'], 0, 100);

//we are passing as a query string so encode it, space will become +
$text = urlencode($text);

//give a file name and path to store the file
$file  = 'filename';
$file = $file . ".mp3";

//now get the content from the Google API using file_get_contents
$mp3 = file_get_contents("http://translate.google.com/translate_tts?tl=en&q=$text");

//save the mp3 file to the path
file_put_contents($file, $mp3);
}
?>
<html>
<body>
<h2>Text to Speech PHP Script</h2>

<form action="" method="post">
Enter your text:
<textarea name="txttext" rows="5" cols="30"></textarea>
<br>
<input type="submit" name="submit" value="Convert">
</form>

<?php  if($_POST){?>

<!-- play the audio file using a player. Here I'm used a HTML5 player. You can use any player insted-->
<audio controls="controls" autoplay="autoplay">
<source src="<?php echo $file; ?>" type="audio/mp3" />
</audio>

<?php }?>

</body>
</html>