Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save audio file in rails

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>>}
like image 833
pramodtech Avatar asked Sep 14 '13 11:09

pramodtech


2 Answers

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
like image 64
pramodtech Avatar answered Oct 19 '22 07:10

pramodtech


Try:

File.open(save_path, 'wb:binary') do |f|
like image 30
BroiSatse Avatar answered Oct 19 '22 06:10

BroiSatse