下面的代码只显示了一个NULL
而不是mp3数据。我猜它缺少了请求的实际提交。不幸的是,所有的文档都是基于API的V1。
$synthesizeSpeechRequest = new SynthesizeSpeechRequest();
$synthesizeSpeechRequest->setInput($input_text);
$synthesizeSpeechRequest->setVoice($voice);
$synthesizeSpeechRequest->setAudioConfig($audioConfig);
//$client->execute($synthesizeSpeechRequest); // ? Something like this here ?
$synthesizeSpeechResponse = new SynthesizeSpeechResponse();
$audioContent = $synthesizeSpeechResponse->getAudioContent();
var_dump($audioContent); // does display NULL
完整代码:
<?php
require_once realpath(__DIR__ . '/vendor').'/autoload.php';
use Google\Service\Texttospeech;
use Google\Service\Texttospeech\AudioConfig;
use Google\Service\Texttospeech\SynthesisInput;
use Google\Service\Texttospeech\VoiceSelectionParams;
use Google\Service\Texttospeech\SynthesizeSpeechRequest;
use Google\Service\Texttospeech\SynthesizeSpeechResponse;
putenv('GOOGLE_APPLICATION_CREDENTIALS=neural-reactor-SOMENUMBERHERE.json');
$client = new Google\Client();
$client->useApplicationDefaultCredentials();
$client->addScope(Texttospeech::CLOUD_PLATFORM);
$service = new Texttospeech($client);
$text = 'There are over 200 Google API services. The chances are good that you will not want them all. In order to avoid shipping these dependencies with your code';
$input_text = new SynthesisInput();
$input_text->setText($text);
$voice = new VoiceSelectionParams();
$voice->setLanguageCode('en-gb');
$voice->setName('en-GB-Standard-A');
$voice->setSsmlGender('FEMALE');
$audioConfig = new AudioConfig();
$audioConfig->setAudioEncoding('MP3');
$synthesizeSpeechRequest = new SynthesizeSpeechRequest();
$synthesizeSpeechRequest->setInput($input_text);
$synthesizeSpeechRequest->setVoice($voice);
$synthesizeSpeechRequest->setAudioConfig($audioConfig);
echo '<pre>'; var_dump($synthesizeSpeechRequest); echo '</pre>';
//$client->execute($synthesizeSpeechRequest); // ? Something like this here ?
$synthesizeSpeechResponse = new SynthesizeSpeechResponse();
$audioContent = $synthesizeSpeechResponse->getAudioContent();
echo '<pre>'; var_dump($audioContent); echo '</pre>'; // does display NULL
// file_put_contents(__DIR__.'/output.mp3', $audioContent);
composer.json
{
"config": {
"platform": {
"php": "7.4"
}
},
"require": {
"google/apiclient": "^2.12.1"
},
"scripts": {
"pre-autoload-dump": "Google\\Task\\Composer::cleanup"
},
"extra": {
"google/apiclient-services": [
"Texttospeech"
]
}
}
1条答案
按热度按时间9jyewag01#
要提交请求,您应该添加以下代码:
它将返回一个SynthesizeSpeechResponse的示例。不要忘记解码音频内容,它是用Base64编码的。
因此,最终代码将如下所示:
如果要使用API密钥而不是应用程序默认凭据(ADC),请添加以下代码:
代替