我正在尝试制作一个 PHP 应用程序,使用它我可以将 .flac 文件发送到谷歌语音服务并获取文本作为回报。
按照官方指南
这是验证码:
require 'vendor/autoload.php';
use Google\Cloud\Core\ServiceBuilder;
// Authenticate using keyfile data
$cloud = new ServiceBuilder([
'keyFile' => json_decode(file_get_contents('b.json'), true)
]);
然后这是语音代码:
use Google\Cloud\Speech\SpeechClient;
$speech = new SpeechClient([
'languageCode' => 'en-US'
]);
// Recognize the speech in an audio file.
$results = $speech->recognize(
fopen(__DIR__ . '/audio_sample.flac', 'r')
);
foreach ($results as $result) {
echo $result->topAlternative()['transcript'] . "\n";
}
当然 $cloud 变量从未使用过。它应该去哪里?
我运行它仍然得到
未捕获的异常 'Google\Cloud\Core\Exception\ServiceException' 带有消息 '{ "error": { "code": 401, "message": "Request has invalid authentication credentials. 预期的 OAuth 2 访问令牌、登录 cookie 或其他有效身份验证凭据。请参阅https://developers.google.com/identity/sign-in/web/devconsole-project .", "status": "UNAUTHENTICATED" } }
我只想做一个简单的查询。任何帮助,将不胜感激。
试试这个:
use Google\Cloud\Speech\SpeechClient;
$speech = new SpeechClient([
'languageCode' => 'en-US',
'keyFile' => json_decode(file_get_contents('b.json'), true)
]);
// Recognize the speech in an audio file.
$results = $speech->recognize(
fopen(__DIR__ . '/audio_sample.flac', 'r')
);
foreach ($results as $result) {
echo $result->topAlternative()['transcript'] . "\n";
}
您对文档提出了一个很好的观点。过去几个月的变化导致了这种有点混乱的情况,值得再次澄清一些事情。我创建了一个问题来解决这个问题。
ServiceBuilder
是一个提供工厂的类,允许您配置 Google Cloud PHP 一次并创建继承该配置的不同客户端(例如 Speech 或 Datastore)。所有选项ServiceBuilder::__construct()
也可在客户端本身中使用,例如SpeechClient
,但有几个例外。
如果你想使用 ServiceBuilder,你可以这样做:
use Google\Cloud\Core\ServiceBuilder;
$cloud = new ServiceBuilder([
'keyFile' => json_decode(file_get_contents('b.json'), true)
]);
$speech = $cloud->speech([
'languageCode' => 'en-us'
]);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句