Text to Speech in PHP (API)

// Code Starts here
<?php

// FileName: tts.php
/*
*  A PHP Class that converts Text into Speech using Google’s Text to Speech API
*
* Author:
* Voltainc
*Contributor :
*Awais
*
*/
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; }
    }
}
?>
// Code Ends here
#1 Make a folder namely “t2s” and keep both files mentioned below in this folder
#2  Save the above given source code to the file as “tts.php”
#3 Save the below given source code to the file as “index.php”
#4 Upload them to your web server and enjoy 🙂
// Demo Starts here
<?php

require “tts.php”;
$tts = new TextToSpeech();
$tts->setText(“Hello World!”);
$tts->saveToFile(“masnun.mp3”);
?>

// Demo Ends here

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s