Monday 28 March 2011

Google TTS API for my paragraphs using HTML5, jQuery and PHP

Most of the credit for this post goes to Abu Ashraf Masnun for this post http://www.masnun.me/2009/12/14/googles-text-to-speech-api-a-php-wrapper-class.html
You'll need to take a copy of his code for this to work. Then you need to append the following lines to the end of the PHP (after his object declaration).
$tts = new TextToSpeech();
$tts->setText($_POST['text']);
$tts->saveToFile("masnun.mp3");

Once you've done this, you can create a HTML file like mine below. To use the page, click on the speaker icons.

Note:This will not work in rubbish browsers. For this you will need to change my HTML5 <audio> tag for something awful like the <object> tag.

Another note:The Google TTS has a 100 character limit.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Text to speech</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<style>
body
{
font-family:Sans-serif;
line-height:1.5em;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
</script>
<script>
var audioText = '<audio controls="controls" autoplay="autoplay">';
audioText += '<source src="masnun.mp3" type="audio/mpeg" />';
audioText += 'Your browser does not support the audio element.';
audioText += '</audio>';
$(document).ready(function()
{
$('.tts').each(function()
{
$(this).after('<a href="#" class="speaker"><img src="http://farm6.static.flickr.com/5091/5568186294_a396c02f4f_t.jpg" /></a>');
});
$('.speaker').click(function()
{
$.post('tts.php',
{
text:$(this).prev('p').text()
}, function(data)
{
$(this).after(audioText);
});
return false;
});
});
</script>
</head>
<body>
<section id="mainContent">
<p class="tts">Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante.</p>
<p class="tts">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
<p class="tts">Johnny Diamond. Peter Sam</p>
</section>
</body>
</html>

No comments:

Post a Comment