Search code examples
phphtmltexttext-to-speechspeech

Text2Speech Error, How can I play audio by entering URL into browser directly?


I got text2speech working, but I want to use GET method how can I do it? I mean I want to convert text2speech by URL like this: http://localhost/txt2speech/v.php?textbox=Hello Word

If I enter that URL in the browser I expect it to play the audio.

I can successfully convert text into speech, however the problem is it plays the same file.

EXAMPLE

If I send http://localhost/txt2speech/v.php?textbox=HelloWord and after that if I send http://localhost/txt2speech/v.php?textbox=SecondString

It plays HelloWorld, but I expect it to play SecondString However if I try in a different window it will play the SecondString file.

I have another problem. It will not work if I pass a string with a space in it.

EXAMPLE

http://localhost/txt2speech/v.php?textbox=Hello This is sentence with spaces

These are the files I am using:

index.php

<html>
<body> 
<h2>Text to Speech PHP Script</h2>

<form action="v.php" method="GET">
Enter your text: <input name="textbox"></input>
</form>

</body>
</html>

v.php

<?php
 if($_GET){
     $text = substr($_GET['textbox'], 0, 100);
   $file  = 'filename';
 $file = "audio/" . $file . ".mp3";
  $mp3 = file_get_contents("https://translate.google.com.vn/translate_tts?ie=UTF-8&q=$sname+&tl=en&client=tw-ob");
 file_put_contents($file, $mp3);
}
?>

<?php  if($_GET){?>
<audio controls="controls" autoplay="autoplay">
  <source src="<?php echo $file; ?>" type="audio/mp3" />
</audio>
<?php }?>

Solution

  • If your post code works, you can change post to get as seen below:

    index.php

    <html>
    <body> 
    <h2>Text to Speech PHP Script</h2>
    
    <form action="v.php" method="get">
    Enter your text: <input name="textbox"></input>
    </form>
    
    
    <?php  if($_GET){?>
    <audio controls="controls" autoplay="autoplay">
      <source src="<?php echo $file; ?>" type="audio/mp3" />
    </audio>
    <?php }?>
    </body>
    </html>
    

    v.php

    <?php
     if($_GET){
         $text = substr($_GET['textbox'], 0, 100);
       $file  = 'filename';
     $file = "audio/" . $file . ".mp3";
     # Convert input to proper encoded url
     $sname = urlencode ( $sname );
      $mp3 = file_get_contents("https://translate.google.com.vn/translate_tts?ie=UTF-8&q=$sname+&tl=en&client=tw-ob");
     file_put_contents($file, $mp3);
    }
    ?>
    

    To prevent spaces from breaking your url, use urlencode function in php.