将音频文件保存在rails中 [英] Save audio file in rails

查看:81
本文介绍了将音频文件保存在rails中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

控制器代码

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=#<File:/tmp/RackMultipart20130914-3587-tgwevx>>}


推荐答案

好的,我得到了答案。

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

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

这篇关于将音频文件保存在rails中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