Google Cloud Text to speech em php

Sep 30 2020

Estou tentando usar o texto em fala do google em meu site php para ser hospedado em um servidor Cpanel ao vivo

Habilitei a API de texto para fala, Criada a chave da API na seção Credenciais, também baixei o arquivo json de credenciais da página Criar chave da conta de serviço.

Então eu baixei os arquivos de amostra do Github e também usei o composer para construir a biblioteca

Agora não entendo onde colocar minhas chaves. Em cada lugar, ele requer EXPORTAR a chave no Shell, mas isso funcionaria para 1 sessão de prompt de comando aberta e terá que ser exportado todas as vezes.

Como desejo executar este código em uma hospedagem baseada em cpanel ao vivo, acho que não será possível exportar.

Existe algum lugar dentro dos códigos onde posso passar a chave?

Por este url artigo em stackoverflow: as primeiras exportações resposta a resposta de CURL para sintetizar-text.txt mas exigimos saída mp3

Outra resposta afirma que devemos usar jq, mas como é um servidor hsoting compartilhado, não tenho certeza se podemos providenciar jq .

Existe alguma saída para este problema?


Atualizar

Tentei o seguinte código após consultar a resposta de @ V.Tur

$params = [ "audioConfig"=>[ "audioEncoding"=>"MP3", "pitch"=> "1", "speakingRate"=> "1", "effectsProfileId"=> [ "medium-bluetooth-speaker-class-device" ] ], "input"=>[ "ssml"=>'<speak>The <say-as interpret-as=\"characters\">SSML</say-as> standard <break time=\"1s\"/>is defined by the <sub alias=\"World Wide Web Consortium\">W3C</sub>.</speak>' ], "voice"=>[ "languageCode"=> "hi-IN", "name" =>"hi-IN-Wavenet-B", 'ssmlGender'=>'MALE' ] ]; $data_string = json_encode($params); $speech_api_key = "My_Key_Here";
$url = 'https://texttospeech.googleapis.com/v1/text:synthesize?fields=audioContent&key=' . $speech_api_key;
$handle = curl_init($url);

curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($handle, CURLOPT_POSTFIELDS, $data_string); curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)
    ]                                                                       
);
$response = curl_exec($handle);              
$responseDecoded = json_decode($response, true);  
curl_close($handle); if($responseDecoded['audioContent']){
    return $responseDecoded['audioContent'];                
} 

Baixei o áudio, mas as pausas / interrupções que mencionei no ssml não funcionaram. Tentei passar dados para $ params como abaixo

$params = "{
    'input':{
     'ssml':'<speak>The <say-as interpret-as=\"characters\">SSML</say-as>
          standard <break time=\"1s\"/>is defined by the
          <sub alias=\"World Wide Web Consortium\">W3C</sub>.</speak>'
    },
    'voice':{
      'languageCode':'en-us',
      'name':'en-US-Standard-B',
      'ssmlGender':'MALE'
    },
    'audioConfig':{
      'audioEncoding':'MP3'
    }
}";

Mas recebo o seguinte erro:

Array ([erro] => Array ([código] => 400 [mensagem] => Carga útil JSON inválida recebida. Nome desconhecido "": O elemento raiz deve ser uma mensagem. [Status] => INVALID_ARGUMENT [detalhes] => Array ( [0] => Array ([@type] => type.googleapis.com/google.rpc.BadRequest [fieldViolations] => Array ([0] => Array ([descrição] => Carga JSON inválida recebida. Nome desconhecido "": O elemento raiz deve ser uma mensagem.))))))

Como resolver isso?

Respostas

2 V.Tur Sep 30 2020 at 00:22

Abaixo do meu exemplo de trabalho de conversão de texto em voz, você pode refazer de acordo com as suas necessidades:

public static function getSound($text) { $text = trim($text); if($text == '') return false;
            
            $params = [ "audioConfig"=>[ "audioEncoding"=>"LINEAR16", "pitch"=> "1", "speakingRate"=> "1", "effectsProfileId"=> [ "medium-bluetooth-speaker-class-device" ] ], "input"=>[ "text"=>$text
                ],
                "voice"=>[
                    "languageCode"=> "en-US",
                    "name" =>"en-US-Wavenet-F"
                ]
            ];

            $data_string = json_encode($params);

            $url = 'https://texttospeech.googleapis.com/v1/text:synthesize?fields=audioContent&key=' . $speech_api_key;
            $handle = curl_init($url);
            
            curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($handle, CURLOPT_POSTFIELDS, $data_string); curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($handle, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)
                ]                                                                       
            );
            $response = curl_exec($handle);              
            $responseDecoded = json_decode($response, true);  
            curl_close($handle); if($responseDecoded['audioContent']){
                return $responseDecoded['audioContent']; } return false; } using: public static function saveSound($text)
   {
      $speech_data = SpeechAPI::getSound($text);//see method upper

      if($speech_data) { $file_name = strtolower(md5(uniqid($text)) . '.mp3'); $path = FileUpload::getFolder();//just return directory path
         if(file_put_contents($path.$file_name, base64_decode($speech_data))){ return $file_name;
             }
         }

        return null;
   }

Para SSML padrão, é necessário alterar os parâmetros de entrada:

$text = "<speak>The <say-as interpret-as=\"characters\">SSML</say-as> standard <break time=\"1s\"/>is defined by the <sub alias=\"World Wide Web Consortium\">W3C</sub>.</speak>"; $params = [
    "audioConfig"=>[
    "audioEncoding"=>"LINEAR16",
    "pitch"=> "1",
    "speakingRate"=> "1",
    "effectsProfileId"=> [
        "medium-bluetooth-speaker-class-device"
       ]
     ],
     "input"=>[
         //"text"=>$text "ssml" => $text
          ],
          "voice"=>[
              "languageCode"=> "en-US",
              "name" =>"en-US-Wavenet-F"
            ]
         ];

sobre escolher audioEncoding - https://cloud.google.com/speech-to-text/docs/encoding