Copyright © 2010 The G String. All Rights Reserved. Snowblind by Themes by bavotasan.com. Powered by WordPress.
Posts Tagged ‘ Streaming ’
I had just resurrected some old music from my music collection; some good, some very, very bad; but I wanted to be honest and display the information on my music blog. After all, it would show I have good taste in music ;)
I was streaming music using the excellent Icecast streaming server, and I wanted to display the currently playing track on my rails-based music blog as a link, which when clicked would feed the artist and track info into Google in a new window to help others find out about artists they might not have heard of. Fortunately, the current track information is provided by Icecast and is used by iTunes to display the current track information while I’m listening. The information is hosted on the admin section of the icecast server, /admin/stats.xml, so actually the simple solution would be to grab that XML file, parse it, and obtain the track information. The element I was interested in was called ‘Title’, under the source element, which contained the Artist – Track Title information, presumably from the mp3′s ID3 tag.
The first step was to obtain the XML file and read in the value of the Title element. I created a method named currently_playing in the application_helper.rb file, which would enable the method to be available to any view in the application.
Net::HTTP.start(‘hostname.co.uk’ , 8888) {|http|
req = Net::HTTP::Get.new(‘/admin/stats.xml’)
req.basic_auth ‘admin’, ICECAST_ADMIN_PASSWORD
response = http.request(req)
xml = REXML::Document.new response.body
xml.elements.each(‘icestats/source/title’) { |title|
return title.text
}
}
Note that I used a constant value for the Icecast admin password, controlled via the constants.rb file in the config folder. This nice block of code HTTP gets the XML file, takes care of the basic HTTP authentication and turns the result into an XML DOM, using XPath to retrieve the value of the Title element.
I decided that I wanted to display this information in the top-right of my header, so I found that component in rails and added a link:
<% cl = currently_listening
unless cl.empty? %>
<div id=”currentlylistening”>
Currently listening to : <%= link_to cl, { :controller => ‘referrals’, :action => ‘redirect_google’,
:title => CGI.escape(cl)}, :target => ‘_blank’ %>
</div>
<% end %>
Finally, I added a method in my referrals controller, called redirect_google. That way, I don’t lose page rank having a link to Google and instead redirect the user where I want them to go.
def redirect_google
redirect_to ‘http://www.google.co.uk/search?q=’ + params + ‘&ie=utf-8&oe=utf-8&aq=t’
end
Now, whenever the user visits a page, they can see what I’m actually listening to in iTunes. Time to delete my embarrassing Simply Red, Eternal and Cher tracks…
I like to think that I stay ahead of the times. In 2000, I used to think that my Creative Nomad jukebox with 6GB of hard-disk space was the most incredible thing ever, and I took mine to University, proud of its ability to reduce a shelf-load of CDs into an object no larger than one or two discs. It was cool how you could take a bunch of music, let them all get strung together into a continuous stream, and have them played back in a random order, like your own personal radio station without the ‘personalities’. Back then, Creative had to market them as jukeboxes- they were still too bulky to be used like iPod shuffles are now. But that was nearly ten years ago, and times must move on.
I have found that the biggest problem after moving to mp3s is keeping up with my collection. I stopped collecting after around 20GB and began to just have smaller collections here and there: some music on my PC laptop, some on my Mac, some on my PC, some on a mp3 player. Overall, it became difficult to keep it all in one place, and so whenever I’d buy a CD, download an album or mix one of my own tracks my collection would become increasingly fragmented. Its got to the stage now where I haven’t actually listened to parts of my collection for many months, so I decided to do something about it.
I wanted to setup my own jukebox, streaming music over the web, so that I could access it wherever I was, from any platform, at any time. That way, all my music is in one place and I save heaps of disc space on my local computers.
So I decided to setup Icecast, an open-source streaming server. It works by receiving an audio stream from somewhere, and converting it into itty-bitty-bytes that are downloaded to clients over the Internet, such as iTunes. The audio stream can be a live feed from a soundcard, or taken from a playlist running off your hard drive. I used the latter approach, because I have a large directory of mp3 files that I want to listen to. This involves using another piece of software called Ices, which is responsible for building the audio stream sent to Icecast. Its a handy piece of software; working from a playlist, it can randomly choose a track, re-sample it to a lower bitrate (to save your bandwidth costs and keep the music playing smoothly) and even cross-fade between tracks.
While I was busy rsyncing my music collection to my server, I downloaded and installed icecast 2.3.2 and ices 0.4 from source. I chose the older version of ices, because it deals with mp3s, whereas the newer version can only read ogg Vorbis files, and my collection consists mainly of mp3 files. I needed to install a couple of dependencies thrown up by configure, specifically libxslt, which I did using apt-get. So far so good.
The first configuration step was configuring Icecast. By default, icecast creates a configuration file in /usr/local/etc/ called icecast.xml which you can edit. The file is commented with examples, and can be tweaked as needed. Don’t forget as this is an XML file that it should be well-formed with matching opening and closing tags, as well as opening and closing comments (and no nesting comments!). I reduced the number of clients (it is a private stream for me!), set the hostname/port, log directory and the source, relay and admin passwords (they’re ‘hackme’ by default!). Following that, I was able to test the server was working by running icecast and checking the error.log file:
icecast -c /usr/local/etc/icecast.xml
tail /var/log/icecast/error.log
I could also visit the admin pages at the hostname and port I had configured, which show a basic admin interface.
The next step was to provide audio for Icecast by configuring Ices. Similarly, the default install created an example configuration file in /usr/local/etc/ called ices.conf.dist. I moved this to ices.conf and began to edit. I changed:
- <File> – I set this to be the playlist file I wanted for the stream. The playlist file is simply a text file with a path to an mp3 file on each line, so I generated it automatically from the music files I kept in /music.
find /music -name *.mp3 > /usr/local/etc/playlist.txt - <Randomize> – I set this to 1 so that Ices jumped around the list, creating a radio station style mix, rather than playing through sequentially.
- <Crossfade> – I set this to 5 so that each song fades-in/fades-out over the course over five seconds, resulting in nice, continuous play.
- <BaseDirectory> – I set this to be the same as the log directory of Icecast so that the logs were nearby each other.
- <Hostname> – I set this to match the hostname I configured in Icecast.
- <Port> – Ditto…
- <Password> – Same…
- <Name> – I set this to “Dan’s Jukebox”, which is what the stream is listed under in iTunes.
- <Genre> – I set this to “Anything”.
- <Description> – This also appears on the web interface and iTunes so I wrote something in there too.
- <URL> – This URL is a page used to describe the stream, and appears on rotation in the iTunes interface so I used my website URL.
- <Public> – I set this to 0 so that the stream isn’t listed publicly and I get subpoenaed by the RIAA…
- <Bitrate> – Very important! This is the setting that Ices uses to determine what quality to send the audio in, and has implications on the amount of bandwidth you use; which in turn determines the financial cost and smoothness of your stream. If your stream is available to multiple users, you have to consider that this figure would be multiplied by the number of listeners, so be careful not to set it too high. 64kbps is about the quality you get listening to MySpace and is low-quality; but you won’t really notice if listening on a laptop speaker anyway. Bearing in mind that the mp3s were mostly encoded at 128kps originally, I decided to keep my bandwidth use down and started out with 64kbs. It sounds alright to me, maybe I’ll ramp it up to about 80-something later if I feel like it.
Once configured, I tested Ices by running it without any options:
ices
By default, Icecast and Ices run in the foreground, which means that once you start running them they don’t return the console back to you and you have to open another to keep using Linux. I wanted them to run in the background as daemons so that when my server boots up / restarts, or I log-out, the music keeps going. I so put together two init.d scripts, starting from /etc/skeleton, to start/stop Icecast and Ices. Below is the icecast init.d script I’m using, and Ices is similar.
#! /bin/sh
# Author: Dan Garland dan@NOSPAMdangarland.co.uk>
# Do NOT “set -e”
# PATH should only include /usr/* if it runs after the mountnfs.sh script
PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC=”Icecast Server”
NAME=icecast
DAEMON=/usr/local/bin/$NAME
DAEMON_ARGS=”-b -c /usr/local/etc/icecast.xml”
ICES=/usr/local/bin/ices
USER=$NAME
GROUP=$NAME
PIDFILE=/var/run/$NAME.pid
ICES_PIDFILE=/var/run/ices.pid
SCRIPTNAME=/etc/init.d/$NAME
# Exit if the package is not installed
|| exit 0
# Read configuration variable file if it is present
&& . /etc/default/$NAME
# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh
# Define LSB log_* functions.
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
. /lib/lsb/init-functions
#
# Function that starts the daemon/service
#
do_start()
{
# Return
# 0 if daemon has been started
# 1 if daemon was already running
# 2 if daemon could not be started
start-stop-daemon –start –quiet –chuid $USER:$GROUP –pidfile $PIDFILE –exec $DAEMON –test > /dev/null \
|| return 1
start-stop-daemon –start –quiet –chuid $USER:$GROUP –pidfile $PIDFILE –exec $DAEMON — \
$DAEMON_ARGS \
|| return 2
# Add code here, if necessary, that waits for the process to be ready
# to handle requests from services started subsequently which depend
# on this one. As a last resort, sleep for some time.
}
#
# Function that stops the daemon/service
#
do_stop()
{
# Return
# 0 if daemon has been stopped
# 1 if daemon was already stopped
# 2 if daemon could not be stopped
# other if a failure occurred
start-stop-daemon –stop –quiet –retry=TERM/30/KILL/5 –pidfile $PIDFILE –name $NAME
RETVAL=”$?”
&& return 2
# Wait for children to finish too if this is a daemon that forks
# and if the daemon is only ever run from this initscript.
# If the above conditions are not satisfied then add some other code
# that waits for the process to drop all resources that could be
# needed by services started subsequently. A last resort is to
# sleep for some time.
start-stop-daemon –stop –quiet –oknodo –retry=0/30/KILL/5 –exec $DAEMON
&& return 2
# Many daemons don’t delete their pidfiles when they exit.
rm -f $PIDFILE
return “$RETVAL”
}
#
# Function that sends a SIGHUP to the daemon/service
#
do_reload() {
#
# If the daemon can reload its configuration without
# restarting (for example, when it is sent a SIGHUP),
# then implement that here.
#
start-stop-daemon –stop –signal 1 –quiet –pidfile $PIDFILE –name $NAME
return 0
}
case “$1″ in
start)
&& log_daemon_msg “Starting $DESC” “$NAME”
do_start
case “$?” in
0|1) && log_end_msg 0 ;;
2) && log_end_msg 1 ;;
esac
;;
stop)
&& log_daemon_msg “Stopping $DESC” “$NAME”
do_stop
case “$?” in
0|1) && log_end_msg 0 ;;
2) && log_end_msg 1 ;;
esac
;;
#reload|force-reload)
#
# If do_reload() is not implemented then leave this commented out
# and leave ‘force-reload’ as an alias for ‘restart’.
#
#log_daemon_msg “Reloading $DESC” “$NAME”
#do_reload
#log_end_msg $?
#;;
restart|force-reload)
#
# If the “reload” option is implemented then remove the
# ‘force-reload’ alias
#
log_daemon_msg “Restarting $DESC” “$NAME”
do_stop
case “$?” in
0|1)
do_start
case “$?” in
0) log_end_msg 0 ;;
1) log_end_msg 1 ;; # Old process is still running
*) log_end_msg 1 ;; # Failed to start
esac
;;
*)
# Failed to stop
log_end_msg 1
;;
esac
;;
*)
#echo “Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}” >&2
echo “Usage: $SCRIPTNAME {start|stop|restart|force-reload}” >&2
exit 3
;;
esac
:
Note the -b option to run in the background and the –chuid option to run the program as the icecast user and group (Icecast doesn’t run as root). If you don’t have a icecast user or group, create them as root with the adduser and addgroup commands:
adduser icecast
addgroup icecast
I could then tell Debian to run these scripts at start-up using update-rc.d:
update-rc.d icecast defaults
update-rc.d ices defaults
Once running, I could point iTunes to the stream by choosing Advanced -> Open Audio Stream, and typing in the full url to the mointpoint. Now I’m listening to some track I swear I haven’t heard since the mid 90′s, and I want to tell the world.
