DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Emad has posted 58 posts at DZone. View Full User Profile

Share your music library on the network

  • submit to reddit
#!/usr/bin/env ruby
# Author : Emad Elsaid (

require 'sinatra' # gem install sinatra

# specify port and environment as production
# to allow external access to server
set :port, 3000
set :environment, :production
# your media library path
MEDIA_PATH = '/Volumes/Data/Songs'

# get all mp3 files in my media library and sort
# then by file name
mp3s = Dir.glob("#{MEDIA_PATH}/**/*.mp3")
data = do |mp3|
    path: mp3,
    filename: File.basename(mp3, '.mp3')

# render the index page as set if files names
# and a player beside it, player will sent file index in data variable
# and another path will read file to stream it
get '/' do
  media_partial = do |d, i| 
    '<audio src="/play/'+i.to_s+'" controls preload="none"></audio> '+
    '<a href="/play/'+i.to_s+'">'+d[:filename]+'</a>'
  end.join '</br>'
<!DOCTYPE html>
        font: 14px Tahoma;
        line-height: 150%;
    <title>Shared Media Center</title>
    #{data.size} Media files found.

# this path will catch any url starts with "play"
# and will stream media to user, so when
# user hit the play button it'll start playing
# the mp3 file
get '/play/:id' do
  send_file data[params[:id].to_i][:path]