Pi Zero streaming audio player

Pi streaming audio

RANT MODE ON. As I get older, I find I have less and less patience with the brain-dead moron who claims to be a 'presenter' (or 'DJ') of the 'terrestrial' Radio 'show'. Each and every one of them appears to be so in love with the sound of their own voice that they insist on wasting my life by reading out the never-ending reasons why some idiot listener is making a 'request' or has written in with some other useless uninteresting 'facts' about their boring pointless lives, even to the extent of babbling over the start and end of every music track

Then, just when you think the 'presenter' has finally run out of verbal diarrhea, they switch over to a series of never-ending advertisements for overpriced rubbish that I will never, ever, be insane enough to purchase. Often I'm amazed there is any time left over to play the occasional music track before the end of their thankfully short 1 Hr shows. Even the 'classical music' radio stations have become 'never ending chat shows', fed by listeners requests and filled with composer 'factoids' (no, I don't care where/when/who first played this composition, nor do I care who it was 'dedicated to' or 'commissioned by'). Why the f*ck they can't just play the damn music without all their useless 'chit-chat' and voice-over 'padding' I'll never know. In short, I've now reached that age (over 20) where I never ever want to listen to another time-wasting 'terrestrial broadcast' radio station ever again, never ever. RANT MODE OFF

Building a Pi streaming audio player

The answer to 'How can I banish boring DJ's and annoying adverts for ever ?" is, of course, to play your own (ripped) music tracks - or tracks from an Internet 'streaming radio' service that plays the sort of material ('genre') you like. Of course you can use Windows Media Player (along with it's built-in DRM) but that requires your PC be 'on' all the time. Alternatively you can build a 'stand-alone' player using the Raspberry Pi and use your Hi-Fi sound system

Whilst the 'cheapest' stand-alone approach is to use the £4 Pi Zero, it has a potential drawback - the lack of a 'stereo output'. Of course the Pi's built-in stereo output is not very (or even at all) "Hi-Fi", so whilst it's possible (with a lot of effort) to wire up the Pi Zero GPIO i/o pins to your own stereo jack circuit you will get much better quality from the mini-HDMI (with an external audio split off adapter) or via a USB 'dongle' or, best of all, via an I2C/I2S DAC add on 'hat'. A Pi Zero (£4) plus a basic I2C/I2S audio DAC 'hat' the 'Phat DAC' (a HiFiBerry for the Pi Zero for £12) costs less than a Pi A+ with poor quality stereo jack (£18)

Free music Internet Radio

Free internet music is, of course, riddled with adverts. However most services also offer a paid for 'advert free' option, and the cost of the advert free option is not as high as it used to be (although still double in UK what you pay in USA). Of course, there are also ways to avoid listening to the averts on the 'free' services. What's more, it's really easy to set up the Pi to play music from an Internet 'radio station' !

Windows is riddled with DRM 'support' - if you want to avoid DRM problems you have to avoid Windows

Audio output from the Pi

Getting 'Hi Fi' from the Pi is a pain. The built-in stereo jack on the A+ / B+ gives "almost un-acceptable" quality as it's no better than 6 or 7 bits ('wav' audio is 16 bits !).

However all Pi's have a built-in HDMI socket - and, for those with sound systems that have HDMI inputs, this is the route I recommend (you can't beat the original digital for 'Hi Fi' quality, so the only reason for not using the HDMI socket is to avoid 'tying' your Pi music player to your Home Cinema system).

If you have a modern 'Home Cinema' 5.1 Surround Sound system with HDMI inputs, it will play the raw digital .wav or .ac3 (5.1) just fine (although you will need to make sure the Pi uses 'pass through' mode if you want 5.1)
It's those with older Home Cinema (with S/PDIF) that will have problems getting surround sound. The problem is, of course, the Music Industry, their obsession with DRM and their doomed attempts to prevent digital sound extraction from the HDMI data stream.

