提问者:小点点

使用php的googlecloud语音API


我试图使用PHP调用Google云语音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负载。

{"错误":{"代码": 400,"消息":"收到的JSON有效载荷无效。未知的名称\"内容\"at"Audio":找不到字段."、"状态":"INVALID_ARGUMENT"、"详细信息": [ { "@type":"type.googleapis.com/google.rpc.BadRequest"、"field违反": [ { "字段":"Audio"、"描述":"接收到无效的JSON有效载荷。未知的名称\"内容\"在"音频":找不到字段。"} ] } ] } } "

我认为这是因为$上传配置不正确。根据谷歌云语音应用编程接口,它应该是“一个基64编码的字符串”。https://cloud.google.com/speech/reference/rest/v1beta1/RecognitionAudio

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


共2个答案

匿名用户

您需要将正确格式化的输入构造为数组,然后对其进行json编码。例如,要发送文件,请将其编码为“内容”,并提交到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);

匿名用户

请将“内容”改为“内容”

小写字母c

它对我的工作。