Internet Radio to Podcast with Shell Tools

Combine several stand-alone programs with some shell “glue” and record your favorite Internet radio show while you sleep.

It all started because I wanted to listen to “Hour of the Wolf” on WBAI radio—it's a cool science-fiction radio program hosted by Jim Freund that features readings, music, author interviews and good “I was there when...” kind of stories. Unfortunately for me, WBAI broadcasts from Long Island, New York, and is too far away from me to receive well. Plus, the show is on Saturday mornings from 5 to 7AM EST—not a really welcoming timeslot for us working folks.

Then, I discovered that WBAI has streaming MP3 audio on its Web site, which solved the reception problem. That left the Oh-Dark-Hundred problem—I'm normally settling into a deep sleep at that hour. And science-fiction buff or no, I'm not going to be catching Jim live any time soon.

The Search

What I needed was a VCR for Internet radio. Specifically, I wanted to capture the stream and save it to disk as an MP3 file, named with the show name and date. I would need to add the proper MP3 ID tags so I could load it into my Neuros audio player for convenient listening. It also would be awfully nice if I could let RSS-compatible software know that I've captured these files. That way, they would show up in a Firefox live bookmark or could be transferred to an iPod during charging. The ultimate effect would be to create an automatic podcast—a dynamically updated RSS feed with links to saved recordings—by snipping a single show out of an Internet media stream at regular intervals.

So, off I went to Google to search for “mp3 stream recording” and “tivo radio” and so on. I found many packages and Web sites, but nothing seemed quite right. Then, I heard a voice from my past—that of the great Master Foo in Eric S. Raymond's “The Rootless Root”, which said to me: “There is more UNIX-nature in one line of shell script than there is in ten thousand lines of C.” So, I wondered if I could accomplish the task using the tools already on the system, connected by a simple shell script.

Collecting the Tools

You see, I already could play the stream by using the excellent MPlayer media player software. Due to patent problems, Fedora Core 3 doesn't ship with MP3 support, so I previously had downloaded and built MPlayer from source as part of the process of MP3-enabling my system. On a side note, MPlayer makes extensive use of the specific hardware features of each different CPU type, so it performs much better as a video player if it is built from source on the machine where you plan to use it. The command:


mplayer -cache 128 \
-playlist http://www.2600.com/wbai/wbai.m3u

served admirably to play the stream through my speakers. All that was left to do was convince MPlayer to save to disk instead. The MPlayer man page revealed -dumpaudio and -dumpfile <filename>, which work together to read the stream and silently save it out to disk, forever and ever. There's no time-out, so it captures until you kill the MPlayer process. Therefore, I wrote this script:


#!/bin/bash

mplayer -cache 128 \
  -playlist http://www.2600.com/wbai/wbai.m3u \
  -dumpaudio -dumpfile test.mp3 &
# the & sets the job running in the background

sleep 30s

kill $! # kill the most recently backgrounded job

which nicely captured a 30-or-so-second MP3 file to disk. The & character at the end of the mplayer command above is critical; it makes MPlayer run as a background task, so the shell script can continue past it to the next command, a timed sleep. Once the sleep is done, the script then kills the last backgrounded task, ending the recording. You may need to adjust the -cache value to suit your Internet connection or even substitute -nocache.

Now that part one was accomplished, I was on to part two—inserting the MP3 ID tags. Back on Google, I found id3v2, a handy little command-line program that adds tags to an MP3 file—and it's already in the Fedora Core distribution! It's amazing, the things that are lurking on your hard drive.

Creating a Podcast

I now had the tools in place to capture and tag my favorite shows. With that in place, I was left with the task of coming up with some way to make a syndication feed from the stack of files. It turns out that RSS feeds are simple eXtensible Markup Language (XML) files that contain links to the actual data we want to feed, whether that be a Web page or, as in this case, an MP3 file.

