soco.music_services.music_service module

Sonos Music Services interface.

This module provides the MusicService class and related functionality.

class soco.music_services.music_service.MusicServiceSoapClient(endpoint, timeout, music_service)[source]

A SOAP client for accessing Music Services.

This class handles all the necessary authentication for accessing third party music services. You are unlikely to need to use it yourself.

Parameters
  • endpoint (str) – The SOAP endpoint. A url.

  • timeout (int) – Timeout the connection after this number of seconds.

  • music_service (MusicService) – The MusicService object to which this client belongs.

get_soap_header()[source]

Generate the SOAP authentication header for the related service.

This header contains all the necessary authentication details.

Returns

A string representation of the XML content of the SOAP

header.

Return type

str

call(method, args=None)[source]

Call a method on the server.

Parameters
  • method (str) – The name of the method to call.

  • args (List[Tuple[str, str]] or None) – A list of (parameter, value) pairs representing the parameters of the method. Defaults to None.

Returns

An OrderedDict representing the response.

Return type

OrderedDict

Raises

MusicServiceException – containing details of the error returned by the music service.

class soco.music_services.music_service.MusicService(service_name, account=None)[source]

The MusicService class provides access to third party music services.

Example

List all the services Sonos knows about:

>>> from soco.music_services import MusicService
>>> print(MusicService.get_all_music_services_names())
['Spotify', 'The Hype Machine', 'Saavn', 'Bandcamp',
 'Stitcher SmartRadio', 'Concert Vault',
 ...
 ]

Or just those to which you are subscribed:

>>> print(MusicService.get_subscribed_services_names())
['Spotify', 'radioPup', 'Spreaker']

Interact with TuneIn:

>>> tunein = MusicService('TuneIn')
>>> print (tunein)
<MusicService 'TuneIn' at 0x10ad84e10>

Browse an item. By default, the root item is used. An OrderedDict is returned:

>>> from json import dumps # Used for pretty printing ordereddicts
>>> print(dumps(tunein.get_metadata(), indent=4))
{
    "index": "0",
    "count": "7",
    "total": "7",
    "mediaCollection": [
        {
            "id": "featured:c100000150",
            "title": "Blue Note on SONOS",
            "itemType": "container",
            "authRequired": "false",
            "canPlay": "false",
            "canEnumerate": "true",
            "canCache": "true",
            "homogeneous": "false",
            "canAddToFavorite": "false",
            "canScroll": "false",
            "albumArtURI":
            "http://cdn-albums.tunein.com/sonos/channel_legacy.png"
        },
        {
            "id": "y1",
            "title": "Music",
            "itemType": "container",
            "authRequired": "false",
            "canPlay": "false",
            "canEnumerate": "true",
            "canCache": "true",
            "homogeneous": "false",
            "canAddToFavorite": "false",
            "canScroll": "false",
            "albumArtURI": "http://cdn-albums.tunein.com/sonos...
            .png"
        },
 ...
    ]
}

Interact with Spotify (assuming you are subscribed):

>>> spotify = MusicService('Spotify')

Get some metadata about a specific track:

>>> response =  spotify.get_media_metadata(
... item_id='spotify:track:6NmXV4o6bmp704aPGyTVVG')
>>> print(dumps(response, indent=4))
{
    "mediaMetadata": {
        "id": "spotify:track:6NmXV4o6bmp704aPGyTVVG",
        "itemType": "track",
        "title": "Bøn Fra Helvete (Live)",
        "mimeType": "audio/x-spotify",
        "trackMetadata": {
            "artistId": "spotify:artist:1s1DnVoBDfp3jxjjew8cBR",
            "artist": "Kaizers Orchestra",
            "albumId": "spotify:album:6K8NUknbPh5TGaKeZdDwSg",
            "album": "Mann Mot Mann (Ep)",
            "duration": "317",
            "albumArtURI":
            "http://o.scdn.co/image/7b76a5074416e83fa3f3cd...9",
            "canPlay": "true",
            "canSkip": "true",
            "canAddToFavorites": "true"
        }
    }
}
or even a playlist:
>>> response =  spotify.get_metadata(
...    item_id='spotify:user:spotify:playlist:0FQk6BADgIIYd3yTLCThjg')

Find the available search categories, and use them:

>>> print(spotify.available_search_categories)
['albums', 'tracks', 'artists']
>>> result =  spotify.search(category='artists', term='miles')

Note

Some of this code is still unstable, and in particular the data structures returned by methods such as get_metadata may change in future.

Parameters
  • service_name (str) – The name of the music service, as returned by get_all_music_services_names(), eg ‘Spotify’, or ‘TuneIn’

  • account (Account) – The account to use to access this service. If none is specified, one will be chosen automatically if possible. Defaults to None.

Raises

MusicServiceException

classmethod get_all_music_services_names()[source]

Get a list of the names of all available music services.

These services have not necessarily been subscribed to.

Returns

A list of strings.

Return type

list

classmethod get_subscribed_services_names()[source]

Get a list of the names of all subscribed music services.

Returns

A list of strings.

Return type

list

classmethod get_data_for_name(service_name)[source]

Get the data relating to a named music service.

Parameters

service_name (str) – The name of the music service for which data is required.

Returns

Data relating to the music service.

Return type

dict

Raises

MusicServiceException – if the music service cannot be found.

property available_search_categories

The list of search categories (each a string) supported.

May include 'artists', 'albums', 'tracks', 'playlists', 'genres', 'stations', 'tags', or others depending on the service. Some services, such as Spotify, support 'all', but do not advertise it.

Any of the categories in this list may be used as a value for category in search().

Example

>>> print(spotify.available_search_categories)
['albums', 'tracks', 'artists']
>>> result =  spotify.search(category='artists', term='miles')
Type

list

sonos_uri_from_id(item_id)[source]

Get a uri which can be sent for playing.

Parameters

item_id (str) – The unique id of a playable item for this music service, such as that returned in the metadata from get_metadata, eg spotify:track:2qs5ZcLByNTctJKbhAZ9JE

Returns

A URI of the form: soco://spotify%3Atrack %3A2qs5ZcLByNTctJKbhAZ9JE?sid=2311&sn=1 which encodes the item_id, and relevant data from the account for the music service. This URI can be sent to a Sonos device for playing, and the device itself will retrieve all the necessary metadata such as title, album etc.

Return type

str

property desc

The Sonos descriptor to use for this service.

The Sonos descriptor is used as the content of the <desc> tag in DIDL metadata, to indicate the relevant music service id and username.

Type

str

get_metadata(item='root', index=0, count=100, recursive=False)[source]

Get metadata for a container or item.

Parameters
  • item (str or MusicServiceItem) – The container or item to browse given either as a MusicServiceItem instance or as a str. Defaults to the root item.

  • index (int) – The starting index. Default 0.

  • count (int) – The maximum number of items to return. Default 100.

  • recursive (bool) – Whether the browse should recurse into sub-items (Does not always work). Defaults to False.

Returns

The item or container’s metadata, or None.

Return type

OrderedDict

See also

The Sonos getMetadata API.

search(category, term='', index=0, count=100)[source]

Search for an item in a category.

Parameters
  • category (str) – The search category to use. Standard Sonos search categories are ‘artists’, ‘albums’, ‘tracks’, ‘playlists’, ‘genres’, ‘stations’, ‘tags’. Not all are available for each music service. Call available_search_categories for a list for this service.

  • term (str) – The term to search for.

  • index (int) – The starting index. Default 0.

  • count (int) – The maximum number of items to return. Default 100.

Returns

The search results, or None.

Return type

OrderedDict

See also

The Sonos search API

get_media_metadata(item_id)[source]

Get metadata for a media item.

Parameters

item_id (str) – The item for which metadata is required.

Returns

The item’s metadata, or None

Return type

OrderedDict

See also

The Sonos getMediaMetadata API

get_media_uri(item_id)[source]

Get a streaming URI for an item.

Note

You should not need to use this directly. It is used by the Sonos players (not the controllers) to obtain the uri of the media stream. If you want to have a player play a media item, you should add add it to the queue using its id and let the player work out where to get the stream from (see On Demand Playback and Programmed Radio)

Parameters

item_id (str) – The item for which the URI is required

Returns

The item’s streaming URI.

Return type

str

get_last_update()[source]

Get last_update details for this music service.

Returns

A dict with keys ‘catalog’, and ‘favorites’. The value of each is a string which changes each time the catalog or favorites change. You can use this to detect when any caches need to be updated.

Return type

OrderedDict

get_extended_metadata(item_id)[source]

Get extended metadata for a media item, such as related items.

Parameters

item_id (str) – The item for which metadata is required.

Returns

The item’s extended metadata or None.

Return type

OrderedDict

See also

The Sonos getExtendedMetadata API

get_extended_metadata_text(item_id, metadata_type)[source]

Get extended metadata text for a media item.

Parameters
  • item_id (str) – The item for which metadata is required

  • metadata_type (str) – The type of text to return, eg

  • 'ARTIST_BIO'

  • Calling (or 'ALBUM_NOTES'.) –

  • extended (get_extended_metadata for the item will show which) –

  • available (metadata_types are) –

Returns

The item’s extended metadata text or None

Return type

str

See also

The Sonos getExtendedMetadataText API

soco.music_services.music_service.desc_from_uri(uri)[source]

Create the content of DIDL desc element from a uri.

Parameters

uri (str) – A uri, eg: 'x-sonos-http:track%3a3402413.mp3?sid=2&amp;flags=32&amp;sn=4'

Returns

The content of a desc element for that uri, eg

'SA_RINCON519_email@example.com'

Return type

str