Spotify On Sonos HOWTO

The US is home to a great number of on-line music services, such as Napster, Pandora and Rhapsody. The trouble is that, due to copyright and royalty issues, access is currently restricted to users in the US.

Over here in Europe, things are fragmented. Last.fm is a popular service that offers listeners the streamed equivalent of a personalised radio station, but outside of the US, it’s available only in the UK and Germany.

The only pan-European music service I know of is France’s Deezer. The trouble is, Deezer’s not very good in its present state. It doesn’t have a large number of songs, so selecting a SmartRadio station, which allows one to listen to a particular artist and others deemed similar, very quickly results in repetition, if, indeed, your chosen artist can be found at all.

Over on the the forums of the multi-room Sonos sound system, the most frequently requested integration of a new music service comes from users from all over Europe who’d like to see their Sonos system able to access Spotify, a high-quality music service based in the Swedish capital.

Sonos is obviously aware of the demand, but thus far hasn’t granted the request. There are a number of reasons why Sonos integration of Spotify is problematic.

Firstly, at the technical level, Spotify has no API to speak of. The service requires the user to download an application, which then runs on their Windows or Mac machine. For Sonos to make this work on their system, they wouldn’t simply be able to perform a few HTTP GETs and make the existing controller software stream from Spotify. They (or more likely Spotify) would have to write a small application to do so. Integrating this with the existing system could prove challenging, but I’m sure it could be done.

Secondly, Spotify is currently in beta as an invitation-only service. This is to control the number of new users taxing the servers and ensure the quality of the service. Periodically, though, eager users in the UK can sign up without an invitation as Spotify decides to expand its user base.

Thirdly, Spotify is only available in a handful of European countries. Sadly, the one I live in isn’t amongst them.

The above problems notwithstanding, I’m going to demonstrate how, with a little bit of determination, it’s possible to listen to Spotify anywhere in the world on any device that supports streaming.

Prerequisites for this exercise are a computer running a fairly recent distribution of Linux. In particular, it’s going to need to be running the revolutionary PulseAudio sound server. This computer is going to act as middleware between Spotify and the device you listen on. Of course, if the machine in question is also your desktop, you can also use it as an endpoint to listen to Spotify.

First of all, you need to sign up as a user of Spotify. Since UK users sometimes don’t need an invitation and, in any case, you need to appear to be registering from a serviced country, we’re going to use a regional proxy, such as lessonfly.com or DaveProxy to do this. You can find many others with Google, so try a few different ones if you think you’re running into a technical problem.

Paste the URL https://www.spotify.com/en/get-started/ into the box and you will be transported to Spotify’s site as if you were in the UK. Once there, sign up for service as a new user.

If you can’t get past a screen informing you that Spotify is currently an invitation-only service, you’re not going to get in by just knocking on the door. In that case, you’re going to need to get yourself invited. If you don’t know anyone who has Spotify, ask around in audiophile and torrent forums. With some effort, you should be able to find someone who can send you an invitation.

Complete your registration with a valid UK address. including with a British postcode. The Royal Mail operate a rather nice postcode finder. Just plug in an address somewhere in the UK and it’ll spit out a postcode you can use.

Once you’ve done that, download the Spotify application for Windows. Spotify doesn’t provide a native Linux application, so we’re going to have to run the Windows binary on our computer.

Next, install the software on your Linux machine by running wine Spotify Installer.exe in a terminal window. It should install flawlessly with a fairly recent version of WINE (a Linux implementation of the Windows API). Once it’s installed, configure it with your Spotify user name and password, plus any additional settings you’d like to add, such as the user name and password of your Last.fm account, so that anything you listen to can be scrobbled.

If you can and you haven’t already done so, configure WINE at this point to use the PulseAudio sound server. It will make your life easier in the long run, as Spotify and any other Windows applications you use that access your computer’s sound card will play nicely with any native Linux applications that do the same. You can configure WINE to use PulseAudio by running winecfg and going to the Audio tab.

Depending on your distribution, you may first need to patch WINE to add PulseAudio support. How to do this is beyond the scope of this HOWTO. but if you have Fedora 12, the patch has already been integrated in the distribution binary.

You should now have a working Spotify client. Regardless of where you live, the client will function normally at this point, but if you’re not within the service area, it will work for only 14 days and you’ll start to see warnings to that effect after a few days.

This is because Spotify’s free service entitles users to travel outside the coverage area for up to two weeks without affecting their access. If you want to travel for longer, you have to sign up for Spotify’s premium service at £9.99 per month.

If all you want to do is listen to Spotify on your Linux desktop, you’re pretty much ready at this point. Consider signing up for Spotify’s premium service, because it will remove both the advertising and the geographical restrictions. Because you can pay with PayPal, no-one need be any the wiser that you don’t actually live in the UK. You can simply appear to be permanently travelling.

I wanted to listen to Spotify on my Sonos system, however. Although my natural habitat is at my computer, I’m frequently also to be found in the kitchen, dining-room, media room and bathroom. I therefore wanted to be able to listen to Spotify anywhere in the house.

Here’s how to get there. The same solution works for streaming Spotify to any number of other networked devices in (or even outside of) your home, including computers, phones, etc.

First of all, we’re going to capture the raw sound that the Spotify application sends to your PC’s sound card. We do this using PulseAudio’s parec utility, which is actually just a symlink to pacat, a program for recording and playing back raw audio streams.

Next, we take the flowing stream and convert it to signed 16 bit little-endian WAV format data. This stage makes the sound much more palatable to other programs, because despite the name, this is actually a very common format for audio data interchange.

Finally, we take the resulting stream of WAV format sound and make it accessible to the Sonos. This requires transcoding it a format that is digestible by the Sonos, such as the commonly used MP3 format.