Another quick look at Google brought me to the XML::RSS module for Perl. It's a complete set of tools that both can create new RSS files and add entries to existing ones. At this point, I thought I was almost done and put together a nice code example that almost worked. In true project timeline tradition, however, the last 5% of the project turned out to require 95% of the total time.

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

This is helpful - but doesn't work... possibly out of date?

ejoso's picture

Does anyone follow this thread anymore? The most recent update being 2007, it's fast become a long tail article...

I've tried this and tinkered with it and the XML::RSS modules kick up pattern match errors for me and I've not been able to resolve them. It would be awesome if any of you fine folks who got this to work in the past could help me out with it...

The errors are:
Use of uninitialized value in pattern match (m//) at /usr/local/share/perl/5.10.1/XML/RSS.pm line 535.
Unregistered entity: Can't access modules field in object of class XML::RSS at /usr/local/share/perl/5.10.1/XML/RSS/Private/Output/Base.pm line 1131

Any thoughts? I pounded away at this for a loong time and wasn't able to get it working as of yet.

Thanks in advance,
Eric

something is broken...

Donovan Worrell's picture

Hi, thanks for the article on this it has helped me automate some recordings I need on a daily basis. A couple of things I noticed...I included the use strict;use warnings on the script you cited and have come up with some odd errors. I have worked through most of them but cannot figure out how to "fix" this:

Unregistered entity: Can't access modules field in object of class XML::RSS at /usr/lib/perl5/site_perl/5.8.5/XML/RSS/Private/Output/Base.pm line 926

any ideas? It seems to be centered around this:


bless\$out,XML::RSS;

based on this error:

Bareword "XML::RSS" not allowed while "strict subs" in use at -e line 1.
Bareword "ARRAY" not allowed while "strict subs" in use at -e line 1.

What am I missing here?

FIXED!!!

Donovan Worrell's picture

Hey,

Much thanks to the maintainers of XML::RSS specifically Shlomi Fish for this diff that fixes this script to work with XML::RSS current.

podcast.diff
--- podcast.sh.old 2007-10-11 20:06:41.077613900 +0200
+++ podcast.sh 2007-10-11 20:11:26.685655662 +0200
@@ -108,31 +108,19 @@

+use strict; \
+use warnings; \
use XML::RSS; \

-my \$in = XMLin('$XML'); \
-my \$out = \$in; \
-bless \$out, XML::RSS; \
-my \$item = \$in->{channel}{item}; \
-
-if ( ( ref \$item ) ne ARRAY ) { \
-
- \$out->add_item(%\$item); \
-} \
-else { \
- foreach \$item ( @{\$item} ) { \
- \$out->add_item(%\$item); \
- } \
-} \
+my \$out = XML::RSS->new(version => '2.0'); \
+\$out->parsefile('$XML'); \

\$out->channel( lastBuildDate => '$XDATE', pubDate => '$XDATE' ); \

... and the ugly version

Anonymous's picture

The ugly compressed version of the perl code is the following:

/usr/bin/perl -e "use XML::RSS; use XML::Simple; \
    $i=XMLin('$XML');$o=$i;bless $o,XML::RSS; \
    $m=$i->{channel}{item};if((ref $m)ne ARRAY) \
    {$o->add_item(%$m);} else \
    {foreach $m (@{$m}) {$o->add_item(%$m);}} \
    $o->channel(lastBuildDate=>'$XDATE', \
    pubDate=>'$XDATE'); \
    $o->add_item(title=>'$XTITLE', \
    link=>$o->{'channel'}{'link'}, \
    pubDate=>'$XDATE', \
    enclosure=>{url=>'file://$FILE', \
    length=>(stat('$FILE'))[7], \
    type=>'audio/mpeg'}, mode=>'insert'); \
    pop(@{$o->{'items'}}) \
    while (@{$o->{'items'}}>$ITEMS); \
    $o->{encoding}='UTF-8'; $o->save('$XML');"

Damn...

Anonymous's picture

I copied the wrong code block; sorry! It should be:

/usr/bin/perl -e "use XML::RSS; use XML::Simple; \
    $o=XML::RSS->new(version=>'2.0');
    $o->parsefile('$XML');
    $o->channel(lastBuildDate=>'$XDATE', \
    pubDate=>'$XDATE'); \
    $o->add_item(title=>'$XTITLE', \
    link=>$o->{'channel'}{'link'}, \
    pubDate=>'$XDATE', \
    enclosure=>{url=>'file://$FILE', \
    length=>(stat('$FILE'))[7], \
    type=>'audio/mpeg'}, mode=>'insert'); \
    pop(@{$o->{'items'}}) \
    while (@{$o->{'items'}}>$ITEMS); \
    $o->{encoding}='UTF-8'; $o->save('$XML');"

What does this achieve?

TRiG's picture

I'm not enough of a geek to understand this. (I'm a trainee geek.) Nor do I yet use Linux. (I may switch over when Microsoft drops XP support. I don't like the way XP tries to organise my life for me, and I'm told Vista is worse.)

