3

我正在尝试使用 PHP 调用 Google Cloud Speech API 并遇到问题。

$stturl = "https://speech.googleapis.com/v1beta1/speech:syncrecognize?key=xxxxxxxxxxxx";
$upload = file_get_contents("1.wav");
$upload = base64_encode($upload);

$data = array(
    "config"    =>  array(
        "encoding"      =>  "LINEAR16",
        "sampleRate"    =>  16000,
        "languageCode"  =>  "en-US"
    ),
    "audio"     =>  array(
        "Content"       =>  $upload,
    )
);

$jsonData = json_encode($data);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $stturl);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);

$result = curl_exec($ch);

结果表明它是无效的 JSON PAYLOAD。

{ "error": { "code": 400, "message": "收到无效的 JSON 有效负载。未知名称 \"content\" at 'audio': 找不到字段。", "status": "INVALID_ARGUMENT", "details ": [ { "@type": "type.googleapis.com/google.rpc.BadRequest", "fieldViolations": [ { "field": "audio", "description": "收到无效的 JSON 有效负载。未知名称 \ “音频”处的“内容”:找不到字段。” } ] } ] } } "

我认为这是因为 $upload 配置不正确。根据 Google Cloud Speech API,它应该是“A base64-encoded string”。 https://cloud.google.com/speech/reference/rest/v1beta1/RecognitionAudio

这就是我使用base64_encode函数的原因,但似乎 JSON 没有正确处理这个值。有什么想法吗?

4

2 回答 2

2

您需要将格式正确的输入构造为数组,然后对其进行 json 编码。例如,要发送文件,请将其 base64 编码为“内容”并提交给 API,如下所示:

$data = array(
    "config" => array(
        "encoding" => "LINEAR16",
        "sample_rate" => $bitRate,
        "language_code" => "en-IN"
    ),
   "audio" => array(
        "content" => base64_encode($filedata)
    )
);

$data_string = json_encode($data);                                                              

$ch = curl_init($googlespeechURL);                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
   'Content-Type: application/json',                                                                                
   'Content-Length: ' . strlen($data_string))                                                                       
);                                                                                                                   

$result = curl_exec($ch);
$result_array = json_decode($result, true);
于 2016-09-14T06:49:05.657 回答
1

请制作“内容”而不是“内容”

小写字母“c”

它为我工作。

于 2016-09-14T10:12:42.370 回答