Text to speech in PHP with Google Translate

Thursday , 15, April 2021 Leave a comment

Google give us text to speech feature on their translator product which is an awesome feature. If you think to add text to speech feature in your website and need a human speaking voice for your website . 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.

The following snippet of PHP code is responsible for the conversion while the MP3 files are cached to reduce requests to Google Translation servers.

  $text = $_POST['textbox'];
  $text = htmlspecialchars($text);
  $text = rawurlencode($text);

  $html = file_get_contents('https://translate.google.com/translate_tts?ie=UTF-8&client=gtx&q='.$text.'&tl=en-IN'); 
  $player = "<audio controls='controls' autoplay><source src='data:audio/mp3;base64,".base64_encode($html)."'></audio>";
  echo $player;


<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>text to speech</title>

    <form method="POST" action="">
    <input type ="text" name="textbox" >
    <input type="submit" name="submit" value="Convert to speech">

This is php code 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.

Dynamic dependent select box using jQuery, Ajax, and PHP show php Errors with Example

Leave a Reply

Your email address will not be published. Required fields are marked *