2015-01-16 3 views
4

не возвращает Мой код вдохновлен этой PHP версией полнодуплексного Google Speech API для преобразования речи в текст: http://mikepultz.com/2013/07/google-speech-api-full-duplex-php-version/Google Speech API - PHP ничего

У меня есть несколько FLAC файлов, которые делают работу и дать массив как объяснили на посту Майка. Но для нескольких файлов flac он просто ничего не возвращает в качестве вывода. Например: http://gavyadhar.com/video/upload/Pantry_Survey.flac, выходные данные не возвращаются.

Но тот же код работает для этого FLAC файла: http://gavyadhar.com/video/upload/pantry_snack_video.flac и возвращает выходной массив следующим образом:

--------- ответ 1: ваше лицо кладовая и одна из основных стеков я обычно Wesley Rd rasa multigrain crackers, и мне они нравятся, потому что они довольно здоровы для вас и [...] ... и т. д. 5 ответов.

Может ли кто-нибудь сказать мне, почему некоторые файлы flac не работают? Или есть ли способ поймать исключения, созданные Google API и отображать их для устранения неполадок?

Спасибо. Прикрепление мой код здесь двух PHP файлов:

PHP file which passes the API key and the FLAC file with its sample rate. 
 

 
<?php 
 
include 'GoogleSpeechToText.php'; 
 

 

 
ini_set('display_errors',1); 
 
ini_set('display_startup_errors',1); 
 
error_reporting(-1); \t \t 
 

 
// Your API Key goes here. 
 
$apiKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'; // my API server key 
 
$speech = new GoogleSpeechToText($apiKey); 
 

 
#var_dump($speech); 
 

 
$file = realpath('upload/Pantry_Survey.flac'); // Full path to the file. 
 

 
echo "<BR><BR>file : ", $file ; 
 

 
#print_r("<br>-------------------"); 
 
#print_r($file1); 
 
#print_r("<br>-------------------"); 
 

 
$bitRate = 44100; // The bit rate of the file. 
 
$result = $speech->process($file, $bitRate, 'en-US'); 
 

 
print_r($result); 
 

 
echo "<BR><BR>-------------"; 
 

 
$responses = $result[0]['alternative']; 
 

 
$i = 0; 
 
foreach ($responses as $response) { 
 
\t $i = $i + 1; 
 
\t #echo $response['transcript']; 
 
\t echo "<br><br> ---------response $i : ", $response['transcript']; 
 
\t 
 
} 
 

 
?>

GoogleSpeechToText.php 
 

 
<?php 
 
/** 
 
* Convert FLAC files to Text using the Google Speech API 
 
* 
 
* Credit due to Mike ([email protected]) for his first version of this. 
 
* 
 
* @version 0.1 
 
* @author Roger Thomas 
 
* @see 
 
* 
 
*/ 
 
class GoogleSpeechToText 
 
{ 
 
    /** 
 
    * URL of the Speech API 
 
    * @var string 
 
    */ 
 
    const SPEECH_BASE_URL = 'https://www.google.com/speech-api/full-duplex/v1/'; 
 

 
\t 
 
\t 
 
    /** 
 
    * A 'unique' string to use for the requests 
 
    * 
 
    * @var string 
 
    */ 
 
    private $requestPair; 
 

 
    /** 
 
    * The Google Auth API Key 
 
    * 
 
    * @var string 
 
    */ 
 
    private $apiKey; 
 

 
    /** 
 
    * CURL Upload Handle 
 
    * 
 
    * @var resource 
 
    */ 
 
    private $uploadHandle; 
 

 
    /** 
 
    * CURL Download Handle 
 
    * 
 
    * @var resource 
 
    */ 
 
    private $downloadHandle; 
 

 
    /** 
 
    * Construct giving the Google Auth API Key. 
 
    * 
 
    * @param string $apiKey 
 
    * @throws Exception 
 
    */ 
 
    public function __construct($apiKey) 
 
    { 
 
     if (empty($apiKey)) { 
 
      throw new Exception('$apiKey should not be empty.'); 
 
     } 
 
     $this->apiKey = $apiKey; 
 
     $this->requestPair = $this->getPair(); 
 
     $this->setupCurl(); 
 
    } 
 

 
    /** 
 
    * Setup CURL requests, both up and down. 
 
    */ 
 
    private function setupCurl() 
 
    { 
 
     $this->uploadHandle = curl_init(); 
 
     $this->downloadHandle = curl_init(); 
 
     
 
\t \t curl_setopt($this->downloadHandle, CURLOPT_URL, self::SPEECH_BASE_URL . 'down?pair=' . $this->requestPair); 
 
\t \t 
 
\t \t #echo "<br>downloadHandle :: ", self::SPEECH_BASE_URL . 'down?pair=' . $this->requestPair; 
 

 
     curl_setopt($this->downloadHandle, CURLOPT_RETURNTRANSFER, true); 
 

 
     curl_setopt($this->uploadHandle,CURLOPT_RETURNTRANSFER,true); 
 

 
     curl_setopt($this->uploadHandle,CURLOPT_POST,true); 
 
\t \t 
 
\t \t //----added by asmi shah - 7 jan 2015 
 
\t \t curl_setopt($this->uploadHandle, CURLOPT_MAX_SEND_SPEED_LARGE, 30000); 
 
\t \t curl_setopt($this->uploadHandle, CURLOPT_LOW_SPEED_TIME, 9999); 
 
\t \t curl_setopt($this->downloadHandle, CURLOPT_LOW_SPEED_TIME, 9999); 
 
\t \t //---- 
 

 
    } 
 

 
    /** 
 
    * Generate a Pair for the request. This identifies the requests later. 
 
    * 
 
    * @return string 
 
    */ 
 
