我正在尝试使用Watson Text to Speech API通过麦克风获取录制音频的文字记录。在前端使用Vue,在后端使用PHP,并使用Guzzle发出请求。
当用户点击按钮时开始录制音频,也就是当我将数据发送到后端并向API发出请求时结束。问题是我得到了一个空洞的回应。没有任何错误。
这就是我所取得的进展:在前台,我使用MediaRecorder录制音频,当音频录制停止时,我从用相应的mimetype录制的数据中制作一个blob,并将其转换为base64字符串,然后将其发送到后台,如下所示:
navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
this.mediaRecorder = new MediaRecorder(stream);
this.mediaRecorder.start();
let audioChunks = [];
this.mediaRecorder.addEventListener("dataavailable", event => {
audioChunks.push(event.data);
});
this.mediaRecorder.addEventListener("stop", () => {
const mimeType = this.mediaRecorder.mimeType;
const audioBlob = new Blob(audioChunks, {type: mimeType});
const audioTrack = stream.getAudioTracks()[0];
stream.removeTrack(audioTrack);
let reader = new FileReader();
reader.readAsDataURL(audioBlob);
reader.onload = () => {
const recording = reader.result;
this.makeRequest(url, 'POST', {'audio': recording, 'mimeType': mimeType})
.then(response => {
// filter response
})
.catch(error => {
//
});
this.mediaRecorder = null;
};
});
})
在后台,我解码base64字符串并将其保存到文件中,然后将其发送到Speech-to-Textneneneba API,如下所示:
$data = json_decode($request->getContent());
$formatted_str = str_replace("data:{$data->mimeType};base64,", "", $data->audio);
$recording = base64_decode($formatted_str);
$filename = Uuid::uuid4()->toString() . ".webm";
file_put_contents($filename, $recording);
$client = new GuzzleClient([
'base_uri' => $baseUrl
]);
try {
$apiRequest = new GuzzleHttpPsr7Request('POST', $clientUrl);
$apiRequestParams = [
'auth' => ['apikey', $apiKey],
'headers' => [
'Content-Type' => $data->mimeType
],
'model' => 'en-GB_BroadbandModel',
'body' => file_get_contents($filename)
];
$response = $client->send($apiRequest, $apiRequestParams);
$data = $response;
return new JsonModel([
'data' => $data
]);
我得到的只是一个空虚的身体的回应。请求状态代码为200。
fopen
用于创建文件句柄,不会读取任何数据。您可能需要file_get_contents