I write an application with speech recognition. All I want is to record some speech and send it to server where I will convert it into text. And I have a problem with sending that sound file. I record voice using p5.js library and when I try to download it there is no problem.
The problem is when I try to send it to server using ajax.
script.js
function toggleRecording(e) {
if (e.classList.contains("recording")) {
recorder.stop();
e.classList.remove("recording");
sendAudioToServer(soundFile)
} else {
e.classList.add("recording");
recorder.record(soundFile);
}
}
function sendAudioToServer(soundFile)
{
var data = new FormData();
data.append('fname', 'test.wav');
data.append('data', soundFile);
console.log(soundFile);
console.log(data);
$.ajax({
type: 'POST',
url: '/recognizeCommand',
data: data,
dataType: 'jsonp',
processData: false,
contentType: false,
success: function(data) {
alert("works!");
},
error: function() {
alert("not works!");
}
})
Java controller
@PostMapping("/recognizeCommand")
public @ResponseBody String recognizeCommand(@RequestParam MultipartFile mpf) {
try {
byte[] bytes = mpf.getBytes();
SpeechRecognitionApplication.logger.info(bytes);
} catch (IOException e) {
e.printStackTrace();
}
return "finish";
}
When I stop recording regardless to toggleRecording function it should stop recording and send it to server. And there is a problem with sendAudioToServer function. Here is the result from Chrome console:
I'm not sure but there is probably problem with FormData. As you can see when I printed it in console it's empty. Founded some similar questions here but there is no solution to solve my problem.
EDIT:
After add dataType: 'jsonp'
There is that error:
EDIT 2:
After adding csrf token:
解决方案
Please add csrf tokens as this.
In header:
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
Set headers.
$.ajax({
type: 'POST',
url: '/recognizeCommand',
data: data,
dataType: 'json',
processData: false,
contentType: false,
beforeSend: function(xhr) {
// here it is
xhr.setRequestHeader(header, token);
},
success: function(data) {
alert("works!");
},
error: function() {
alert("not works!");
}
})
Try adding debug point here.
SpeechRecognitionApplication.logger.info(bytes);