It’s really amazing how Google is providing cool APIs for every this and that! And here comes another one that impressed me
I am talking about the Text To Speech API by Google. It’s fantastic! I wrote a php wrapper class that would help you create mp3 files from texts
Of course, using Google as the medium!
Here’s the source code:
<?php // FileName: tts.php /* * A PHP Class that converts Text into Speech using Google's Text to Speech API * * Author: * Abu Ashraf Masnun * http://masnun.com * */ class TextToSpeech { public $mp3data; function __construct($text="") { $text = trim($text); if(!empty($text)) { $text = urlencode($text); $this->mp3data = file_get_contents("http://translate.google.com/translate_tts?q={$text}"); } } function setText($text) { $text = trim($text); if(!empty($text)) { $text = urlencode($text); $this->mp3data = file_get_contents("http://translate.google.com/translate_tts?q={$text}"); return $mp3data; } else { return false; } } function saveToFile($filename) { $filename = trim($filename); if(!empty($filename)) { return file_put_contents($filename,$this->mp3data); } else { return false; } } } ?>
And here’s demo :
<?php require "tts.php"; $tts = new TextToSpeech(); $tts->setText("Hello World!"); $tts->saveToFile("masnun.mp3"); ?>
You can alternatively pass the text to the constructor of the object like this:
<?php require "tts.php"; $tts = new TextToSpeech("Hello World!"); $tts->saveToFile("masnun.mp3"); ?>
That is simple, isn’t that? Hope you like it!
Pingback: Twitted by masnun
Pingback: Tweets that mention Google’s Text to Speech API : A PHP Wrapper Class | maSnun.com -- Topsy.com
Pingback: Google's Text to Speech API : A PHP Wrapper Class | maSnun.com | Coder Online
Nifty nice class… carry on digging google
Hello, if i would speech a text without limit of 100 char, how can i split the text and speech all one next another?
Let me know plz and sorry for my english.
Split the texts in small blocks and get the sound files for each.
Yes, my problem is how execute one after another the link that i have created.
how do I know when the execution of the first link is completed to start the second?
Thanks
When the saveToFile() method returns true, it means the portion is done.
i have modified this so it can support French, but when i tried to add some unique character in French like “Et vous êtes?” it won’t working correctly.. it sounds weird..
It’s a problem on Google’s side I think.
Thanks buddy
facing error in your code
Notice: Undefined variable: mp3data in E:\wamp\www\voice\tts.php on line 27
hey neha, are you on php4?
no ,i am using php 5.3.0
There’s something going wrong with the OO model.