Sankalp Mishra Sankalp Mishra - 9 months ago 212
PHP Question

Text-to-speech in PHP with Google Translate

I am trying to convert words to speech ..

Untill now I have tried this:

$text = "Hello this is a test for voice api of google";

// Name of the MP3 file generated using the MD5 hash
$file = md5($text);

// Save the MP3 file in this folder with the .mp3 extension
$file = "audio/" . $file .".mp3";
if($file) {
echo "created";
} else {
echo "not created";

// If the MP3 file exists, do not create a new request
if (!file_exists($file)) {
$mp3 = file_get_contents(
'' . $text);
echo "hello";
file_put_contents($file, $mp3);
} else {
echo "hii";

In my html file :

<audio controls="controls" autoplay="autoplay">
<source src="<?php echo $file; ?>" type="audio/mp3" />

I am getting created hello and an audio player in output. But no file is played and neither it is created in the folder?

  1. There is a problem with the url you try to access. It is broken ! You should have tried first. The new URL, that I found on the FF console is :

    For the single word Hello. And you see that you have to specify the language, and the length of your text in textlen, even though it did work for all the sentences I tried without changing this var.

  2. Another problem is that you have to urlencode() your text, or you will have a bug with accents and punctuation. So the line to download the MP3 becomes :

    // Language of the sentence
    $lang = "fr";
    $mp3 = file_get_contents(
    ''. urlencode($text) .'&tl='. $lang .'&total=1&idx=0&textlen=5&prev=input');

So the complete code looks like :


    $text = "Bonjour, comment allez vous ?";
    // Yes French is a beautiful language.
    $lang = "fr";

    // MP3 filename generated using MD5 hash
    // Added things to prevent bug if you want same sentence in two different languages
    $file = md5($lang."?".urlencode($text));

    // Save MP3 file in folder with .mp3 extension 
    $file = "audio/" . $file . ".mp3";

    // Check folder exists, if not create it, else verify CHMOD
    if (!is_dir("audio/"))
        if (substr(sprintf('%o', fileperms('audio/')), -4) != "0777")
            chmod("audio/", 0777);

    // If MP3 file exists do not create new request
    if (!file_exists($file))
        // Download content
        $mp3 = file_get_contents(
        ''. urlencode($text) .'&tl='. $lang .'&total=1&idx=0&textlen=5&prev=input');
        file_put_contents($file, $mp3);