title: Ruby CGI Stream Audio
body: <p>What I want to do is use a CGI script (written in Ruby) to read a binary file off of the filesystem (audio, specifically) and stream it to the browser.</p>
  
  <p>This is how I am doing that so far,</p>
  
  <pre><code>require 'config'
  
  ENV['REQUEST_URI'] =~ /\?(.*)$/
  f= $config[:mdir] + '/' + $1.url_decode
  f = File.open f, 'rb'
  
  print "Content-Type: audio/mpeg\r\n"#TODO: Make it guess mime type
  print "\r\n"
  
  #Outputs file
  while blk = f.read(4096)
      $stdout.puts blk
      $stdout.flush
  end
  
  f.close
  </code></pre>
  
  <p>It's not perfect, there are security holes (exposing the whole filesystem..), but it just isn't working right. It's reading the right file, and as far as I can tell, outputting it in 4k blocks like it should. Using Safari, if I go to the URL, it will show a question mark on the audio player. If I use wget to download it, it appears to work and is about the right size, but is corrupted. It begins playing fine, then crackles, and then stops. </p>
  
  <p>How should I go about doing this? Do I need to Base-64 encode, if can I do that without loading the whole file into memory in one go?</p>
  
  <p>Btw, this is only going to be used over local area network, and I want easy setup, so I'm not interested in a dedicated streaming server.</p>