我已经尽我所知来获取Google Speech to text API的返回值,但返回false却无济于事。我确保我的flac文件是一个单通道文件(ffmpeg -i test.flac -ac 1 test1.flac)-仍然没有。我在做什么错了?
<?php
// Your API Key goes here.
$apiKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$audioFile = realpath(__DIR__ . '/test.flac');
$url="https://speech.googleapis.com/v1/speech:recognize?key={$apiKey}";
$audioFileResource = fopen($audioFile, 'r');
$base64Audio = base64_encode(stream_get_contents($audioFileResource));
$settings=array(
'config'=> array(
'encoding'=>'FLAC',
'sampleRateHertz'=>44100,
'maxAlternatives' => 3,
'languageCode' => 'en-US'
),
'audio'=>array(
'content'=>$base64Audio
)
);
$json=json_encode($settings);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, $json );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result=curl_exec ($ch);
var_dump($result);
exit;
更新:我已经更新了代码,现在可以使用了。我错了两件事。首先是配置设置中的“ sampleRateHertz”而不是“ sampleRate”。其次,我必须在对等端禁用SSL验证。现在可以使用了。
返回以下内容:
D:\>php GoogleSpeechToText_example.php
string(320) "{
"results": [
{
"alternatives": [
{
"transcript": "the quick brown fox jumped over the lazy dog",
"confidence": 0.9850106
},
{
"transcript": "the quick brown fox jumps over the lazy dog",
"confidence": 0.90610087
}
]
}
]
}
答案 0 :(得分:1)
幸运的是,我发现了问题所在。我必须添加以下代码行:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);