验证并使用 Google 云语音 API

Authenticate and use Google Cloud Speech API

我正在尝试制作一个 PHP 应用程序,使用它我可以将 .flac 文件发送到 google 语音服务并在 return.

中获取文本

紧随 official guide

这是验证码:

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 变量。它应该去哪里?

我运行还是得到了

Uncaught exception 'Google\Cloud\Core\Exception\ServiceException' with message '{ "error": { "code": 401, "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See 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";
}

关于文档,您提出了一个很好的观点。过去几个月的变化导致了这种有点混乱的情况,值得再次审视以澄清事情。我创建了一个 issue 来解决这个问题。

ServiceBuilder 是一个 class,它提供工厂,允许您配置 Google Cloud PHP 一次,并创建继承它的不同客户端(例如语音或数据存储)配置。 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'
]);

或者,您可以在使用 api:

之前调用 putenv
/** Setting Up Authentication. */
$key_path = '/full/path/to/key-file.json';
putenv( 'GOOGLE_APPLICATION_CREDENTIALS=' . $key_path );