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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<?php // FileName: tts.php /* * A PHP Class that converts Text into Speech using Google's Text to Speech API * * Author: * Abu Ashraf Masnun * https://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 :
1 2 3 4 5 6 |
<?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:
1 2 3 4 5 |
<?php require "tts.php"; $tts = new TextToSpeech("Hello World!"); $tts->saveToFile("masnun.mp3"); ?> |
That is simple, isn’t that? Hope you like it!