Google 语音 API - php 不返回任何内容

2024-03-11

我的代码受到用于语音转文本的全双工谷歌语音 API 的 php 版本的启发:http://mikepultz.com/2013/07/google-speech-api-full-duplex-php-version/ http://mikepultz.com/2013/07/google-speech-api-full-duplex-php-version/

我有几个 flac 文件可以正常工作并提供数组输出,如 Mike 的帖子中所述。但对于少数 flac 文件,它不会返回任何内容作为输出。例如 :http://gavyadhar.com/video/upload/Pantry_Survey.flac http://gavyadhar.com/video/upload/Pantry_Survey.flac,不返回任何输出。

但同样的代码适用于这个 flac 文件:http://gavyadhar.com/video/upload/pantry_snack_video.flac http://gavyadhar.com/video/upload/pantry_snack_video.flac并返回数组输出,如下所示:

---------回应 1:你面对的是食品储藏室和主要的一堆,我通常是 Wesley Rd rasa 杂粮饼干,我喜欢它们,因为它们对你来说非常健康,并且 [...] ...等等 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); 		

// 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) {
	$i = $i + 1;
	#echo $response['transcript'];
	echo "<br><br> ---------response $i : ", $response['transcript'];
	
}

?>
GoogleSpeechToText.php

<?php
/**
 * Convert FLAC files to Text using the Google Speech API
 *
 * Credit due to Mike ([email protected] /cdn-cgi/l/email-protection) 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/';

	
	
    /**
     * 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();
        
		curl_setopt($this->downloadHandle, CURLOPT_URL, self::SPEECH_BASE_URL . 'down?pair=' . $this->requestPair );
		
		#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);
		
		//----added by asmi shah - 7 jan 2015
		curl_setopt($this->uploadHandle, CURLOPT_MAX_SEND_SPEED_LARGE, 30000);
		curl_setopt($this->uploadHandle, CURLOPT_LOW_SPEED_TIME, 9999);
		curl_setopt($this->downloadHandle, CURLOPT_LOW_SPEED_TIME, 9999);
		//----

    }

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

    /**
     * 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.'
            );
        }
		else { echo "<br>file exists"; }

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

        if (empty($rate) || !is_integer($rate)) {
            throw new Exception('$rate must be specified and be an integer');
        }
		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);
        
		curl_setopt($this->uploadHandle,CURLOPT_HTTPHEADER,array('Transfer-Encoding: chunked','Content-Type: audio/x-flac; rate=' . $rate));
        
		curl_setopt($this->uploadHandle,CURLOPT_POSTFIELDS,$upload_data);
		
		#echo "<br><br>------ data : ", $data;
		#echo "<br><br>------";
		#echo "<BR><BR> URL made up : ", self::SPEECH_BASE_URL . 'up?lang=' .$language . '&lm=dictation&client=chromium&pair=' .$this->requestPair . '&key=' . $this->apiKey;
		

        $curlMulti = curl_multi_init();

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

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

		#var_dump($this->downloadHandle);
		#echo "resource type ::".get_resource_type($this->downloadHandle);
        
		$output = array();
        $results = explode("\n", $res);
		
		
		#var_dump($results);
		#$i = 0;
        foreach ($results as $result) {
			#$i = $i + 1;
			#echo "<BR><BR><BR>--------------- string ||$i|| : ", $result;
			
            $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)) {
			echo "<BR><br>output is empty<BR>";
            return false;
        }
		echo "<BR><BR>";
        return  $output;
    }

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

?>

您提供的音频文件使用 2 个通道。由于语音当前仅支持单通道音频,因此您需要将其转换为单通道。 所有编码仅支持 1 通道(单声道)音频。Google语音API的音频编码细节 https://cloud.google.com/speech-to-text/docs/release-notes#v1beta1

将音频文件转换为 1 个通道后,我能够成功获得所提供的音频文件的响应。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Google 语音 API - php 不返回任何内容 的相关文章

  • Apache 2.4.9 在启用 ssl 模块并设置 ssl 证书后失败

    Apache 在尝试设置 ssl 证书后抛出以下错误 ssl emerg pid 30907 AH02572 Failed to configure at least one certificate and key for localhos
  • 使用 PHP 创建图表并导出为 PDF

    我正在寻找有关使用 PHP 创建图表的建议 我还希望能够将这些图表导出到 PDF 文档 我目前正在使用谷歌图表 但我不喜欢将我的所有信息发送到谷歌的想法 我更喜欢自己的托管解决方案 我见过很多 Flash 解决方案 但我不知道有什么方法可以
  • Magento 中的子域 htaccess 问题

    public html www domain com public html subdomain subdomain domain com public html htaccess public html subdomain htacces
  • __callStatic():从静态上下文实例化对象?

    我对 PHP 中的 静态 和 动态 函数和对象如何协同工作感到困惑 特别是在 callStatic 方面 callStatic 的工作原理 您可以有一个普通的班级 MyClass 在班级内您可以 放置一个名为 callStatic 的静态函
  • MYSQL 的 Google OAuth 2.0 用户 ID 数据类型

    我正在实施 Google OAuth 2 0 并注意到 Google OAuth 返回的唯一用户 ID 是21位数字长的 我想大整数 20 足以满足这种需求 但我现在看到 Google OAuth 返回的用户 ID 的长度感到困惑 关于我应
  • PHPExcel下载文件

    我想下载使用 PHPExcel 生成的 Excel 文件 我按照以下代码PHPExcel 强制下载问题 https stackoverflow com questions 26265108 phpexcel force download i
  • Magento - 将特定父类别的子类别列为链接

    我是 php 的初学者 并且一直试图将一个父类别的子类别作为链接调用 我得到了这个 它调出了 getName 但 getUrl 根本没有返回任何 URL 输出代码只是 li a href name of sub a li
  • php表格:每行显示3个单元格[重复]

    这个问题在这里已经有答案了 我看这里 数组放入每行 5 个单元格的表格中 https stackoverflow com questions 9099568 array into a table with 5 cells in each r
  • cURL 错误 77:设置证书验证位置时出错:CAfile

    我正在使用 Firebase php SDKlink https firebase php readthedocs io en latest index html并在 Windows 10 上的 XAMPP 服务器上使用 laravel 最
  • 覆盖供应商自动加载编辑器

    有没有办法让您创建的自动加载文件在调用供应商自动加载之前运行 我们似乎遇到了 SimpleSAML 的自动加载覆盖我们创建的自动加载文件之一的问题 我是 Composer 的新手 似乎无法在网上找到任何解决方案 我尝试将我们的自动加载文件包
  • session_regenerate_id 没有创建新的会话 id

    我有一个脚本 旨在完成当前会话并开始新的会话 我使用了一段代码 它在我的开发计算机上运行良好 但是 当我将其发布到生产服务器时 会话 ID 始终保持不变 以下是我重新启动会话的代码 session start SESSION array P
  • 使用 PHP 对 ASP.NET 成员身份中的用户进行身份验证

    我在尝试使用 PHP 针对现有 ASP NET 成员资格数据库对用户进行身份验证时遇到一些问题 我在网上搜索过 发现现有的答案似乎对我不起作用 即 public static function Hash password salt deco
  • 使用 PHP 的 Google Glass GDK 身份验证

    我正在尝试点击此链接来验证 GDK 中的用户 https developers google com glass develop gdk authentication https developers google com glass de
  • CakePHP Xml 实用程序库触发 DOMDocument 警告

    我正在使用 CakePHP 在视图中生成 XMLXML核心库 http book cakephp org 2 0 en core utility libraries xml html xml Xml build data array ret
  • 使用 DOJO 自动完成文本框

    我正在寻找一种使用 DOJO 进行文本框自动建议的简单方法 我将查询的数据库表 使用 PHP 脚本 以 JSON 形式返回 有超过 100 000 条记录 因此这确实不应该采用 FilteringSelect 或 ComboBox 的形式
  • 如何在 HTML / Javascript 页面中插入 PHP 下拉列表

    好吧 这是我的第二篇文章 请接受我是一个完全的新手 愿意学习 花了很多时间在各个网站上寻找答案 而且我几乎已经到达了我需要到达的地方 至少在这一点上 我有一个网页 其中有许多 javascript 函数 这些函数一起使用 google 地图
  • PHP文件上传

    如果我想在文件名转到服务器的永久位置 而不是临时位置 之前更改文件名 我该如何执行此操作 代码如下
  • mysqli bind_param 中的 NULL 是什么类型?

    我正在尝试将参数绑定到 INSERT INTO MySQLi 准备好的语句 如果该变量存在 否则插入 null 然后我知道 type variable i corresponding variable has type integer d
  • PHP cURL 在本地工作,在 AWS 服务器上出现错误 77

    最新更新 脚本作为管理员用户通过 SSH shell 作为 php script php 成功运行 当由 nginx 用户运行时 curl 命令无法执行 https 请求 所以我猜测这是nginx用户无法正确使用curl的问题 我已经检查了
  • “pdo_mysql”已禁用,我无法启用它。我在 iMac 7.1 OSX 10.6.8 上安装了 MAMP v. 3.0.4

    pdo mysql 已禁用 我无法启用它 我在 iMac 7 1 OSX 10 6 8 上安装了 MAMP v 3 0 4 在我的 phpinfo 页面上 我可以看到唯一启用的 PDO 是 sqlite 如果我查看 php 5 5 10 扩

随机推荐