Texto a voz de Google Cloud en php

Sep 30 2020

Estoy tratando de usar el texto a voz de Google en mi sitio web php para alojarlo en un servidor Cpanel en vivo.

He habilitado la API de texto a voz, la CLAVE de API creada en la sección Credenciales, también descargué el archivo json de credenciales de la página Crear clave de cuenta de servicio.

Luego descargué los archivos de muestra de Github y también usé el compositor para construir la biblioteca

Ahora no entiendo dónde poner mis llaves. En cada lugar, exige EXPORTAR la clave en Shell, pero eso funcionaría para 1 sesión abierta del símbolo del sistema y deberá exportarse cada vez.

Como quiero ejecutar este código en un alojamiento basado en cpanel en vivo, creo que no será posible exportarlo.

¿Hay algún lugar dentro de los códigos donde pueda pasar la llave?

En este artículo de url en stackoverflow: la primera respuesta exporta la respuesta de CURL a Synthesize-text.txt pero requerimos salida mp3

Otra respuesta dice que deberíamos usar jq, pero dado que es un servidor de hsoting compartido, no estoy seguro de poder organizar jq .

¿Hay alguna salida a este problema?


Actualizar

Probé el siguiente código después de consultar la respuesta 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'];                
} 

Obtengo el audio descargado pero las pausas / pausas que mencioné en ssml no funcionaron. Intenté pasar datos a $ params como se muestra a continuación

$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'
    }
}";

Pero obtengo el siguiente error:

Array ([error] => Array ([código] => 400 [mensaje] => Carga útil JSON no válida recibida. Nombre desconocido "": El elemento raíz debe ser un mensaje. [Estado] => INVALID_ARGUMENT [detalles] => Array ( [0] => Array ([@type] => type.googleapis.com/google.rpc.BadRequest [fieldViolations] => Array ([0] => Array ([description] => Se recibió una carga útil JSON no válida. Nombre desconocido) "": El elemento raíz debe ser un mensaje.))))))

¿Cómo solucionar esto?

Respuestas

2 V.Tur Sep 30 2020 at 00:22

Debajo de mi ejemplo de trabajo de texto a voz, puede rehacerlo según sus necesidades:

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 el estándar SSML, es necesario cambiar los 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"
            ]
         ];

acerca de elegir audioEncoding - https://cloud.google.com/speech-to-text/docs/encoding