【问题标题】:Authenticate and use Google Cloud Speech API验证和使用 Google Cloud Speech API
【发布时间】:2018-06-14 19:22:16
【问题描述】:

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

关注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 变量从未被使用过。应该去哪里?

我跑了还是得到了

未捕获的异常“Google\Cloud\Core\Exception\ServiceException” 带有消息'{“错误”:{“代码”:401,“消息”:“请求已 无效的身份验证凭据。预期的 OAuth 2 访问令牌, 登录 cookie 或其他有效的身份验证凭据。看 https://developers.google.com/identity/sign-in/web/devconsole-project.", “状态”:“未经身份验证”} }

我只想做一个简单的查询。任何帮助将不胜感激。

【问题讨论】:

标签: php google-cloud-platform google-cloud-speech


【解决方案1】:

或者,您可以在使用 api 之前调用 putenv

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

【讨论】:

    【解决方案2】:

    试试这个:

    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 是一个提供工厂的类,允许您配置 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'
    ]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多