With the above code you record a predetermined section of an Internet radio station (a programme), yes? And then you produce RSS code which creates a podcast feed of that program, yes? And then, on another computer, you set up a program (iTunes or something similar) to download that podcast, yes?

Do I understand you right? On computer 1 (always on the Internet), you record the programme and produce the podcast, and then on computer 2 (and potentially many other computers) (occasionally on the internet) you subscribe to that podcast. It seems a long-winded way of going about it, but I can see some benefits.

For those of us without access to always-online computers, is there any way we can set up such podcasts? Can we, somewhere, enter the URL of a live radio station (say http://www.cbc.ca/listen/streams/r1_toronto_32.html) and some times (say 19:00-20:00 on what I think is Eastern Time), and be given a resultant podcast feed to subscribe to?

(I live in Ireland, and don't have much experience with Canadian and US time zones. If you can understand the time expressions on the Vinyl Tap page, please explain them to me.)

Re: What does this achieve?

Phil Salkie's picture

You don't need two computers - the machine which you're saving the radio shows on makes an XML file so that podcast-aware programs can pick up the new radio shows as they're recorded, and automatically put them on to your music player at recharge/sync time. Maybe this will be an excuse to install Kubuntu on a spare hard drive partition and get your feet wet with Linux!

There's no service that I'm aware of that will make a podcast for you, basically for copyright reasons - perhaps someone in a less copyright-frenzied country will do that, and make a ton of money.

For Canadian times, look at: http://www.timetemperature.com/tzca/canada_time_zone.shtml
They seem to be assuming Eastern, AT is Atlantic, NT is Newfoundland.

For a possible way to do a similar thing on your XP machine, look at:
http://streamripper.sourceforge.net/
(You'll have to configure automatic dialing to the internet on your XP system for that to work.)

RDF, not RTF!

Evan Prodromou's picture

You said, "RSS stands for RTF Site Summary." Actually, it stands for "RDF Site Summary" -- the original name from the My Netscape Network. RDF is a framework for making statements about resources (like Web sites); see http://www.w3.org/RDF/ .

RTF is the "Rich Text Format", the default word processing exchange format used in WordPad and other word processors. It has nothing to do with RSS.

Re: RDF, not RTF!

Phil Salkie's picture

You are, of course, correct. Sadly, I've been caught perpetuating one of those errors like "to gild the lily" - so many people do it that it's become almost right. So, indeed, s/RTF/RDF/G9000

use fifo as intermediate wav file

Henk Postma's picture

You may save a lot of intermediate disk space by using a fifo buffer for the wav file. I use this for my particular version of a podcast generator:

#!/bin/bash
# call with $1=url, $2=mp3 file
# to stop recording, kill the mplayer process (killall mplayer)
# create unique name based on md5 hash of stream url and output mp3 file
output=/tmp/`echo $1 $2 | md5sum | awk '{print $1}'`
# make the fifo buffer
mkfifo "$output"
# start mplayer, dump the video (if any) to /dev/null
mplayer "$1" -ao pcm:file="$output" -vo null -vc dummy &
# and start transcoding from the fifo -> mp3 file
lame -S "$output" "$2"
rm "$output"

Kudos and extending the functionality

woodside's picture

I have hacked away on this to a point that it works pretty well for me. It am still having a few minor issues on the rss document ceation when I use the same script to record a few different programs throughout the week. It hasn't risen to the level of actually digging into it again, though. All in all, it works great.

I have been looking for a way to post-process the files to add bookmarks to the files, because one of the shows I record has 10 minute music breaks while they cut to local programming. I am looking for a way to extend this script by overlaying a bookmark. For example, 27 minutes into the show I want to insert a bookmark so that when they cut to music, I hit the forward button and advance to the next bookmark, which would be just before the cut back to the show. This assumes that the show is consistent with cuts, but that doesn't seem to be a problem.

Thanks for the excellent article.

I've brushed up the script

Rick's picture

I've brushed up the script a bit so that you only need one
and everything is pretty much passed from the crontab.

See it here

Cheers,

Rick

Link -

Wong Seuol's picture

Link is not working.. Thanks.. I would like to see ur scripted...

Thanks

Dead link

Kinney's picture

The link you refer to above appears to be dead. Would love to see the revised code.

Re: I've brushed up the script

Phil Salkie's picture

Nice job! Much cleaner than my hack-and-patch approach... Thanks!

Firefox Live Bookmarks and the enclosure tag

eric.john.miller's picture

Firefox live bookmarks do not appear to support the enclosure tag. Do you have a workaround for this?

I've been thinking about putting together something like this for a while. Thanks for a great article!

Re: Firefox Live Bookmarks and the enclosure tag

Phil Salkie's picture

Sure - it breaks the "link" feature on some news aggregators, but makes the live bookmarks work again. Sigh...

Change this bit of perl:
link=>$o->{'channel'}{'link'}, \

To this:
link=>'file://$FILE', \

With this change (assuming you have some useful plugin like Plugger or MPlayer Plugin) clicking on the live bookmark starts playing the captured file. This is really how it should have been in the article - it's much more useful than having the link to the homepage, plus that link is in the title section anyway.

Re: Firefox Live Bookmarks and the enclosure tag

eric.john.miller's picture

Thanks, that did the trick!

Mplayer?

tpurl's picture

Why not use streamripper instead? As long as you're writing your content to a file, streamripper works very well and requires fewer command switches.

Mplayer?

Sean Edwards's picture

Mplayer, ecasound, sox . . . there are many command-line audio tools. I prefer ecasound myself.

Re: Mplayer?

Phil Salkie's picture

(This comment got deleted because I'd managed to cross-up my user names... Here's my second try at it.)

Streamripper was one of the programs I looked at when I first tried to do time-based capture. I thought it would be the do-everything package that I wanted, but I found that it

1) Has almost no Linux documentation available from the website
2) Has a limited number of stream types that it can access
3) Has timed duration, but not timed start
4) Can't transcode (i.e. take a RealPlayer stream and save it as MP3)
5) Has ID3V2 file tagging, but it wasn't clear if you could tag with data that didn't come from the stream itself.

That being said, it seems to be a pretty capable package, and if it saves the shows you want in the format you want, great - you're absolutely right - it saves some messing around in the script, especially if you can get the MP3 tags to do what you want. But its main purpose seems to be to capture _songs_ from internet radio streams (like shoutcast), not whole _programs_.

So, it was sufficiently not what I was looking for that I opted to take the program which I was already using as a listener tool (MPlayer) and make it be what I wanted (a VCR for Internet Radio) by using a shell script. (Plus, that seemed to be a cool enough thing to do to write an article about.)

Thanks for the article

Joel's picture

Thanks for the article. It should be a good reference, even I don't need to do exactly what you're doing.

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix