Last Updated: July 25, 2019
·
457
· blazeeboy

Share your music library on the network

this script uses sinatra to share your media files from your songs library the script will enable users to play music on page using a streaming url
this script is part of a larger one to create a media library on the network with upload capability, play list, favorite, commenting...etc
something like grooveshark.com but on the local network.
if you want to participate please fork this project, enhance teh script and commit it.

Gist : https://github.com/blazeeboy/RubyScripts/tree/master/05-21-2014

#!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)

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 = mp3s.map do |mp3|
  {
    path: mp3,
    filename: File.basename(mp3, '.mp3')
  }
end

# 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 = data.map.with_index 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>'
<<-EOT
<!DOCTYPE html>
<html>
  <head>
    <style>
      body{
        font: 14px Tahoma;
        line-height: 150%;
      }
    </style>
    <title>Shared Media Center</title>
  </head>
  <body>
    #{media_partial}
    <hr>
    #{data.size} Media files found.
  </body>
</html>
EOT
end

# 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]
end