PHP Script – Text to Speech using Google API


In this tutorial we are going to see how to a do a Text to Speech PHP Script using Google Speech API. Its pretty easy and very good If you want to have a ‘Text to Speech’ functionality in your website.

Lets see which Google API helps us for that:

The above URL is the one we are going to use. All we have to do is just pass the text to query string ?q=your+text

Run this URL in browser and you will know how it works (Please use Chrome/Firefox/Latest IE )

Here is the entire script to play around. And more over I have given a DEMO and DOWNLOAD link at the bottom of this post.

	//get the text 
   $text = substr($_POST['textbox'], 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 = "audio/" . $file . ".mp3";

   //now get the content from the Google API using file_get_contents
   $mp3 = file_get_contents("$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: <input name="textbox"></input>

<?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 }?>
<br />
<a href="">Find the tutorial here -</a>

Just read the comments in the script, you will be able to understand the script. This script actually get the content from the Google API and store it as a MP3 file in a folder (audio). Make sure audio folder is writable.

I have used HTML5 Player in this script which works only in Modern Browsers. You can use any other Player which can be able to Play MP3 file.


Here is the DEMO and DOWNLOAD for you:


8 thoughts on “PHP Script – Text to Speech using Google API

  1. Hi i am using same demo that you have define here . but i need to convert text more than one or more page . (1000-2000 word ) is it possible using above demo or can pay for google for that.

Leave a Reply

Theme: Overlay by Kaira