将音频文件保存在rails中

我有简单的rails应用程序,我使用HTML5音频web api与recorder.js录制语音,然后将其保存在应用程序服务器上。 录音发生很好,我可以重播录音和听到声音,但当我在服务器上发布时,我的音频文件是空白的。

html / js代码

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."); } }; } 

控制器代码

 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 

控制台日志

 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=#>} 

好的,我得到了答案。

问题是当文件进入时,它会将读取光标设置到文件的末尾,因此我们需要首先回放文件以确保将读取光标设置为开头。

将我的控制器代码更改为以下,它工作正常。

  audio.rewind # Open and write the file to file system. File.open(save_path, 'wb') do |f| f.write audio.read end 

尝试:

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