<?php
/**
* DEPRECATED: Unofficial Text-to-Speech using the Google Translate endpoint.
* This method is no longer reliable or functional due to changes by Google
* (e.g., CAPTCHA, rate limiting). Use a modern official API instead.
*
* @param string $text The text to convert to speech.
* @param string $languageCode The language code (e.g., 'en' for English).
* @param string $outputDirectory The directory to save the MP3 file in.
* @return string|false The path to the saved MP3 file on success, or false on failure.
*/
function unofficialTextToSpeech(string $text, string $languageCode = 'en', string $outputDirectory = 'temp/'): string|false
{
// --- Input Validation and Preprocessing ---
// 1. Sanitize input to handle only the first 100 characters.
// The Google Translate API endpoint had a known character limit.
$sanitizedText = substr($text, 0, 100);
// 2. URL-encode the text for the query string (spaces become '+', etc.).
$encodedText = urlencode($sanitizedText);
// 3. Define the full path for the output file.
// We use the encoded text to create a unique filename.
$outputFilePath = $outputDirectory . $encodedText . '.mp3';
// 4. Check if the file already exists to prevent unnecessary API calls.
if (file_exists($outputFilePath)) {
return $outputFilePath;
}
// --- API Request Configuration ---
// The unofficial Google Translate Text-to-Speech endpoint structure.
$apiUrl = "http://translate.google.com/translate_tts?ie=UTF-8&tl={$languageCode}&q={$encodedText}";
// 5. Initialize cURL session.
$curlHandle = curl_init();
// 6. Set cURL options.
curl_setopt($curlHandle, CURLOPT_URL, $apiUrl);
// Return the transfer as a string instead of outputting it directly.
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
// (Optional but good practice) Set a user agent to mimic a browser.
// curl_setopt($curlHandle, CURLOPT_USERAGENT, 'Mozilla/5.0...');
// --- Execution and Cleanup ---
// 7. Execute the cURL request. $mp3Data will contain the MP3 file content.
$mp3Data = curl_exec($curlHandle);
// 8. Check for cURL errors.
if (curl_errno($curlHandle) || !$mp3Data) {
// Log the error (optional) and clean up.
// error_log('cURL error: ' . curl_error($curlHandle));
curl_close($curlHandle);
return false;
}
// 9. Close the cURL resource to free up system resources.
curl_close($curlHandle);
// 10. Save the binary MP3 data to the file system.
$success = file_put_contents($outputFilePath, $mp3Data);
return $success !== false ? $outputFilePath : false;
}
// ======================================
// USAGE EXAMPLE
// ======================================
// The input text would typically come from a POST request.
$inputText = $_POST['word'] ?? "Hello world, this is a test of the old Text-to-Speech utility.";
$outputDirectory = 'temp/'; // Ensure this directory exists and is writable!
if (!is_dir($outputDirectory)) {
mkdir($outputDirectory, 0777, true);
}
// Call the function
$mp3File = unofficialTextToSpeech($inputText, 'en', $outputDirectory);
if ($mp3File) {
echo "✅ Success! MP3 saved to: " . htmlspecialchars($mp3File) . "\n";
// You could then stream this file to the user's browser.
} else {
echo "❌ Failed to generate MP3. The Google API endpoint is likely blocked or unavailable.\n";
}
// -------------------------------------------------------------
// ✨ MODERN ALTERNATIVE: Use Google Cloud Text-to-Speech API
// -------------------------------------------------------------
/*
* For a reliable, production-ready solution, you should use the
* Google Cloud Text-toSpeech client library for PHP:
*
* 1. Install the library: composer require google/cloud-text-to-speech
* 2. Example:
* require 'vendor/autoload.php';
* use Google\Cloud\TextToSpeech\V1\TextToSpeechClient;
*
* $client = new TextToSpeechClient();
* $synthesisInput = ['text' => $inputText];
* $voice = ['languageCode' => 'en-US', 'name' => 'en-US-Standard-C'];
* $audioConfig = ['audioEncoding' => 'MP3'];
*
* $response = $client->synthesizeSpeech($synthesisInput, $voice, $audioConfig);
* file_put_contents('official_output.mp3', $response->getAudioContent());
*/Code language: PHP (php)