    private function getPair() 
 
    { 
 
     $c = ''; 
 
     $s = ''; 
 
     for ($i=0; $i<16; $i++) { 
 
      $s .= $c[rand(0, strlen($c) - 1)]; 
 
     } 
 
\t \t echo "pair : ",$s; 
 
     return $s; 
 
\t \t 
 
    } 
 

 
    /** 
 
    * Make the request, returning either an array, or boolean false on 
 
    * failure. 
 
    * 
 
    * @param string $file the file name to process 
 
    * @param integer $rate the bitrate of the flac content (example: 44100) 
 
    * @param string $language the ISO language code 
 
    *  (en-US has been confirmed as working) 
 
    * @throws Exception 
 
    * @return array|boolean false for failure. 
 
    */ 
 
    public function process($file, $rate, $language = 'en-US') 
 
    { 
 
     if (!$file || !file_exists($file) || !is_readable($file)) { 
 
      throw new Exception(
 
       '$file must be specified and be a valid location.' 
 
      ); 
 
     } 
 
\t \t else { echo "<br>file exists"; } 
 

 
     $data = file_get_contents($file); 
 
\t \t 
 
\t \t #var_dump($rate); 
 
     if (!$data) { 
 
      throw new Exception('Unable to read ' . $file); 
 
     } 
 
\t \t else { echo "<br>file is readable"; } 
 
\t \t 
 
\t \t 
 
\t \t $upload_data = array(
 
\t \t \t \t \t "Content_Type" => "audio/x-flac; rate=". $rate, 
 
\t \t \t \t \t "Content"  => $data, 
 
\t \t); 
 
\t \t 
 

 
     if (empty($rate) || !is_integer($rate)) { 
 
      throw new Exception('$rate must be specified and be an integer'); 
 
     } 
 
\t \t else { echo "<br>sample rate is received :" . $rate ; } 
 

 
     curl_setopt($this->uploadHandle,CURLOPT_URL,self::SPEECH_BASE_URL . 'up?lang=' .$language . '&lm=dictation&timeout=20&client=chromium&pair=' .$this->requestPair . '&key=' . $this->apiKey); 
 
     
 
\t \t curl_setopt($this->uploadHandle,CURLOPT_HTTPHEADER,array('Transfer-Encoding: chunked','Content-Type: audio/x-flac; rate=' . $rate)); 
 
     
 
\t \t curl_setopt($this->uploadHandle,CURLOPT_POSTFIELDS,$upload_data); 
 
\t \t 
 
\t \t #echo "<br><br>------ data : ", $data; 
 
\t \t #echo "<br><br>------"; 
 
\t \t #echo "<BR><BR> URL made up : ", self::SPEECH_BASE_URL . 'up?lang=' .$language . '&lm=dictation&client=chromium&pair=' .$this->requestPair . '&key=' . $this->apiKey; 
 
\t \t 
 

 
     $curlMulti = curl_multi_init(); 
 

 
     curl_multi_add_handle($curlMulti, $this->downloadHandle); 
 
     curl_multi_add_handle($curlMulti, $this->uploadHandle); 
 
\t \t 
 
     $active = null; 
 
     do { 
 
      curl_multi_exec($curlMulti, $active); 
 
     } while ($active > 0); 
 

 
     $res = curl_multi_getcontent($this->downloadHandle); 
 

 
\t \t #var_dump($this->downloadHandle); 
 
\t \t #echo "resource type ::".get_resource_type($this->downloadHandle); 
 
     
 
\t \t $output = array(); 
 
     $results = explode("\n", $res); 
 
\t \t 
 
\t \t 
 
\t \t #var_dump($results); 
 
\t \t #$i = 0; 
 
     foreach ($results as $result) { 
 
\t \t \t #$i = $i + 1; 
 
\t \t \t #echo "<BR><BR><BR>--------------- string ||$i|| : ", $result; 
 
\t \t \t 
 
      $object = json_decode($result, true); 
 
      if (
 
       (isset($object['result']) == true) && 
 
       (count($object['result']) > 0) 
 
      ) { 
 
       foreach ($object['result'] as $obj) { 
 
        $output[] = $obj; 
 
       } 
 
      } 
 
     } 
 

 
     curl_multi_remove_handle($curlMulti, $this->downloadHandle); 
 
     curl_multi_remove_handle($curlMulti, $this->uploadHandle); 
 
     curl_multi_close($curlMulti); 
 

 
     if (empty($output)) { 
 
\t \t \t echo "<BR><br>output is empty<BR>"; 
 
      return false; 
 
     } 
 
\t \t echo "<BR><BR>"; 
 
     return $output; 
 
    } 
 

 
    /** 
 
    * Close any outstanding connections in the destruct 
 
    */ 
 
    public function __destruct() 
 
    { 
 
     curl_close($this->uploadHandle); 
 
     curl_close($this->downloadHandle); 
 
    } 
 
} 
 

 
?>

+0

и теперь 'https: // www.google.com/речи апи/полнодуплексный/v1 /' возвращает 404:/ – user3526

+0

I Я также сталкиваюсь с той же проблемой. – sandeepsure

ответ

2

аудио Предоставленный файл использует 2 канала. Поскольку речь в настоящее время поддерживает только одноканальный звук, вам нужно будет преобразовать его в один канал. Все кодировки поддерживают только 1 канал (моно) аудио. Audio encoding detail of Google speech API

После преобразования аудиофайла до 1 канала я смог успешно получить ответ с предоставленным аудиофайлом.

+0

Подробнее о преобразовании файла в нужный формат: http://stackoverflow.com/a/42214318/1161370 – Mahesh