That alone won’t be enough, however. We still need a way for the Sonos to actually get to the data we’re producing. To achieve that, we’ll take our newly re-encoded data and stream it over HTTP from the Linux computer. That way, any device that can play an MP3 stream can connect to the computer and grab the data.

Putting this together, we get the following script:

#!/bin/bash
 
type pactl &>/dev/null ||
  { echo pactl unavailable. Install pulseaudio-utils.; exit 1; }
 
type cvlc &>/dev/null ||
  { echo cvlc unavailable. Install vlc-core.; exit 1; }
 
# Change this to 'true' if you have Spotify's premium service.
#
SPOTIFY_PREMIUM=false
 
# The computer's first Ethernet interface.
#
IF=eth0
IPADDR=$( ip addr show dev $IF | awk '/^ *inet / { print $2; exit }' | sed 's#/.*##' )
PORT=8080
DEVICE=$( pactl list | grep -A 2 'Source #' | sed -ne 's/^.*Name: \(.\+\.monitor\)$/\1/p' | grep -iv headset | head -n 1 )
 
if [ "$SPOTIFY_PREMIUM" = 'true' ]; then
  BITRATE=320
else
  BITRATE=160
fi
 
parec --device=$DEVICE --format=s16le --rate=44100 --channels=2 |
  sox --type raw -s2L --rate 44100 --channels 2 - --type wav - 2>/dev/null |
    cvlc -q - --sout "#transcode{acodec=mp3,ab=$BITRATE}:standard{access=http,mux=raw,dst=$IPADDR:$PORT}" 2>/dev/null

Copy and paste the above script into a file, make it executable and run it. If you don’t have SoX or VLC installed, install them now.

There’s a chance the above script won’t work for you. It’s not very sophisticated and doesn’t do a lot of error-checking. If you have multiple Ethernet interfaces in your computer and it’s not connected to the network via the first one, you’ll need to modify the script.

Similarly, if you have multiple sound cards in your computer, the above script may try to use a different one than the one to which the Spotify application is sending its output. Again, you’ll have to modify the script to make it work.

For the majority of users, however, the above script will just work.

Spotify streams its free service in Ogg Vorbis Q5 format, which is good for a nominal 160 kbps of data. Premium users get Ogg Vorbis Q9, which is nominally 320 kbps, although the Ogg Vorbis codec is so good that you’ll be hard-pressed to tell the difference. Make the appropriate modification to the script if you’ve signed up for premium service and want the higher bit rate.

Assuming the script is working, you should now be able to connect to your computer using your Sonos (or similar device) and listen to whatever Spotify is playing at the time. If your computer’s IP address were. for example, 192.168.1.12, you would add a radio station to the Sonos, giving it the following URL: http://192.168.1.12:8080/

At this point, music should start to emanate from the speakers connected to your Sonos system. If it doesn’t, make sure that the Spotify application is actually playing something and that the above script is functioning correctly. Troubleshooting the script may prove tricky for you, but it includes enough variables that it, too, is unfortunately beyond the scope of this posting.

If you’ve got this far, well done. You’re listening to Spotify in a location that isn’t officially served, using a client application that was written for use on a different operating system, transcoding its output and retransmitting it to an unsupported device!

Obviously, the integration with the Sonos is poor. You can start or stop listening to the stream from your computer, but your computer will go on streaming after you have stopped listening. This only really matters if you’re scrobbling data to Last.fm, because you will scrobble tracks you didn’t actually listen to.

Similarly, you can’t control or even view the details of what you listen to from the Sonos. To select new music or see what’s currently playing, you’ll have to visit the computer and use the Spotify application.

Still, some integration is better than no integration at all, I think.

There’s also the problem of service ending after 14 days if you’re not in the service area. Whilst you can sign up for premium service to escape this restriction — and I encourage you to do so — there’s another solution.

Spotify’s preferences dialogue allows you to specify a proxy server to use to access the service. You can choose between a number of different flavours of proxy, one of which is SOCKS5. If the proxy you fill in here happens to be located in Spotify’s service area, it will appear to Spotify as if you, yourself, are also within that area.

Here again, Google is your friend.

Freely available open proxies of this kind tend to come and go with the weather, but you actually only briefly need one once every two weeks to reset the clock on your travelling. After logging in via a proxy, you can reselect no proxy and enjoy another two weeks of listening on the road, as it were.

If you can’t locate a SOCKS5 proxy, use an HTTPS proxy instead. That will work equally well and these are much more common than their SOCKS5 cousins.

There are some stability issues with this set-up. Occasionally, the script will hang and the Sonos will be unable to (re-)connect to the stream. In that case, you’ll need to restart the script. Alternatively, you could write a watchdog to monitor the script and restart it as necessary.

Also, you’ll experience the occasional audio drop-out, particularly if you’re streaming Spotify via a SOCKS5 or HTTPS proxy in another country. There’s not much you can do about this, other than sign up for premium service so that you have unlimited access to a direct stream.

Finally, there’s some minor danger to your privacy to be aware of with this configuration. You’ll recall that all data going to your computer’s sound card is being captured and streamed. That means that if you were to receive an incoming call via, say, Skype, and that program is configured to send its output to the same sound card as Spotify, anyone in your house can now tune into the conversation via the Sonos. If this is a worry to you, use PulseAudio to send only the output of Skype to a USB headset.

Getting this operational should not be regarded as a guarantee of continuity of service. Spotify is at liberty to block your account at any time, even as a paying subscriber, because you’re circumnavigating their geographical restrictions. They’re under absolutely no obligation to you.

Nevertheless, if you can get this working and manage to stay under Spotify’s radar, I hope it’s of some use to you. If nothing else, it’s a nice demonstration of the combined power of Linux, the Internet and geek willpower.

One thought on “Spotify On Sonos HOWTO

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>