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 :

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.

//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);
<h2>Text to Speech PHP Script</h2>

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

<?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" />

<?php }?>



2 thoughts on “Text to Speech with PHP & Google API

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s