Using Google Speech Recognition API with PHP

I want to make a simple script that uses google speech recognition, I have tried various ways so that I can access the API with Request Body, but has always failed.

Example URL: https://content-speech.googleapis.com/v1/speech:recognize?prettyPrint=true&alt=json&key=AIzaSyD-XXXXXXXXXXXXXXXXX-Al7hLQDbugrDcw

JSON example:

{
"audio": {
    "content": "ZkxhQwAAACIEg....more......FzSi6SngVApeE="
  },
  "config": {
    "encoding": "FLAC",
    "sampleRateHertz": 16000,
    "languageCode": "en-US"
  }
}

Upvotes: 0

Views: 10417

Answers (1)

Lohardt
Lohardt

Reputation: 1045

Documentation: https://cloud.google.com/speech-to-text/docs/basics

Code samples: https://cloud.google.com/speech-to-text/docs/samples

Consider using a library:

Google Cloud Client Library PHP (also has code samples): https://googlecloudplatform.github.io/google-cloud-php/#/docs/google-cloud/v0.61.0/speech/speechclient

Speech-to-Text Client Libraries https://cloud.google.com/speech-to-text/docs/reference/libraries#client-libraries-install-php

Speaker is a 3.party library you could use: https://github.com/duncan3dc/speaker

Quick example from google/cloud-speech:

Install:

composer require google/cloud-speech

Sample:

  # Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';

# Imports the Google Cloud client library
use Google\Cloud\Speech\SpeechClient;

# Your Google Cloud Platform project ID
$projectId = 'YOUR_PROJECT_ID';

# Instantiates a client
$speech = new SpeechClient([
    'projectId' => $projectId,
    'languageCode' => 'en-US',
]);

# The name of the audio file to transcribe
$fileName = __DIR__ . '/resources/audio.raw';

# The audio file's encoding and sample rate
$options = [
    'encoding' => 'LINEAR16',
    'sampleRateHertz' => 16000,
];

# Detects speech in the audio file
$results = $speech->recognize(fopen($fileName, 'r'), $options);

foreach ($results as $result) {
    echo 'Transcription: ' . $result->alternatives()[0]['transcript'] . PHP_EOL;
}

Upvotes: 5

Related Questions