• Making Text To Speech In PHP With Google Translate

    Google provides text to speech feature on their translator product which is an awesome feature. If you are creating a web app of your own and need a human speaking voice for your app, you will get lost. Google have a URL for creating these audio files when given a text. I will tell you how to implement this text to speech feature on your PHP site without directly compromising the Google URL.
    For our task, we will only create a file named get_sound.php which sends a GET request to Google via cURL and returns the audio file. We will play this audio file using the audio element in HTML5 or you can use SWF players. The audio returned will be of the mpeg format.

    get_sound.php

    This file sends request to Google and returns the audio file. This file needs the text parameter to return the sound file. The audio file type is mpeg.
    <?
    if(isset($_GET['text'])){
     $txt=htmlspecialchars($_GET['text']);
     $txt=rawurlencode($txt);
     if($txt!="" || strlen($txt) < 100){
      header("Content-type: audio/mpeg");
      $url="http://translate.google.com/translate_tts?ie=UTF-8&q=$txt&tl=en";
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_TIMEOUT, 30);
      $audio = curl_exec($ch);
      echo $audio;
     }else{
      echo "No value or String exceeds 100 characters.";
     }
    }
    ?>
    As you can see, the URL of the Google text to speech is :
    http://translate.google.com/translate_tts?ie=UTF-8&q=$txt&tl=en
    where $txt is a string.
    This is applicable only to english. So, pronunciation will be different for other languages. In this case, replace the "en" in the url to the short forms of the language needed to make speech.
    You can see short forms in this file from line 52.
  • You might also like

    No comments:

    Post a Comment

    Good day precious one, We love you more than anything.

Powered by Blogger.