0
votes

I am trying to make a PHP application using which I can send a .flac file to the google speech service and get text in return.

Following the official guide

This is the authentication code:

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)
]);

Then this is the speech code:

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

Of course the $cloud variable is never used. Where should it go?

I ran it nonetheless got

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" } }

I just want to make a simple query. Any help would be appreciated.

2
have you created a key file?user8011997
@rtfm: Yes, b.json is a valid key file. Had followed the following link to create it: developers.google.com/identity/protocols/…Mohit

2 Answers

1
votes

Try this:

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

You bring up a good point regarding the documentation. Changes over the last few months have caused this somewhat confusing situation, and it deserves another look to clarify things. I've created an issue to resolve this.

ServiceBuilder is a class which provides factories allowing you to configure Google Cloud PHP once and create different clients (such as Speech or Datastore) which inherit that configuration. All the options on ServiceBuilder::__construct() are also available in the clients themselves, such as SpeechClient, with a couple of exceptions.

If you want to use the ServiceBuilder, you could do something like this:

use Google\Cloud\Core\ServiceBuilder;

$cloud = new ServiceBuilder([
    'keyFile' => json_decode(file_get_contents('b.json'), true)
]);

$speech = $cloud->speech([
    'languageCode' => 'en-us'
]);
0
votes

Alternatively, you can call putenv before before working with api:

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