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("http://translate.google.com/translate_tts?tl=en&q=$text");
//save the mp3 file to the path
<h2>Text to Speech PHP Script</h2>
<form action="" method="post">
Enter your text: <input name="textbox"></input>
<!-- 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" />
<a href="http://blog.theonlytutorials.com/php-script-text-speech-google-api/">Find the tutorial here - Blog.Theonlytutorials.com</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: