Save audio file on rails

I have a simple rails application in which I use HTML5 audio web api with recorder.js to record voice and then save it on the application server. The recording is normal, I can play the recording and hear the sound, but when I post it on the server, my audio file is empty.

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>>} 
+4
source share
2 answers

Ok, I got an answer.

The problem is when the file enters, it will have a read cursor installed at the end of the file, so you must first rewind the file to make sure that the read cursor is set to the beginning.

My controller code is changed 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 
+2
source

Try:

 File.open(save_path, 'wb:binary') do |f| 
0
source

Source: https://habr.com/ru/post/1502177/


All Articles