To extract digital data (ac3 or 6 channel PCM for older PC speakers) from HDMI you will have to purchase the converter from China (outside the reach of the Music Industry) or pay through the nose for a 'Licenced' converter (intended for Studios and 'money no object' audiophiles). Look for "HDMI Digital Multi-channel Audio Decoder" on eBay (the 'headline' cost is about £30, however that exceeds the VAT-free import duty limit, so will attract 20% VAT + a £10 handling charge, and you will end up paying nearer £50)

A cheap way to get analogue audio from the HDMI socket is by using a 'HDMI-VGA converter with audio'. However whilst all 'converters' will 're-mix' the 5.1 and 'downgrade' it to analogue stereo 'just fine', they are not aimed at producing Hi-Fi quality (although they will do a better job than the Pi on-board stereo jack).

Another approach is to use a USB audio 'dongle'. However most are aimed at 'gamers', so typically distort the playback (by boosting the bass for better sounding gunshots and explosions). The data 'drop out' problem (see below) rather 'rules out' all USB 'dongles' so I don't consider them further.

The Pi has a single USB GPIO port which has to be shared between all USB devices and the Ethernet. This is true for all Pi's (the 'higher end' Pi's just have an on-board hub that uses the same single GPIO USB port)
Further, the CPU has to do all the USB data shuffling - so making it do e.g. mp3 conversion at the same time leads to insufficient CPU cycles left to handle data i/o.
So USB audio playback can suffer from 'data dropouts', especially if you are trying to play anything other than a 44.1kHz 16 bit wav file or transfer data from a network 'share' at the same time.
About the only way to get a USB audio dongle to play back without 'dropouts' is to fully 'buffer' the audio track. This means fetch it from your network and hold it as .wav on the Pi SDHC card before trying to play it - and then avoid doing ANYTHING on the network or any other USB devices whilst playing the music track

There is, of course, one big advantage in holding tracks on the Pi SDHC card = it makes your player truly portable (especially so if you build it with a battery option = see at end below) !

Most I2C/I2S DAC 'hats' available in UK - such as the 'HiFiBerry' and 'RASPYPLAY3' - are priced from £18 to £30 or so.
At the higher end you get digital co-ax and/or S/PDIF as well as analogue outputs = see, for example, the WINGONEER HIFI DiGi+ (for about £28) and the (rather over-hyped, over specified) Cirrus Logic / Wolfson at £35 (which uses 14 GPIO pins !), all aimed at the truly dedicated 'price no object' audiophile.
Since I have very few 5.1 music tracks (.ac3) but still wanted 'Hi Fi' for not a lot of cash, I decided to use my existing sound system with an I2C/I2S DAC, although I also consider (below) using the stereo jack (A+) and HDMI (via a HDMI-VGA converter with audio extract)

I recommend sticking to the basic DAC 'hat' that just uses the I2C/I2S bus - such as a HiFiBerry DAC+ re-sized for the Pi Zero and renamed the pHAT-DAC. This can be had for a mere £12, which is about the same cost as some 'no-name' / 'no drivers' I2C/I2S audio DAC from China (via eBay). Note the pHAT-DAC PCB is tracked for RCA sockets but only a 3.5mm stereo jack ('Line Out') is fitted as standard

An alternative is the Pi-DACZero. This has a lower 'headline' price of £7.80, but to this is added £4.60 shipping, giving a total of £12.40 (for 1 off), making it slightly more expensive than the pHAT-DAC (which can be ordered as the same time as your Pi Zero from Pimoroni at no extra postage cost). The Pi-DACZero does have one advantage over the pHAT-DAC and that's having RCA sockets as standard (rather than a stereo jack socket with RCA extra). There is also mention of a 3pin header for a Rotary Encoder (however you can wire that to the Pi Zero i/o header direct i.e. without needing a plug). As with the pHAT DAC, the Pi-DACZero uses the Linux drivers already built into Raspbian. So no kernel recompilation needed (it uses the I2S interface)

NOTE I've not actually tried the Pi-DACZero (a 'whois' on the IQaudio web site revealed it is Registered to an individual who claims to be 'non-trading' :-) but they appear legit (VAT number checks out, for example) plus they have a Canadian agent (http://www.pi-shack.com)))

Using Pi Stereo jack GPIO output

All Pi's (except the Zero), have a stereo jack output. This is achieved by using the SoC's built-in Pulse Width Modulation (PWM) circuits (PWM0_OUT (Right channel) = GPIO pin 40, and PWM1_OUT (Left channel) = GPIO pin 45) which are then wired to a low-pass filter and capacitively coupled to the stereo jack socket.

On the Pi Zero, GPIO 40 and 45 are not 'tracked' from the SOC - and whilst it's possible to 'redirect' PWM0_OUT to GPIO 18 (ALT 5) and PWM1_OUT to GPIO 13 (ALT 5) or 19 (ALT 0) - which are tracked from the SOC to the 0.1" holes - this is REALLY HARD to do without access to the "dt-blob device tree" definitions for the Pi Zero. You then have to build your own 'low pass filter' circuit (which is likely to suffer from the same hiss and hum as the 'classic' A/B unless you also fit a voltage reg. like the A+/B+ have).
If you must build a 'stereo jack' for the Pi Zero, for further details, see here

If you really want to use the stereo jack analogue output, just choose the Pi A+ instead of the Zero. If you want to continue with the Pi Zero but not use an I2C/I2S DAC 'hat', I recommend using the mini-HDMI socket - the quality will be better that the stereo jack and a lot less hassle

Direct Stereo output from the Pi is not Hi-Fi. It's about 6 or 7 bit resolution (nowhere near the .wav 16 bit original). In short, if you want quality audio you will have to look elsewhere

Using the Pi HDMI output

The cheapest way to get 'acceptable' audio is from the HDMI socket, using a 'HDMI-VGA with audio' converter. I recommend one that has an external power option (some have micro-USB sockets, others have a micro-bullet socket but come with a USB-bullet plug cable). All can be had for less than £5 on eBay.

WARNING - you will find many 99p 'HDMI to RCA cable' offerings - these DO NOT CONTAIN the active circuitry required to extract and convert the digital HDMI signals into analogue stereo audio.

Using I2C/I2S DAC audio output (recommended)

Much like a PC, all you need to do is install the 'right' audio driver and then all audio applications will output via the new hardware (at least they will after you disable the old hardware, enable the new and reboot)

Unlike a PC, code to access the audio chip has to be 'built into' the Pi operating system kernel. Fortunately, support for all the 'common' audio DAC chips is already built into the Raspbian Jessie package (it's just a matter of 'activating' the right code during boot-up). However IF you purchase some 'no name' I2C/I2S DAC from China, you may end up trying to rebuild the Raspbian kernel !

Before starting anything 'new', it's always a 'good idea' to make sure you have the latest version of Raspbian and all it's components - however once you get your project working, DO NOT update anything !

To update Raspbian :-
$ sudo apt-get update

If you went for the recommended "pHAT DAC", you can download and install all the drivers etc. from the Pimoroni web site using a single command :-

The pHAT DAC uses the same hardware as the HiFi Berry, so enable that 'device-tree overlay' :-

Edit the config.txt file, find the line #dtoverlay=hifiberry-dac and remove the '#' (or just add the line) :-
$sudo nano /boot/config.txt
dtoverlay=hifiberry-dac
Also in /boot/config.txt, check for 'dtparam=audio=on', and if it exists, comment it out:
#dtparam=audio=on

To get it to work with mpd (see below), you will need to manually add the card 'by name' to the mpd config file

STOP PRESS. As with anything *nix, 'how to get anything working' changes with every software/system release. Apparently (as of mid 2016) to get the pHAT DAC working with Jessie and the Pi zero, "all" you need to do is set "output = hifiberry_dac" in the "/boot/config/settings.ini" (after assigning the I/O pins (Device Overlay), of course). No doubt, by the time you read this, something will have changed again

Using the stereo jack / HDMI audio out

If you have 'redirected' the GPIO pins on a Pi Zero, you will also need to ensure the kernel driver is loaded

Use the command lsmod to check whats loaded :-
$ lsmod
Look for an entry starting "snd-bcm2835". If not seen, add it using the command :-
$ sudo modprobe snd-bcm2835

Testing audio output

To play music tracks, we need the audio sound driver package alsa.

alsa should have come with Raspbian, however, just in case it's got lost :-
$ sudo apt-get install alsa-utils

alsa comes with aplay, a .wav track player. However, to test mp3's from the command line, we need an extra player, mpg321.

$ sudo apt-get install mpg321

An alternative to mpg321 is mplayer, which includes FLAC support :-

sudo apt-get install mplayer

Note that the mp3 player (mpg321) can be used to convert a mp3 file to .wav, however to do this you need the lame codec.

During play back, a .mp3 has to be 'unpacked' and processed by the Pi CPU chip 'on the fly'. This eats into the CPU cycles needed for 'data shuffling' on the Pi's single USB port, which has to be shared between all USB devices, including the Ethernet and WiFi LAN. This can lead to data 'drop outs' and thus interrupted playback, especially if the .mp3 is fetched from your Server/NAS. Playing back from a local folder (on the SDHC card) or processing a .wav track imposes much less overhead, so if your mp3's won't play, copy them to a local folder and/or convert them to .wav first. On average, I get about 20 classical .wav tracks per Gb, so can fit more than 300 on a 16Gb SDHC card (or up to 500 non-classical tracks).

$ sudo apt-get install lame

The amixer cset numid=3 (n) command sets the audio i/o path for alsa, where (n) is 0 for 'auto' (HDMI if a HDMI display is sensed, else GPIO), 1 to force 'GPIO' (pins) and 2 to force HDMI.

To force the Pi to use the GPIO pins :-
amixer cset numid=3 1
To force the Pi to use the HDMI socket :-
amixer cset numid=3 2

OK, so we can play tracks from the command line - for a 'streaming player', see "The MPD / MPC solution", below

Using your old PC speakers

Whilst most current PC speakers use HDMI, older PC speakers had to be 'driven' by 'pre-decoded' digital PCM data streams (typically using 3 'stereo cables' = 6 channels, to get the 5.1).

So you might think it would be easy to find a HDMI to PCM 'extractor' box .. fat chance. The Music Industry HDMI 'DRM' restrictions are designed to prevent exactly that. So almost every HDMI 'audio extractor' you can find will 'down mix' the digital data into 2Ch stereo only. You can find a DRM busting "HDMI Digital Multi-channel Audio Decoder" on eBay (from China, outside the reach of the Music Industry 'enforcers'), however this costs about £30 (which exceeds the VAT-free import duty limit, so will attract 20% VAT + a £10 handling charge, and you will end up paying nearer £50)

The MPD / MPC solution

MPD - Music Player Daemon - is audio player software that simply 'runs' in the background. MPD is controlled (play start, stop, skip etc) by MPC - the Music Player Client.

You can run MPC on the PI = in which case you control it from the command line (manually, or via a script), or you can run MPC on some 'remote' (networked) device - such as a PC or smart phone/Tablet
You do, of course, need an Internet connection - which means (of course) you control the Pi from a serial command terminal (putty) running on your PC
On the Pi Zero, you also need to connect up the Pi audio output i/o pins - the Zero has no 'stereo output' socket (or plug in a USB audio 'dongle', see later)

The mpd.conf contents

user "mpd". When the Pi starts up, there is no 'logged in' user. This means that the start-up files are 'launched' by the operating system itself, i.e. as 'root', with the rights and permissions of the 'super user' (su). This means anything 'left running' after launch will have 'su' access rights, so anyone who can 'control' mpd - and that's everyone in the world running mpc utility - can then 'command' it to do anything they like (including deleting and replacing system files etc)
Adding the line user "mpd" 'switches' mpd from 'su' to the user account 'mpd', which (by default) as no access to anything

Unlike Windows, there is no need to specifically 'create' a user account. It's also quite normal to give the name of the utility to the user account - whilst this may be confusing for the Windows user, in Unix it's quite normal for every utility left running (like a Windows 'service') to have it's own 'user' account

Having restricted mpd with user=mpd, we have to 'change ownership' of the mpd executable files to user mpd (otherwise it won't even launch itself :-) )
Fortunately, all the files needed to run mpd can usually be found in the mpd folder (if not, use the command whereis mpd to find them), so just type the command :-
sudo chown -R mpd /var/lib/mpd
This both changes ownership (allowing mpd to run itself) and sets the files to 'Read only' (so mpd can't modify it's own executables).
playlist_directory is where the play lists are (going to be) stored. Usually this will be a folder on the Pi (you can choose a networked fold, however this will add to your network traffic, especially when mpd starts 'indexing' new tracks)
NOTE that if you set music_directory (below) to 'point' mpd at your Server/NAS music archive, it's going to 'index' the WHOLE ARCHIVE into it's 'play list' (and if you have more than a few dozen tracks it's going to TAKE AGES)
So, when it comes to setting the 'music_directory' for the first time, a 'good idea' would be to 'aim' at a folder containing only a few of your 'favorite' tracks (and add others later)
music_directory sets the location of the music tracks.
You can 'point' "playlist_directory" and "music_directory" at wherever the music tracks are stored (which might be in a folder on a Server/NAS on your LAN), however more usually the files will be 'on the Pi'.
To have mpd access your Server/LAN music tracks directly, set the IP address (or DNS name) of your samba/NAS server (and path to where your music is stored), but remember that mpd will 'index' the music_directory tracks into it's playlist_directory and this will take ages if you have thousands of tracks.
If you have 'mapped' ('mounted' in Unix speak) your music folder using NFS instead, the entry will look something like the following :-
music_directory "/net/servername/path/to/music"

Current versions of mpd can access your home network server/NAS without needing you to install either NFS or SMB/Windows network file sharing on the Pi (see later)

audio_output selects the output hardware
If you have multiple USB devices, the audio dongle might not be on '1,0'. You can use the aplay -l command to list the audio devices found bu the Pi (the Pi GPIO 'stereo jack' internal audio path is "bcm2835").

Starting mpd

To start mpd running from the command line, use the command :-
$ mpd &
The "&" means 'run in the background'.
To restart mpd, after making changes to the mpd.conf file :-
$ sudo service mpd restart
To launch mpd on each startup, add the line "/usr/bin/mpd" to the Pi start-up file (rc.local).
To edit rc.local from the command line :-
cd ..
cd ..
cd etc
sudo nano rc.local
NOTE. Make sure to add the line "/usr/bin/mpd" before the line "exit 0" :-)

Controlling MPD from your PC

Whilst you can use a putty (serial command terminal) to 'manually' control MPD on the Pi, it's a lot easier to use a GUI tool such as the Auremo MPD client interface for Windows.

The version I am using (0.8.0, Feb 2016) not only lets you 'aim' MPD at your music collection, but also allows you to choose from Internet radio sources

Controlling MPD from your smart phone

I don't doubt that you can find more than one MPC utility for smart phones. The one I came across required you create an 'account' so that the Pi mpd player could be shared by multiple individuals within the home. It seemed overly complex to me, so I stuck with my PC.

Testing MPD with an Internet Radio source

You use MPC to tell MPD what to play. This can be done from the command line - for example, to play "Radio Paradise" :-

$ cd (to where MPC was installed)
$ mpc add http://stream-sd.radioparadise.com:8056
To start playing (via the stereo output) :-
$ mpc play 1
MPD should start to play Radio Paradise (and display what it is playing on the Command Terminal window = some people wire the Pi Serial out (TxD) to a LCD display panel to make use of this feature).

Note that a 'battle' between listeners and advertisers has been raging ever since the first commercial radio station took to the air - with advertisers trying to force the listeners to hear their ads and listeners 'tuning out' (to another station) every time an ad. is played. Today the battle is on the Internet - and whilst you can avoid most visual ads whilst browsing (by using 'defence in depth = Firefox with add-ons such as NoScript, FlashBlock, uBlock, Ghostery, Google Disconnect etc etc), it can be a while lot harder to avoid 'radio' ads.

The 'big names' (Pandora, Spotify) offer both a 'free' stream that is 'advertising supported' free stream and a 'premium' (charged for) service without the ads. Plainly they DON'T have too totally different music 'delivery' systems, so 'avoiding' the ads. on the free service is 'possible' (one common solution doesn't actually 'skip' the ads, only mutes them).
Copyright and Royalty issues mean that some services are only available if you have a 'acceptable' IP address (for example, for Pandora you need a US IP address). Proxy servers can usually be used to 'address' this problem :-)
Many smaller 'stations' are promoted as 'ad free' but are not 'DJ chatter free'. You just have to search until you find what you like

Finding Internet radio streaming 'address links' for MPD

Start by visiting the 'radio' web site (e.g. http://www.listenlive.eu/). Choose the page with the 'genre' you like (eg for the Top40: http://www.listenlive.eu/top40.html). Look for the 'Listen Live', 'Listen Now' etc. button and RIGHT CLICK on it. Now look for the web addresses (URL) that ends in ".m3u" and choose the one you want (for example, on Q-Music, you can find a 96kbps stream as "http://icecast4.play.cz/evropa2-64.mp3.m3u") and DOWNLOAD (Save As) the file at that link

The ".m3u" file is a normal file that you can open with Notepad etc.
Inside the file you will find a line like: "http://icecast-qmusic.cdp.triple-it.nl:80/Qmusic_be_live_96.mp3" - and from this you can work out the correct URL for the Pi (in this case, it's "http://icecast-qmusic.cdp.triple-it.nl:80")
Note that not all streaming services link directly to a real 'music track' .mp3 URL (e.g. the Alpha Radio: the ".m3u" contains "http://86.57.151.4:8009/listen.pls", so whilst it's a 'custom' track format (.pls) you can still work out the URL for the Pi :- "http://86.57.151.4:8009")

Portable player (battery options)

A huge range of Li-ion 'USB battery packs' can be found on eBay. Whilst most are intended to 'recharge' your mobile phone (so are stated to output '5v' = which you can assume to mean 'anything from 5.0 to 5.9v') the 'universal' ones and those aimed at extending the operation of your tablet / smart phone typically have better regulated output ('5.3v' is ideal).

You can find a huge range of 2000-2500mAh 'specified' capacity (single 18650 type battery) 'lipstick style' for less than £3 (you can also find some at 99p or less = of course these are just a case which doesn't actually include the battery (but could be dismantled for parts :-) ).
For double the capacity, expect to pay double the price and watch out for the sizes. Whilst most are just 2x 18650 type batteries some are custom type battery 'ultra-thin' style, which are often way too wide/high for any sensible 'project box' - so check your box first :-) Note that some silly sellers give the size of the packaging, not the size of the battery pack :-)
Some come with an 'on/off' switch and whilst may save you the hassle of a separate switch to control the Pi most are the 'multiple press' types that activate a built-in LED light (so less than ideal)
Some sellers make ludicrous 'capacity' claims (1000000 mAh for example) - make your own judgement of capacity based on the size/weight of the item 'to avoid disappointment' :-)
NOTE. Watch out for the output voltage - the 'cheaper' range, usually sold as 'chargers', often have very poor output regulation. So always check the specified output - any not stated (or stated as '5v') can be assumed to be the typical 'Power Bank' specification of "5.0 to 5.5v" !!!

It's quite possible to use one of these as an 'Uninterruptible Power Supply'