首页 > 解决方案 > 如何使用 Curl PHP 生成访问令牌并实现 google 文本到语音

问题描述

我正在尝试使用 Google Text to Speech API 实现 Text to Speech。我一直在关注这里的文档。 源链接

这是请求示例:

curl -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) -H "Content-Type: application/json; charset=utf-8" --data "{
  'input':{
    'text':'I\'ve added the event to your calendar.'
  },
  'voice':{
    'languageCode':'en-gb',
    'name':'en-GB-Standard-A',
    'ssmlGender':'FEMALE'
  },
  'audioConfig':{
    'audioEncoding':'MP3'
  }
}" "https://texttospeech.googleapis.com/v1/text:synthesize"

到目前为止,这是我的编码工作

<?php
$apikey ="my keys goes here";
$url = "https://texttospeech.googleapis.com/v1/text:synthesize";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
$params_post ="{
  'input':{
    'text':'I have added the event to your calendar.'
  },
  'voice':{
    'languageCode':'en-gb',
    'name':'en-GB-Standard-A',
    'ssmlGender':'FEMALE'
  },
  'audioConfig':{
    'audioEncoding':'MP3'
  }
}";

curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Bearer $apikey",'Content-Type: application/json; charset=utf-8'));  
curl_setopt($ch,CURLOPT_CUSTOMREQUEST,'POST');
curl_setopt($ch,CURLOPT_POSTFIELDS, $params_post);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
 echo $response = curl_exec($ch);

curl_close($ch);

print_r($response);


?>

这是我的问题:当我运行代码时,它会抛出请求访问令牌的错误。主要问题是上面的文档 URL 链接没有显示如何首先获取访问令牌。

这是它显示的错误

{ "error": { "code": 401, "message": "请求具有无效的身份验证凭据。预期的 OAuth 2 访问令牌、登录 cookie 或其他有效的身份验证凭据。请参阅https://developers.google.com/identity/登录/web/devconsole-project。” , "status": "UNAUTHENTICATED" } } { "error": { "code": 401, "message": "请求具有无效的身份验证凭据。预期的 OAuth 2 访问令牌、登录 cookie 或其他有效的身份验证凭据。请参阅https: //developers.google.com/identity/sign-in/web/devconsole-project。” ,“状态”:“未经身份验证”} }

标签: phpgoogle-text-to-speech

解决方案


推荐阅读