5

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>>}
pramodtech
  • 6,300
  • 18
  • 72
  • 111
  • Can you use pry or other debugger to stop execution just before `File.open`, check the temporary file path using `params[:audio].tmpfile` and check if that file is not blank ? (just wanting to bisect problem a bit to know if it occurs on client side or server side part) – kik Sep 14 '13 at 11:40
  • tmpfile doesn't exist, I printed output params[:audio].tempfile n it gives something like # – pramodtech Sep 14 '13 at 11:48

2 Answers2

4

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
pramodtech
  • 6,300
  • 18
  • 72
  • 111
1

Try:

File.open(save_path, 'wb:binary') do |f|
BroiSatse
  • 44,031
  • 8
  • 61
  • 86