我正在尝试使用 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 没有正确处理这个值。有什么想法吗?