Categories
PHP

php text to speech with google api

// Convert Words (text) to Speech (MP3)
// ------------------------------------
$word=$_POST['word'];
// Google Translate API cannot handle strings > 100 characters
$word = substr($word, 0, 100);

// Replace the non-alphanumeric characters
// The spaces in the sentence are replaced with the Plus symbol
$word = urlencode($word);

// If the MP3 file exists, do not create a new request
// create curl resource
$ch = curl_init();

// set url
curl_setopt($ch, CURLOPT_URL, 'http://translate.google.com/translate_tts?ie=UTF-8&tl=en&q='.$word);

//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// $output contains the mp3 file
$mp3 = curl_exec($ch);

// close curl resource to free up system resources
curl_close($ch);

file_put_contents('temp/'.$word.'.mp3', $mp3);
PS: this code no longer works as google added captcha code

By milind

Milind is a Senior WordPress Engineer at rtCamp.
WordPress Ecosystem Contributor and AMP Support Engineer.