Google Text to Voice API in PHP

Posted By: Matpal - December 16, 2011
Since there is no specific API for converting text to speech, but it can be obtained through the Google URLs of Google translation service. There is a limit of this service. You can convert only 100 characters into speech. The code returns you an mp3 file.

[In this example we used <audio>  tag , which is used in HTML5. So please use Chrome or Mozilla Firefox to test that]


<?php

 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; }
    }
 
}

$data="Hello, I am testing the API.";

$tts = new TextToSpeech();
$tts->setText($data);
$tts->saveToFile("masnun.mp3");

?>

<audio controls="controls">
  <source src="masnun.mp3" type="audio/mpeg" />
  Your browser does not support the audio element.
</audio>

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.