I have simple rails app where I use HTML5 audio web api with recorder.js to record voice and then save it on application server. Recording is happening fine, I can replay recording and hear the sound but when I post it on server my audio file is blank.
html/js code
function stopRecording() {
recorder.stop();
recorder.exportWAV(function(s) {
audio.src = window.URL.createObjectURL(s);
sendWaveToPost(s);
});
}
function sendWaveToPost1(blob) {
alert('in');
var data = new FormData();
data.append("audio", blob, (new Date()).getTime() + ".wav");
var oReq = new XMLHttpRequest();
oReq.open("POST", "/audio/save_file");
oReq.send(data);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
console.log("Uploaded");
} else {
console.log("Error " + oReq.status + " occurred uploading your file.");
}
};
}
Controller code
def save_file
audio = params[:audio]
save_path = Rails.root.join("public/#{audio.original_filename}")
# Open and write the file to file system.
File.open(save_path, 'wb') do |f|
f.write params[:audio].read
end
render :text=> 'hi'
end
Console log
Parameters: {"audio"=>#<ActionDispatch::Http::UploadedFile:0xb61fea30
@original_filename="1379157692066.wav", @content_type="audio/wav", @headers="Content-
Disposition: form-data; name=\"audio\"; filename=\"1379157692066.wav\"\r\nContent-Type:
audio/wav\r\n", @tempfile=#<File:/tmp/RackMultipart20130914-3587-tgwevx>>}
Okay, I got the answer.
The issue is when the file comes in, it will have th read cursor set to the end of the file so we need to rewind the file first to ensure read cursor is set to the beginning.
Changed my controller code to below and it worked.
audio.rewind
# Open and write the file to file system.
File.open(save_path, 'wb') do |f|
f.write audio.read
end
Try:
File.open(save_path, 'wb:binary') do |f|
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With