开发者

Playing an MP3 through Ruby on Rails in chrome

I'm writing a Ruby on Rails application which allows a user to upload an mp3 file, then play it back. I have it working to the point where a user can do those things, BUT there is an issue when seeking through the song. If a user seeks ahead (or lets it play) to a spot in the song, usually about 2/3 or 3/4 the way through the song, then attempts to seek back to the beginning (for example 0:20), the play timer will go to 0:20, like it should but the actual audio will start over again as if the user seeked to 0:00.

Right now I'm simply attempting to get the song to play in chrome's basic html5 mp3 player that it uses when passed an mp开发者_StackOverflow中文版3 file. This is the code I'm using to serve up the file, hopefully with all the correct headers:

  file_begin = 0
  file_size = @media.file_file_size 
  file_end = file_size - 1

  if !request.headers["Range"]
    status_code = "200 OK"
  else
    status_code = "206 Partial Content"
    match = request.headers['range'].match(/bytes=(\d+)-(\d*)/)
    if match
      file_begin = match[1]
      file_end = match[1] if match[2] && !match[2].empty?
    end
    response.header["Content-Range"] = "bytes " + file_begin.to_s + "-" + file_end.to_s + "/" + file_size.to_s
  end
  response.header["Content-Length"] = (file_end.to_i - file_begin.to_i + 1).to_s
  response.header["Last-Modified"] = @media.file_updated_at.to_s

  response.header["Cache-Control"] = "public, must-revalidate, max-age=0"
  response.header["Pragma"] = "no-cache"
  response.header["Accept-Ranges"]=  "bytes"
  response.header["Content-Transfer-Encoding"] = "binary"
  send_file(DataAccess.getUserMusicDirectory(current_user.public_token) + @media.sub_path, 
            :filename => @media.file_file_name,
            :type => @media.file_content_type, 
            :disposition => "inline",
            :status => status_code,
            :stream =>  'true',
            :buffer_size  =>  4096)

I'd appreciate any insight into this problem. I feel like I'm so close because it pretty much all works, except for seeking near the beginning causing a new request.

Thanks!


Is re-invention of the wheel a requirement? The reason I ask is you could have simply allowed the user to upload the MP3 file and used html5's feature as you're targeting Chrome. Paperclip could have taken care of the upload, to somewhere preferable in the public directory, and you just hand off that path to the tag.

Crazy ideas removed from my comments (below) to prevent confusing other SO readers. See my last comment for a solution but Amazon S3 is pretty much the best solution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