Skip to content

Instantly share code, notes, and snippets.

@monteiro
Created May 2, 2024 08:06
Show Gist options
  • Save monteiro/87fa272e0762bfce007b004efd96658d to your computer and use it in GitHub Desktop.
Save monteiro/87fa272e0762bfce007b004efd96658d to your computer and use it in GitHub Desktop.
Using google TTS API with PHP
<?php
require_once 'vendor/autoload.php';
// Function to convert text to speech using Google Cloud Text-to-Speech API
function textToSpeech($text, $serviceAccountPath) {
// Create and configure a new client object
$client = new Google_Client();
$client->setAuthConfig($serviceAccountPath);
$client->addScope('https://www.googleapis.com/auth/cloud-platform');
$httpClient = $client->authorize();
// Google Text-to-Speech API URL
$url = 'https://texttospeech.googleapis.com/v1/text:synthesize';
// The text and voice configuration
$data = [
"input" => ["text" => $text],
"voice" => ["languageCode" => "pt-PT", "ssmlGender" => "FEMALE"],
"audioConfig" => ["audioEncoding" => "MP3"]
];
// Make the request
$response = $httpClient->post($url, [
'json' => $data
]);
// Decode the JSON response
$responseDecoded = json_decode($response->getBody(), true);
// Check if the API call was successful
if (isset($responseDecoded['audioContent'])) {
// Decode the audio content and save it as an MP3 file
file_put_contents("output.mp3", base64_decode($responseDecoded['audioContent']));
echo "Audio content written to 'output.mp3'\n";
} else {
// Output error message
echo "Failed to convert text to speech.\n";
if (isset($responseDecoded['error']['message'])) {
echo "Error message: " . $responseDecoded['error']['message'] . "\n";
}
}
}
// Path to your service account JSON key
$serviceAccountPath = __DIR__ .'/google-tts-credentials.json';
// The text you want to convert to speech
$text = "Boa tarde Hugo, como te posso ajudar?";
// Call the function
textToSpeech($text, $serviceAccountPath);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment