soco.core module

The core module contains the SoCo class that implements the main entry to the SoCo functionality

soco.core.only_on_master(function)[source]

Decorator that raises SoCoSlaveException on master call on slave.

class soco.core.SoCo(ip_address)[source]

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.

Basic Methods

play_from_queue(index[, start]) Play a track from the queue by index.
play() Play the currently selected track.
play_uri([uri, meta, title, start, force_radio]) Play a URI.
pause() Pause the currently playing track.
stop() Stop the currently playing track.
seek(timestamp) Seek to a given timestamp in the current track, specified in the format of HH:MM:SS or H:MM:SS.
next() Go to the next track.
previous() Go back to the previously played track.
mute bool – The speaker’s mute state.
volume int – The speaker’s volume.
play_mode str – The queue’s play mode.
cross_fade bool – The speaker’s cross fade state.
ramp_to_volume(volume[, ramp_type]) Smoothly change the volume.
get_current_track_info() Get information about the currently playing track.
get_speaker_info([refresh, timeout]) Get information about the Sonos speaker.
get_current_transport_info() Get the current playback state.

Queue Management

get_queue([start, max_items, full_album_art_uri]) Get information about the queue.
queue_size int – Size of the queue.
add_to_queue(queueable_item[, position, as_next]) Add a queueable item to the queue.
add_uri_to_queue(uri[, position, as_next]) Add the URI to the queue.
add_multiple_to_queue(items[, container]) Add a sequence of items to the queue.
remove_from_queue(index) Remove a track from the queue by index.
clear_queue() Remove all tracks from the queue.

Group Management

group soco.groups.ZoneGroup – The Zone Group of which this device
partymode() Put all the speakers in the network in the same group, a.k.a Party Mode.
join(master) Join this speaker to another “master” speaker.
unjoin() Remove this speaker from a group.
all_groups set of soco.groups.ZoneGroup – All available groups.
all_zones set of soco.groups.ZoneGroup – All available zones.
visible_zones set of soco.groups.ZoneGroup – All visible zones.

Player Identity and Settings

player_name str – The speaker’s name.
uid str – A unique identifier.
household_id str – A unique identifier for all players in a household.
is_visible bool – Is this zone visible?
is_bridge bool – Is this zone a bridge?
is_coordinator bool – Is this zone a group coordinator?
bass int – The speaker’s bass EQ.
treble int – The speaker’s treble EQ.
loudness bool – The Sonos speaker’s loudness compensation.
night_mode bool – The speaker’s night mode.
dialog_mode bool – Get the Sonos speaker’s dialog mode.
status_light bool – The white Sonos status light between the mute button and the

Playlists and Favorites

get_sonos_playlists(*args, **kwargs) Convenience method for get_music_library_information('sonos_playlists').
create_sonos_playlist(title) Create a new empty Sonos playlist.
create_sonos_playlist_from_queue(title) Create a new Sonos playlist from the current queue.
remove_sonos_playlist(sonos_playlist) Remove a Sonos playlist.
add_item_to_sonos_playlist(queueable_item, …) Adds a queueable item to a Sonos’ playlist.
reorder_sonos_playlist(sonos_playlist, …) Reorder and/or Remove tracks in a Sonos playlist.
clear_sonos_playlist(sonos_playlist[, update_id]) Clear all tracks from a Sonos playlist.
move_in_sonos_playlist(sonos_playlist, …) Move a track to a new position within a Sonos Playlist.
remove_from_sonos_playlist(sonos_playlist, track) Remove a track from a Sonos Playlist.
get_sonos_playlist_by_attr(attr_name, match) Return the first Sonos Playlist DidlPlaylistContainer that matches the attribute specified.
get_favorite_radio_shows([start, max_items]) Get favorite radio shows from Sonos’ Radio app.
get_favorite_radio_stations([start, max_items]) Get favorite radio stations from Sonos’ Radio app.
get_sonos_favorites([start, max_items]) Get Sonos favorites.

Miscellaneous

switch_to_line_in([source]) Switch the speaker’s input to line-in.
is_playing_radio bool – Is the speaker playing radio?
is_playing_line_in bool – Is the speaker playing line-in?
is_playing_tv bool – Is the playbar speaker input from TV?
switch_to_tv() Switch the playbar speaker’s input to TV.
set_sleep_timer(sleep_time_seconds) Sets the sleep timer.
get_sleep_timer() Retrieves remaining sleep time, if any

Warning

Properties on this object are not generally cached and may 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.

Note

Since all methods/properties on this object will result in an UPnP request, they might result in an exception without it being mentioned in the Raises section.

In most cases, the exception will be a soco.exceptions.SoCoUPnPException (if the player returns an UPnP error code), but in special cases it might also be another soco.exceptions.SoCoException or even a requests exception.

ip_address = None

The speaker’s ip address

player_name

str – The speaker’s name.

uid

str – A unique identifier.

Looks like: 'RINCON_000XXXXXXXXXX1400'

household_id

str – A unique identifier for all players in a household.

Looks like: 'Sonos_asahHKgjgJGjgjGjggjJgjJG34'

is_visible

bool – Is this zone visible?

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

is_bridge

bool – Is this zone a bridge?

is_coordinator

bool – Is this zone a group coordinator?

play_mode

str – 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.
cross_fade

bool – The speaker’s cross fade state.

True if enabled, False otherwise

ramp_to_volume(volume, ramp_type='SLEEP_TIMER_RAMP_TYPE')[source]

Smoothly change the volume.

There are three ramp types available:

  • 'SLEEP_TIMER_RAMP_TYPE' (default): Linear ramp from the current volume up or down to the new volume. The ramp rate is 1.25 steps per second. For example: To change from volume 50 to volume 30 would take 16 seconds.
  • 'ALARM_RAMP_TYPE': Resets the volume to zero, waits for about 30 seconds, and then ramps the volume up to the desired value at a rate of 2.5 steps per second. For example: Volume 30 would take 12 seconds for the ramp up (not considering the wait time).
  • 'AUTOPLAY_RAMP_TYPE': Resets the volume to zero and then quickly ramps up at a rate of 50 steps per second. For example: Volume 30 will take only 0.6 seconds.

The ramp rate is selected by Sonos based on the chosen ramp type and the resulting transition time returned. This method is non blocking and has no network overhead once sent.

Parameters:
  • volume (int) – The new volume.
  • ramp_type (str, optional) – The desired ramp type, as described above.
Returns:

The ramp time in seconds, rounded down. Note that this does not include the wait time.

Return type:

int

play_from_queue(index, start=True)[source]

Play a track from the queue by index.

The index number is required as an argument, where the first index is 0.

Parameters:
  • index (int) – 0-based index of the track to play
  • start (bool) – If the item that has been set should start playing
play()[source]

Play the currently selected track.

play_uri(uri='', meta='', title='', start=True, force_radio=False)[source]

Play a URI.

Playing a URI will replace what was playing with the stream given by the URI. For some streams at least a title is required as metadata. This can be provided using the meta argument or the title argument. If the title argument is provided minimal metadata will be generated. If meta argument is provided the title argument is ignored.

Parameters:
  • uri (str) – URI of the stream to be played.
  • meta (str) – The metadata to show in the player, DIDL format.
  • title (str) – The title to show in the player (if no meta).
  • start (bool) – If the URI that has been set should start playing.
  • force_radio (bool) – forces a uri to play as a radio stream.

On a Sonos controller music is shown with one of the following display formats and controls:

  • Radio format: Shows the name of the radio station and other available data. No seek, next, previous, or voting capability. Examples: TuneIn, radioPup
  • Smart Radio: Shows track name, artist, and album. Limited seek, next and sometimes voting capability depending on the Music Service. Examples: Amazon Prime Stations, Pandora Radio Stations.
  • Track format: Shows track name, artist, and album the same as when playing from a queue. Full seek, next and previous capabilities. Examples: Spotify, Napster, Rhapsody.

How it is displayed is determined by the URI prefix: x-sonosapi-stream:, x-sonosapi-radio:, x-rincon-mp3radio:, hls-radio: default to radio or smart radio format depending on the stream. Others default to track format: x-file-cifs:, aac:, http:, https:, x-sonos-spotify: (used by Spotify), x-sonosapi-hls-static: (Amazon Prime), x-sonos-http: (Google Play & Napster).

Some URIs that default to track format could be radio streams, typically http:, https: or aac:. To force display and controls to Radio format set force_radio=True

Note

Other URI prefixes exist but are less common. If you have information on these please add to this doc string.

Note

A change in Sonos® (as of at least version 6.4.2) means that the devices no longer accepts ordinary http: and https: URIs for radio stations. This method has the option to replaces these prefixes with the one that Sonos® expects: x-rincon-mp3radio: by using the “force_radio=True” parameter. A few streams may fail if not forced to to Radio format.

pause()[source]

Pause the currently playing track.

stop()[source]

Stop the currently playing track.

seek(timestamp)[source]

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

Raises:ValueError – if the given timestamp is invalid.
next()[source]

Go to the next track.

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).

previous()[source]

Go back to the previously played track.

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.

mute

bool – The speaker’s mute state.

True if muted, False otherwise.

volume

int – The speaker’s volume.

An integer between 0 and 100.

bass

int – The speaker’s bass EQ.

An integer between -10 and 10.

treble

int – The speaker’s treble EQ.

An integer between -10 and 10.

loudness

bool – The Sonos speaker’s loudness compensation.

True if on, False otherwise.

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

night_mode

bool – The speaker’s night mode.

True if on, False if off, None if not supported.

dialog_mode

bool – Get the Sonos speaker’s dialog mode.

True if on, False if off, None if not supported.

all_groups

set of soco.groups.ZoneGroup – All available groups.

group

soco.groups.ZoneGroup – The Zone Group of which this device is a member.

None if this zone is a slave in a stereo pair.

all_zones

set of soco.groups.ZoneGroup – All available zones.

visible_zones

set of soco.groups.ZoneGroup – All visible zones.

partymode()[source]

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.

join(master)[source]

Join this speaker to another “master” speaker.

unjoin()[source]

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.

switch_to_line_in(source=None)[source]

Switch the speaker’s input to line-in.

Parameters:source (SoCo) – The speaker whose line-in should be played. Default is line-in from the speaker itself.
is_playing_radio

bool – Is the speaker playing radio?

is_playing_line_in

bool – Is the speaker playing line-in?

is_playing_tv

bool – Is the playbar speaker input from TV?

switch_to_tv()[source]

Switch the playbar speaker’s input to TV.

status_light

bool – The white Sonos status light between the mute button and the volume up button on the speaker.

True if on, otherwise False.

get_current_track_info()[source]

Get information about the currently playing track.

Returns:A dictionary containing information about the currently playing track: playlist_position, duration, title, artist, album, position and an album_art link.
Return type:dict

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.

Note

Calling this method on a slave in a group will not return the track the group is playing, but the last track this speaker was playing.

get_speaker_info(refresh=False, timeout=None)[source]

Get information about the Sonos speaker.

Parameters:
  • refresh (bool) – Refresh the speaker info cache.
  • timeout – How long to wait for the server to send data before giving up, as a float, or a (connect timeout, read timeout) tuple e.g. (3, 5). Default is no timeout.
Returns:

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

Return type:

dict

get_current_transport_info()[source]

Get the current playback state.

Returns:The following information about the speaker’s playing state:
  • current_transport_state (PLAYING, TRANSITIONING, PAUSED_PLAYBACK, STOPPED)
  • current_transport_status (OK, ?)
  • current_speed(1, ?)
Return type:dict

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

get_queue(start=0, max_items=100, full_album_art_uri=False)[source]

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

queue_size

int – Size of the queue.

get_sonos_playlists(*args, **kwargs)[source]

Convenience method for get_music_library_information('sonos_playlists').

Refer to the docstring for that method

add_uri_to_queue(uri, position=0, as_next=False)[source]

Add the URI to the queue.

For arguments and return value see add_to_queue.

add_to_queue(queueable_item, position=0, as_next=False)[source]

Add a queueable item to the queue.

Parameters:
  • queueable_item (DidlObject or MusicServiceItem) – The item to be added to the queue
  • position (int) – The index (1-based) at which the URI should be added. Default is 0 (add URI at the end of the queue).
  • as_next (bool) – Whether this URI should be played as the next track in shuffle mode. This only works if play_mode=SHUFFLE.
Returns:

The index of the new item in the queue.

Return type:

int

add_multiple_to_queue(items, container=None)[source]

Add a sequence of items to the queue.

Parameters:
  • items (list) – A sequence of items to the be added to the queue
  • container (DidlObject, optional) – A container object which includes the items.
remove_from_queue(index)[source]

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

Parameters:index (int) – The (0-based) index of the track to remove
clear_queue()[source]

Remove all tracks from the queue.

get_favorite_radio_shows(start=0, max_items=100)[source]

Get favorite radio shows from Sonos’ Radio app.

Returns:
dict: A dictionary 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.

Deprecated since version 0.13: Will be removed in version 0.15. Use soco.music_library.get_favorite_radio_shows instead.

get_favorite_radio_stations(start=0, max_items=100)[source]

Get favorite radio stations from Sonos’ Radio app.

See get_favorite_radio_shows() for return type and remarks.

Deprecated since version 0.13: Will be removed in version 0.15. Use soco.music_library.get_favorite_radio_stations instead.

get_sonos_favorites(start=0, max_items=100)[source]

Get Sonos favorites.

See get_favorite_radio_shows() for return type and remarks.

Deprecated since version 0.13: Will be removed in version 0.15. Use soco.music_library.get_sonos_favorites instead.

create_sonos_playlist(title)[source]

Create a new empty Sonos playlist.

Parameters:title – Name of the playlist
Return type:DidlPlaylistContainer
create_sonos_playlist_from_queue(title)[source]

Create a new Sonos playlist from the current queue.

Parameters:title – Name of the playlist
Return type:DidlPlaylistContainer
remove_sonos_playlist(sonos_playlist)[source]

Remove a Sonos playlist.

Parameters:sonos_playlist (DidlPlaylistContainer) – Sonos playlist to remove or the item_id (str).
Returns:True if succesful, False otherwise
Return type:bool
Raises:SoCoUPnPException – If sonos_playlist does not point to a valid object.
add_item_to_sonos_playlist(queueable_item, sonos_playlist)[source]

Adds a queueable item to a Sonos’ playlist.

Parameters:
  • queueable_item (DidlObject) – the item to add to the Sonos’ playlist
  • sonos_playlist (DidlPlaylistContainer) – the Sonos’ playlist to which the item should be added
get_item_album_art_uri(item)[source]

Get an item’s Album Art absolute URI.

set_sleep_timer(sleep_time_seconds)[source]

Sets the sleep timer.

Parameters:

sleep_time_seconds (int or NoneType) – How long to wait before turning off speaker in seconds, None to cancel a sleep timer. Maximum value of 86399

Raises:
  • SoCoException – Upon errors interacting with Sonos controller
  • ValueError – Argument/Syntax errors
get_sleep_timer()[source]

Retrieves remaining sleep time, if any

Returns:
Number of seconds left in timer. If there is no
sleep timer currently set it will return None.
Return type:int or NoneType
reorder_sonos_playlist(sonos_playlist, tracks, new_pos, update_id=0)[source]

Reorder and/or Remove tracks in a Sonos playlist.

The underlying call is quite complex as it can both move a track within the list or delete a track from the playlist. All of this depends on what tracks and new_pos specify.

If a list is specified for tracks, then a list must be used for new_pos. Each list element is a discrete modification and the next list operation must anticipate the new state of the playlist.

If a comma formatted string to tracks is specified, then use a similiar string to specify new_pos. Those operations should be ordered from the end of the list to the beginning

See the helper methods clear_sonos_playlist(), move_in_sonos_playlist(), remove_from_sonos_playlist() for simplified usage.

update_id - If you have a series of operations, tracking the update_id and setting it, will save a lookup operation.

Examples

To reorder the first two tracks:

# sonos_playlist specified by the DidlPlaylistContainer object
sonos_playlist = device.get_sonos_playlists()[0]
device.reorder_sonos_playlist(sonos_playlist,
                              tracks=[0, ], new_pos=[1, ])
# OR specified by the item_id
device.reorder_sonos_playlist('SQ:0', tracks=[0, ], new_pos=[1, ])

To delete the second track:

# tracks/new_pos are a list of int
device.reorder_sonos_playlist(sonos_playlist,
                              tracks=[1, ], new_pos=[None, ])
# OR tracks/new_pos are a list of int-like
device.reorder_sonos_playlist(sonos_playlist,
                              tracks=['1', ], new_pos=['', ])
# OR tracks/new_pos are strings - no transform is done
device.reorder_sonos_playlist(sonos_playlist, tracks='1',
                              new_pos='')

To reverse the order of a playlist with 4 items:

device.reorder_sonos_playlist(sonos_playlist, tracks='3,2,1,0',
                              new_pos='0,1,2,3')
Parameters:
  • sonos_playlist – (DidlPlaylistContainer): The Sonos playlist object or the item_id (str) of the Sonos playlist.
  • tracks – (list): list of track indices(int) to reorder. May also be a list of int like things. i.e. ['0', '1',] OR it may be a str of comma separated int like things. "0,1". Tracks are 0-based. Meaning the first track is track 0, just like indexing into a Python list.
  • new_pos (list) – list of new positions (int|None) corresponding to track_list. MUST be the same type as tracks. 0-based, see tracks above. None is the indicator to remove the track. If using a list of strings, then a remove is indicated by an empty string.
  • update_id (int) – operation id (default: 0) If set to 0, a lookup is done to find the correct value.
Returns:

Which contains 3 elements: change, length and update_id.

Change in size between original playlist and the resulting playlist, the length of resulting playlist, and the new update_id.

Return type:

dict

Raises:

SoCoUPnPException – If playlist does not exist or if your tracks and/or new_pos arguments are invalid.

clear_sonos_playlist(sonos_playlist, update_id=0)[source]

Clear all tracks from a Sonos playlist. This is a convenience method for reorder_sonos_playlist().

Example:

device.clear_sonos_playlist(sonos_playlist)
Parameters:
  • sonos_playlist – (DidlPlaylistContainer): Sonos playlist object or the item_id (str) of the Sonos playlist.
  • update_id (int) – Optional update counter for the object. If left at the default of 0, it will be looked up.
Returns:

See reorder_sonos_playlist()

Return type:

dict

Raises:
move_in_sonos_playlist(sonos_playlist, track, new_pos, update_id=0)[source]

Move a track to a new position within a Sonos Playlist. This is a convenience method for reorder_sonos_playlist().

Example:

device.move_in_sonos_playlist(sonos_playlist, track=0, new_pos=1)
Parameters:
  • sonos_playlist – (DidlPlaylistContainer): Sonos playlist object or the item_id (str) of the Sonos playlist.
  • track (int) – 0-based position of the track to move. The first track is track 0, just like indexing into a Python list.
  • new_pos (int) – 0-based location to move the track.
  • update_id (int) – Optional update counter for the object. If left at the default of 0, it will be looked up.
Returns:

See reorder_sonos_playlist()

Return type:

dict

Raises:

SoCoUPnPException – See reorder_sonos_playlist()

remove_from_sonos_playlist(sonos_playlist, track, update_id=0)[source]

Remove a track from a Sonos Playlist. This is a convenience method for reorder_sonos_playlist().

Example:

device.remove_from_sonos_playlist(sonos_playlist, track=0)
Parameters:
  • sonos_playlist – (DidlPlaylistContainer): Sonos playlist object or the item_id (str) of the Sonos playlist.
  • track (int) – 0*-based position of the track to move. The first track is track 0, just like indexing into a Python list.
  • update_id (int) – Optional update counter for the object. If left at the default of 0, it will be looked up.
Returns:

See reorder_sonos_playlist()

Return type:

dict

Raises:

SoCoUPnPException – See reorder_sonos_playlist()

get_sonos_playlist_by_attr(attr_name, match)[source]

Return the first Sonos Playlist DidlPlaylistContainer that matches the attribute specified.

Parameters:
  • attr_name (str) – DidlPlaylistContainer attribute to compare. The most useful being: ‘title’ and ‘item_id’.
  • match (str) – Value to match.
Returns:

The

first matching playlist object.

Return type:

(DidlPlaylistContainer)

Raises:
  • (AttributeError) – If indicated attribute name does not exist.
  • (ValueError) – If a match can not be found.

Example:

device.get_sonos_playlist_by_attr('title', 'Foo')
device.get_sonos_playlist_by_attr('item_id', 'SQ:3')