The soco module

SoCo (Sonos Controller) is a simple library to control Sonos speakers

soco.discover(timeout=1, include_invisible=False, interface_addr=None)

Discover Sonos zones on the local network.

Return an set of SoCo instances for each zone found. Include invisible zones (bridges and slave zones in stereo pairs if include_invisible is True. Will block for up to timeout seconds, after which return None if no zones found.

Parameters:
  • timeout (int) – block for this many seconds, at most. Default 1
  • include_invisible (bool) – include invisible zones in the return set. Default False
  • interface_addr (str) – Discovery operates by sending UDP multicast datagrams. interface_addr is a string (dotted quad) representation of the network interface address to use as the source of the datagrams (i.e. it is a value for IP_MULTICAST_IF). If None or not specified, the system default interface for UDP multicast messages will be used. This is probably what you want to happen.
Returns:

a set of SoCo instances, one for each zone found, or else None.

Return type:

(set)

Note

There is no easy cross-platform way to find out the addresses of the local machine’s network interfaces. You might try the netifaces module and some code like this:

>>> from netifaces import interfaces, AF_INET, ifaddresses
>>> data = [ifaddresses(i) for i in interfaces()]
>>> [d[AF_INET][0]['addr'] for d in data if d.get(AF_INET)]
['127.0.0.1', '192.168.1.20']

This should provide you with a list of values to try for
interface_addr if you are having trouble finding your Sonos devices
class soco.SoCo(ip_address)

A simple class for controlling a Sonos speaker.

For any given set of arguments to __init__, only one instance of this class may be created. Subsequent attempts to create an instance with the same arguments will return the previously created instance. This means that all SoCo instances created with the same ip address are in fact the same SoCo instance, reflecting the real world position.

Public functions:

play -- Plays the current item.
play_uri -- Plays a track or a music stream by URI.
play_from_queue -- Plays an item in the queue.
pause -- Pause the currently playing track.
stop -- Stop the currently playing track.
seek -- Move the currently playing track a given elapsed time.
next -- Go to the next track.
previous -- Go back to the previous track.
switch_to_line_in -- Switch the speaker's input to line-in.
switch_to_tv -- Switch the playbar speaker's input to TV.
get_current_track_info -- Get information about the currently playing
                          track.
get_speaker_info -- Get information about the Sonos speaker.
partymode -- Put all the speakers in the network in the same group.
join -- Join this speaker to another "master" speaker.
unjoin -- Remove this speaker from a group.
get_queue -- Get information about the queue.
get_artists -- Get artists from the music library
get_album_artists -- Get album artists from the music library
get_albums -- Get albums from the music library
get_genres -- Get genres from the music library
get_composers -- Get composers from the music library
get_tracks -- Get tracks from the music library
get_playlists -- Get playlists from the music library
get_music_library_information -- Get information from the music library
get_current_transport_info -- get speakers playing state
browse_by_idstring -- Browse (get sub-elements) a given type
add_uri_to_queue -- Adds an URI to the queue
add_to_queue -- Add a track to the end of the queue
remove_from_queue -- Remove a track from the queue
clear_queue -- Remove all tracks from queue
get_favorite_radio_shows -- Get favorite radio shows from Sonos'
                            Radio app.
get_favorite_radio_stations -- Get favorite radio stations.
create_sonos_playlist -- Create a new empty Sonos playlist
create_sonos_playlist_from_queue -- Create a new Sonos playlist
                                    from the current queue.
add_item_to_sonos_playlist -- Adds a queueable item to a Sonos'
                               playlist
get_item_album_art_uri -- Get an item's Album Art absolute URI.
search_track -- Search for an artist, artist's albums, or track.
get_albums_for_artist -- Get albums for an artist.
get_tracks_for_album -- Get tracks for an artist's album.
start_library_update -- Trigger an update of the music library.

Properties:

uid -- The speaker's unique identifier
mute -- The speaker's mute status.
volume -- The speaker's volume.
bass -- The speaker's bass EQ.
treble -- The speaker's treble EQ.
loudness -- The status of the speaker's loudness compensation.
cross_fade -- The status of the speaker's crossfade.
status_light -- The state of the Sonos status light.
player_name  -- The speaker's name.
play_mode -- The queue's repeat/shuffle settings.
queue_size -- Get size of queue.
library_updating -- Whether music library update is in progress.
album_artist_display_option -- album artist display option
is_playing_tv -- Is the playbar speaker input from TV?
is_playing_radio -- Is the speaker input from radio?
is_playing_line_in -- Is the speaker input from line-in?

Warning

These properties are not cached and will obtain information over the network, so may take longer than expected to set or return a value. It may be a good idea for you to cache the value in your own code.

add_item_to_sonos_playlist(queueable_item, sonos_playlist)

Adds a queueable item to a Sonos’ playlist

Parameters:
  • queueable_item – the item to add to the Sonos’ playlist
  • sonos_playlist – the Sonos’ playlist to which the item should be added
add_to_queue(*args, **kwargs)

Adds a queueable item to the queue

add_uri_to_queue(*args, **kwargs)

Adds the URI to the queue

Parameters:uri (str) – The URI to be added to the queue
album_artist_display_option

Return the current value of the album artist compilation setting (see http://www.sonos.com/support/help/3.4/en/sonos_user_guide/ Chap07_new/Compilation_albums.htm)

This is a string. Possible values:

  • “WMP” - Use Album Artists
  • “ITUNES” - Use iTunes® Compilations
  • “NONE” - Do not group compilations

To change the current setting, call start_library_update and pass the new setting.

all_groups

Return a set of all the available groups

all_zones

Return a set of all the available zones

bass

The speaker’s bass EQ. An integer between -10 and 10.

browse(ml_item=None, start=0, max_items=100, full_album_art_uri=False, search_term=None, subcategories=None)

Browse (get sub-elements) a music library item

Parameters:
  • ml_item (MusicLibraryItem) – The MusicLibraryItem to browse, if left out or passed None, the items at the base level will be returned
  • start (int) – The starting index of the results
  • max_items (int) – The maximum number of items to return
  • full_album_art_uri (bool) – If the album art URI should include the IP address
  • search_term (str) – A string that will be used to perform a fuzzy search among the search results. If used in combination with subcategories, the fuzzy search will be performed on the subcategory. NOTE: Searching will not work if ml_item is None.
  • subcategories (list) – A list of strings that indicate one or more subcategories to dive into. NOTE: Providing sub categories will not work if ml_item is None.
Returns:

A SearchResult object

Return type:

SearchResult

Raises:

AttributeError: If ml_item has no item_id attribute SoCoUPnPException: With error_code='701' if the item cannot be browsed

browse_by_idstring(search_type, idstring, start=0, max_items=100, full_album_art_uri=False)

Browse (get sub-elements) a given type

Parameters:
  • search_type – The kind of information to retrieve. Can be one of: ‘artists’, ‘album_artists’, ‘albums’, ‘genres’, ‘composers’, ‘tracks’, ‘share’, ‘sonos_playlists’, and ‘playlists’, where playlists are the imported file based playlists from the music library
  • idstring – String ID to search for
  • start – Starting number of returned matches
  • max_items – Maximum number of returned matches. NOTE: The maximum may be restricted by the unit, presumably due to transfer size consideration, so check the returned number against the requested.
  • full_album_art_uri – If the album art URI should include the IP address
Returns:

A dictionary with metadata for the search, with the keys ‘number_returned’, ‘update_id’, ‘total_matches’ and an ‘item_list’ list with the search results.

clear_queue(*args, **kwargs)

Removes all tracks from the queue.

Returns: True if the Sonos speaker cleared the queue.

Raises SoCoException (or a subclass) upon errors.

create_sonos_playlist(title)

Create a new empty Sonos playlist.

Params title:Name of the playlist
Returns:An instance of DidlPlaylistContainer
create_sonos_playlist_from_queue(*args, **kwargs)

Create a new Sonos playlist from the current queue.

Params title:Name of the playlist
Returns:An instance of DidlPlaylistContainer
cross_fade

The speaker’s cross fade state. True if enabled, False otherwise

get_album_artists(*args, **kwargs)

Convenience method for get_music_library_information() with search_type=’album_artists’. For details on remaining arguments refer to the docstring for that method.

get_albums(*args, **kwargs)

Convenience method for get_music_library_information() with search_type=’albums’. For details on remaining arguments refer to the docstring for that method.

get_albums_for_artist(artist, full_album_art_uri=False)

Get albums for an artist.

Parameters:
  • artist (str) – Artist name
  • full_album_art_uri (bool) – If the album art URI should include the IP address
Returns:

A SearchResult object.

Return type:

SearchResult

get_artists(*args, **kwargs)

Convenience method for get_music_library_information() with search_type=’artists’. For details on remaining arguments refer to the docstring for that method.

get_composers(*args, **kwargs)

Convenience method for get_music_library_information() with search_type=’composers’. For details on remaining arguments refer to the docstring for that method.

get_current_track_info()

Get information about the currently playing track.

Returns: A dictionary containing the following information about the currently playing track: playlist_position, duration, title, artist, album, position and a link to the album art.

If we’re unable to return data for a field, we’ll return an empty string. This can happen for all kinds of reasons so be sure to check values. For example, a track may not have complete metadata and be missing an album name. In this case track[‘album’] will be an empty string.

get_current_transport_info()

Get the current playback state

Returns: A dictionary containing the following information about the speakers playing state current_transport_state (PLAYING, PAUSED_PLAYBACK, STOPPED), current_trasnport_status (OK, ?), current_speed(1,?)

This allows us to know if speaker is playing or not. Don’t know other states of CurrentTransportStatus and CurrentSpeed.

get_favorite_radio_shows(start=0, max_items=100)

Get favorite radio shows from Sonos’ Radio app.

Returns: A list containing the total number of favorites, the number of favorites returned, and the actual list of favorite radio shows, represented as a dictionary with title and uri keys.

Depending on what you’re building, you’ll want to check to see if the total number of favorites is greater than the amount you requested (max_items), if it is, use start to page through and get the entire list of favorites.

get_favorite_radio_stations(start=0, max_items=100)

Get favorite radio stations from Sonos’ Radio app.

Returns: A list containing the total number of favorites, the number of favorites returned, and the actual list of favorite radio stations, represented as a dictionary with title and uri keys.

Depending on what you’re building, you’ll want to check to see if the total number of favorites is greater than the amount you requested (max_items), if it is, use start to page through and get the entire list of favorites.

get_genres(*args, **kwargs)

Convenience method for get_music_library_information() with search_type=’genres’. For details on remaining arguments refer to the docstring for that method.

get_item_album_art_uri(item)

Get an item’s Album Art absolute URI.

get_music_library_information(search_type, start=0, max_items=100, full_album_art_uri=False, search_term=None, subcategories=None, complete_result=False)

Retrieve music information objects from the music library

This method is the main method to get music information items, like e.g. tracks, albums etc., from the music library with. It can be used in a few different ways:

The search_term argument performs a fuzzy search on that string in the results, so e.g calling:

get_music_library_items('artist', search_term='Metallica')

will perform a fuzzy search for the term ‘Metallica’ among all the artists.

Using the subcategories argument, will jump directly into that subcategory of the search and return results from there. So. e.g knowing that among the artist is one called ‘Metallica’, calling:

get_music_library_items('artist', subcategories=['Metallica'])

will jump directly into the ‘Metallica’ sub category and return the albums associated with Metallica and:

get_music_library_items('artist', subcategories=['Metallica',
                                                 'Black'])

will return the tracks of the album ‘Black’ by the artist ‘Metallica’. The order of sub category types is: Genres->Artists->Albums->Tracks. It is also possible to combine the two, to perform a fuzzy search in a sub category.

The start, max_items and complete_result arguments all has to do with paging of the results. Per default, the searches are always paged, because there is a limit to how many items we can get at a time. This paging is exposed to the user with the start and max_items arguments. So calling:

get_music_library_items('artists', start=0, max_items=100)
get_music_library_items('artists', start=100, max_items=100)

will get the first and next 100 items, respectively. It is also possible to ask for all the elements at once:

get_music_library_items('artists', complete_result=True)

This will perform the paging internally and simply return all the items.

Parameters:
  • search_type – The kind of information to retrieve. Can be one of: ‘artists’, ‘album_artists’, ‘albums’, ‘genres’, ‘composers’, ‘tracks’, ‘share’, ‘sonos_playlists’, and ‘playlists’, where playlists are the imported file based playlists from the music library
  • start – Starting number of returned matches (zero based).
  • max_items – Maximum number of returned matches. NOTE: The maximum may be restricted by the unit, presumably due to transfer size consideration, so check the returned number against the requested.
  • full_album_art_uri – If the album art URI should include the IP address
  • search_term – A string that will be used to perform a fuzzy search among the search results. If used in combination with subcategories, the fuzzy search will be performed in the subcategory
  • subcategories – A list of strings that indicate one or more subcategories to dive into
  • complete_result – Will disable paging (ignore start and max_items) and return all results for the search. WARNING! Getting e.g. all the tracks in a large collection might take some time.
Returns:

A SearchResult object

Raises:

SoCoException upon errors

NOTE: The playlists that are returned with the ‘playlists’ search, are the playlists imported from (files in) the music library, they are not the Sonos playlists.

The information about the which searches can be performed and the form of the query has been gathered from the Janos project: http://sourceforge.net/projects/janos/ Props to the authors of that project.

get_playlists(*args, **kwargs)

Convenience method for get_music_library_information() with search_type=’playlists’. For details on remaining arguments refer to the docstring for that method.

NOTE: The playlists that are referred to here are the playlist (files) imported from the music library, they are not the Sonos playlists.

get_queue(start=0, max_items=100, full_album_art_uri=False)

Get information about the queue

Parameters:
  • start – Starting number of returned matches
  • max_items – Maximum number of returned matches
  • full_album_art_uri – If the album art URI should include the IP address
Returns:

A Queue object

This method is heavly based on Sam Soffes (aka soffes) ruby implementation

get_sonos_playlists(*args, **kwargs)

Convenience method for: get_music_library_information(‘sonos_playlists’) Refer to the docstring for that method

get_speaker_info(refresh=False)

Get information about the Sonos speaker.

Arguments: refresh – Refresh the speaker info cache.

Returns: Information about the Sonos speaker, such as the UID, MAC Address, and Zone Name.

get_tracks(*args, **kwargs)

Convenience method for get_music_library_information() with search_type=’tracks’. For details on remaining arguments refer to the docstring for that method.

get_tracks_for_album(artist, album, full_album_art_uri=False)

Get tracks for an artist’s album.

Parameters:
  • artist (str) – Artist name
  • album (str) – Album name
  • full_album_art_uri (bool) – If the album art URI should include the IP address
Returns:

A SearchResult object.

Return type:

SearchResult

group

The Zone Group of which this device is a member.

group will be None if this zone is a slave in a stereo pair.

is_bridge

Is this zone a bridge?

is_coordinator

Return True if this zone is a group coordinator, otherwise False.

return True or False

is_playing_line_in

Is the speaker playing line-in?

return True or False

is_playing_radio

Is the speaker playing radio?

return True or False

is_playing_tv

Is the playbar speaker input from TV?

return True or False

is_visible

Is this zone visible? A zone might be invisible if, for example it is a bridge, or the slave part of stereo pair.

return True or False

join(master)

Join this speaker to another “master” speaker.

Note

The signature of this method has changed in 0.8. It now requires a SoCo instance to be passed as master, not an IP address

library_updating

True if the music library is in the process of being updated

Returns:True if the music library is in the process of being updated
Return type:bool
loudness

The Sonos speaker’s loudness compensation. True if on, otherwise False.

Loudness is a complicated topic. You can find a nice summary about this feature here: http://forums.sonos.com/showthread.php?p=4698#post4698

mute

The speaker’s mute state. True if muted, False otherwise

next(*args, **kwargs)

Go to the next track.

Returns: True if the Sonos speaker successfully skipped to the next track.

Raises SoCoException (or a subclass) upon errors.

Keep in mind that next() can return errors for a variety of reasons. For example, if the Sonos is streaming Pandora and you call next() several times in quick succession an error code will likely be returned (since Pandora has limits on how many songs can be skipped).

partymode()

Put all the speakers in the network in the same group, a.k.a Party Mode.

This blog shows the initial research responsible for this: http://blog.travelmarx.com/2010/06/exploring-sonos-via-upnp.html

The trick seems to be (only tested on a two-speaker setup) to tell each speaker which to join. There’s probably a bit more to it if multiple groups have been defined.

pause(*args, **kwargs)

Pause the currently playing track.

Returns: True if the Sonos speaker successfully paused the track.

Raises SoCoException (or a subclass) upon errors.

play(*args, **kwargs)

Play the currently selected track.

Returns: True if the Sonos speaker successfully started playing the track.

Raises SoCoException (or a subclass) upon errors.

play_from_queue(*args, **kwargs)

Play a track from the queue by index. The index number is required as an argument, where the first index is 0.

index: the index of the track to play; first item in the queue is 0 start: If the item that has been set should start playing

Returns: True if the Sonos speaker successfully started playing the track. False if the track did not start (this may be because it was not requested to start because “start=False”)

Raises SoCoException (or a subclass) upon errors.

play_mode

The queue’s play mode. Case-insensitive options are

NORMAL – Turns off shuffle and repeat. REPEAT_ALL – Turns on repeat and turns off shuffle. SHUFFLE – Turns on shuffle and repeat. (It’s strange, I know.) SHUFFLE_NOREPEAT – Turns on shuffle and turns off repeat.

play_uri(*args, **kwargs)

Play a given stream. Pauses the queue. If there is no metadata passed in and there is a title set then a metadata object will be created. This is often the case if you have a custom stream, it will need at least the title in the metadata in order to play.

Arguments: uri – URI of a stream to be played. meta – The track metadata to show in the player, DIDL format. title – The track title to show in the player start – If the URI that has been set should start playing

Returns: True if the Sonos speaker successfully started playing the track. False if the track did not start (this may be because it was not requested to start because “start=False”)

Raises SoCoException (or a subclass) upon errors.

player_name

The speaker’s name. A string.

previous(*args, **kwargs)

Go back to the previously played track.

Returns: True if the Sonos speaker successfully went to the previous track.

Raises SoCoException (or a subclass) upon errors.

Keep in mind that previous() can return errors for a variety of reasons. For example, previous() will return an error code (error code 701) if the Sonos is streaming Pandora since you can’t go back on tracks.

queue_size

Get size of queue

remove_from_queue(*args, **kwargs)

Remove a track from the queue by index. The index number is required as an argument, where the first index is 0.

index: the index of the track to remove; first item in the queue is 0

Returns:True if the Sonos speaker successfully removed the track

Raises SoCoException (or a subclass) upon errors.

search_track(artist, album=None, track=None, full_album_art_uri=False)

Search for an artist, artist’s albums, or specific track.

Parameters:
  • artist (str) – Artist name
  • album (str) – Album name
  • track (str) – Track name
  • full_album_art_uri (bool) – If the album art URI should include the IP address
Returns:

A SearchResult object.

Return type:

SearchResult

seek(*args, **kwargs)

Seeks to a given timestamp in the current track, specified in the format of HH:MM:SS or H:MM:SS.

Returns: True if the Sonos speaker successfully seeked to the timecode.

Raises SoCoException (or a subclass) upon errors.

start_library_update(album_artist_display_option=u'')

Start an update of the music library.

If specified, album_artist_display_option changes the album artist compilation setting (see also album_artist_display_option).

status_light

The white Sonos status light between the mute button and the volume up button on the speaker. True if on, otherwise False.

stop(*args, **kwargs)

Stop the currently playing track.

Returns: True if the Sonos speaker successfully stopped the playing track.

Raises SoCoException (or a subclass) upon errors.

switch_to_line_in()

Switch the speaker’s input to line-in.

Returns: True if the Sonos speaker successfully switched to line-in.

If an error occurs, we’ll attempt to parse the error and return a UPnP error code. If that fails, the raw response sent back from the Sonos speaker will be returned.

Raises SoCoException (or a subclass) upon errors.

switch_to_tv()

Switch the playbar speaker’s input to TV.

Returns: True if the Sonos speaker successfully switched to TV.

If an error occurs, we’ll attempt to parse the error and return a UPnP error code. If that fails, the raw response sent back from the Sonos speaker will be returned.

Raises SoCoException (or a subclass) upon errors.

treble

The speaker’s treble EQ. An integer between -10 and 10.

uid

A unique identifier. Looks like – RINCON_000XXXXXXXXXX1400

unjoin()

Remove this speaker from a group.

Seems to work ok even if you remove what was previously the group master from it’s own group. If the speaker was not in a group also returns ok.

Returns: True if this speaker has left the group.

Raises SoCoException (or a subclass) upon errors.

visible_zones

Return an set of all visible zones

volume

The speaker’s volume. An integer between 0 and 100.

exception soco.SoCoException

base exception raised by SoCo, containing the UPnP error code

exception soco.UnknownSoCoException

raised if reason of the error can not be extracted

The exception object will contain the raw response sent back from the speaker