我正在尝试将一个音频文件发送给IBM Watson,后者通常用于语音到文本的转换 . 我已经按照HTTP Rest接口的教程,在那里我发现了这个:
curl -X POST -u {username}:{password}
--header "Content-Type: audio/flac"
--data-binary @{path}audio-file.flac
“https://stream.watsonplatform.net/speech-to-text/api/v1/recognize”
此命令用于识别要发送给watson的音频文件 .
下面是我使用cURL的PHP代码 .
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,
"https://stream.watsonplatform.net/speech-to-
text/api/v1/recognize");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$post = array(
"file" => "@" .realpath("{path}audio-file.flac")
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, "{username}" . ":" .
"{password}");
$headers = array();
$headers[] = "Content-Type: audio/flac";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
else{
print_r($result);
}
curl_close ($ch);
?>
当我在浏览器中运行它时,我不断收到此错误:
{ "code" : 401 , "error" : "Not Authorized" , "description" : "2018-05-03T03:15:09-05:00, Error ERCDPLTFRM-INVLDCHR occurred when accessing https://stream.watsonplatform.net/speech-to-text/api/v1/recognize, Tran-Id: stream01-896101253 - " }
预期产量应为:
{
"results": [
{
"alternatives": [
{
"confidence": 0.891,
"transcript": "several tornadoes touch down as a line
of severe thunderstorms swept through Colorado on
Sunday "
}
],
"final": true
}
],
"result_index": 0
}
我不明白该怎么做以纠正错误 . 二进制数据字段是否正确?以下一个:
$post = array(
"file" => "@" .realpath("{path}audio-file.flac")
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
或者还有其他一些问题......
[注意:]
我通过提供有效的用户名和密码成功纠正了身份验证问题 . 但现在问题似乎有所不同 . 我的代码中的一些修改如下:
$post = array(
"file" =>
curl_file_create('<tmp_path>','file_type','file_name')
);
$headers[] = "Content-Type: audio/mp3";
这些修改是在我的音频文件是mp3扩展时进行的 . 但现在在浏览器上运行脚本时,我得到:
{“code_description”:“错误请求”,“代码”:400,“错误”:“流是0字节,但需要至少100个字节 . ” }
我已经检查过有关此错误的相关帖子:400问题,但问题仍然存在 . 这是链接Send file via cURL from form POST in PHP
即使按照上面的链接中的答案,我的问题也没有 .
但是当在终端中运行以下内容时:
curl -X POST -u : --header "Content-Type: audio/mp3" --data-binary @ / var / www / test / 96 - Cliches.mp3“https://stream.watsonplatform.net/speech-to-text/api/v1/recognize”
它正如预期的那样完美地获取输出 . 但是当在浏览器上运行php脚本时,我遇到了这个问题 . 什么可能出错?请建议做什么 . 谢谢 .
1 回答
我已经解决了这个问题!!这是下面负责问题的部分......
我必须在我的php文件中添加一些代码...
tmp_file_path来自..
还增加了一些其他线路......
然后在浏览器中执行代码,结果如预期完美,如下所示:
好吧都照顾好了:D!