Spotify Playlist Player

Has anyone gotten podcast URI’s to work? Or is this feature not supported yet?

Good morning.

I got my spotify works. However, I don’t understand about the media_player part especially the aliases part. Please kindly advice.

media_player:
  - platform: spotify
    client_id:  xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    client_secret:  xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    aliases:
         xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx: 'Web Player (Chrome)' <== Where is the 'xxx' from and stand for? and also "Web Player (Chrome)" <== is this the name of speaker devices in HA example 'name of the media_player in ha I have?
         xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx: 'All Home Speakers'

Thank you very much. I got it working so nice.

regarding the question above ‘aliases’ I didn’t use that part in my media_player at all.

Makani where did you add this code? Thanks!

Also what is the “ID” in your example.

@makani47
Your automation only updates when you pause or play the spotify. I added a feature to change the sliders while playing. It includes a 10 second delay to prevent input number jumping to “original” value. So when volume changed outside HA it actually takes 10 seconds + time to notice the change to update input_number.

@Dracoy
That code needs to be in “automation:” section. If you want to modify your automations from the front end they need to have unique ID’s. ID can be whatever you come up with.

- alias: Spotify volume (set)
  trigger:
  - platform: state
    entity_id: input_number.spotify_volume
  action:
  - service: media_player.volume_set
    data_template:
      entity_id: media_player.spotify
      volume_level: '{{ states.input_number.spotify_volume.state }}'

- alias: Spotify volume (get)
  trigger:
  - platform: template
    value_template: '{{(states.media_player.spotify.attributes.volume_level | float) != (states.input_number.spotify_volume.state | float) }}'
  action:
    # 10 second delay to prevent input_number jumping to "original" value
    # before it is updated from spotify
  - delay: '00:00:10'
  - service: input_number.set_value
    data_template:
      entity_id: input_number.spotify_volume
      value: "{{states.media_player.spotify.attributes.volume_level}}"
1 Like

That might explain why I get errors on occasion with input_number. I hadn’t looked into it much since I last posted. I’ll give your modified version a try.

Hi,

I liked the idea of controlling spotify directly from panel but I wanted it to be bidirectional not only for volume but for shuffle and source too.

Here is my approach:

As I’m working with packages, I have everything related to spotify in packages/spotify.yaml

media_player:
  - platform: spotify
    client_id: !secret spotify_client_id
    client_secret: !secret spotify_client_secret

group:
  home_spotify_player:
    name: Spotify Player
    entities:
      - media_player.spotify
  
  home_spotify_controls:
    name: Spotify Controls
    control: hidden
    entities:
      - input_select.spotify_playlist
      - input_select.spotify_source
      - script.spotify_music
      - input_number.spotify_volume
      - input_boolean.spotify_shuffle


homeassistant:
  customize:
    script.spotify_music:
      friendly_name: 'Play'
      icon: mdi:play

sensor:
  - platform: template
    sensors:
      spotify_volume:
        friendly_name: "Spotify Volume"
        value_template: "{{ states.media_player.spotify.attributes.volume_level }}"
  - platform: template
    sensors:
      spotify_shuffle:
        friendly_name: "Spotify Shuffle"
        value_template: "{{ states.media_player.spotify.attributes.shuffle }}"
  - platform: template
    sensors:
      spotify_source:
        friendly_name: "Spotify Source"
        value_template: "{{ states.media_player.spotify.attributes.source }}"

input_number:
  spotify_volume:
    name: Volume
    icon: mdi:volume-high
    initial: 100
    min: 0
    max: 100
    step: 1

input_select:
  spotify_playlist:
    name: 'Playlist:'
    options:
      - Made In Germany
      - Murmel
      - Chillige Bässe
      - Chillstep
      - Mixed Hip Hop
      - Mixed Electro
      - Mixed Rock
      - Mixed Dub
      - Good Feeling
      - Nightair
      - Streetbangers
    icon: mdi:spotify
  spotify_source:
    name: 'Source:'
    options:
      - ECHOKUECHE
      - ECHODOTBUERO
      - ECHODOTAUDI
    initial: ECHOKUECHE
    icon: mdi:speaker-wireless

input_boolean:
  spotify_shuffle:
    name: Shuffle
    icon: mdi:shuffle-variant

script:
  spotify_music:
    alias: "Play selected spotify playlist"
    sequence:
      - service: media_player.select_source
        data_template: 
          entity_id: media_player.spotify
          source: >
            {% if is_state("input_select.spotify_source", "ECHOKUECHE") %} ECHOKUECHE
            {% elif is_state("input_select.spotify_source", "ECHODOTBUERO") %} ECHODOTBUERO
            {% elif is_state("input_select.spotify_source", "ECHODOTAUDI") %} ECHODOTAUDI
            {% endif %}
      - service: media_player.play_media
        data_template:
          entity_id: media_player.spotify
          media_content_type: playlist
          media_content_id: >
            {% if is_state("input_select.spotify_playlist", "Made In Germany") %} spotify:user:playlists.germany:playlist:5M7jfvXr6fiQ21U8jfe9aE
            {% elif is_state("input_select.spotify_playlist", "Murmel") %} spotify:user:1143893613:playlist:5dfbLgeesT8gixq1GTWBoU
            {% elif is_state("input_select.spotify_playlist", "Chillige Bässe") %} spotify:user:spotify:playlist:37i9dQZF1DX37cXruBmbRS
            {% elif is_state("input_select.spotify_playlist", "Chillstep") %} spotify:user:kent1337:playlist:6IjDl5eRczFdgZkKYXhuHZ
            {% elif is_state("input_select.spotify_playlist", "Mixed Hip Hop") %} spotify:user:1143893613:playlist:4yuXhTpPFSTnRSYmAN8mse
            {% elif is_state("input_select.spotify_playlist", "Mixed Electro") %} spotify:user:1143893613:playlist:1grR3x1MSPlyfS6VsaSzPn
            {% elif is_state("input_select.spotify_playlist", "Mixed Rock") %} spotify:user:1143893613:playlist:2ECMyR5ovezJBGQDnL3w23
            {% elif is_state("input_select.spotify_playlist", "Mixed Dub") %} spotify:user:1143893613:playlist:093q3iMD3lAA4h5oatDJPh
            {% elif is_state("input_select.spotify_playlist", "Good Feeling") %} spotify:user:1143893613:playlist:0rHdZMqeSR4XVvPf6QmFM4
            {% elif is_state("input_select.spotify_playlist", "Nightair") %} spotify:user:1143893613:playlist:2C4xXSYKJp0CYwIyWhODpD
            {% elif is_state("input_select.spotify_playlist", "Streetbangers") %} spotify:user:1143893613:playlist:1JzR2qe9P3EOjgSyVNJ80R
            {% endif %}

automation:
  - alias: 'Spotify Volume (Set)'
    trigger:
      platform: state
      entity_id: input_number.spotify_volume
    action:
      service: media_player.volume_set
      data_template:
        entity_id: media_player.spotify
        volume_level: '{{  states.input_number.spotify_volume.state | int / 100  }}'
  
  - alias: 'Spotify Volume (Sync)'
    trigger:
      - platform: homeassistant
        event: start
      - platform: state
        entity_id: sensor.spotify_volume
    action:
      - delay:
          seconds: 5
      - service: input_number.set_value
        data_template:
          entity_id: input_number.spotify_volume
          value: '{{  states.sensor.spotify_volume.state | float | round(2) * 100  }}'
  
  - alias: 'Spotify Shuffle (Set)'
    trigger:
      platform: state
      entity_id: input_boolean.spotify_shuffle
    action:
      service: media_player.shuffle_set
      data_template:
        entity_id: media_player.spotify
        shuffle: >
          {% if is_state('input_boolean.spotify_shuffle', 'off') %} 
          false
          {% elif is_state('input_boolean.spotify_shuffle', 'on') %}
          true
          {% endif %}
  
  - alias: 'Spotify Shuffle (Sync)'
    trigger:
      - platform: homeassistant
        event: start
      - platform: state
        entity_id: sensor.spotify_shuffle
    action:
      - delay:
          seconds: 5
      - service_template: >
          {% if states.sensor.spotify_shuffle.state == 'False' %}
            input_boolean.turn_off
          {% else %}
            input_boolean.turn_on
          {% endif %}
        data:
          entity_id: input_boolean.spotify_shuffle

  - alias: 'Spotify Source (Sync)'
    trigger:
      - platform: homeassistant
        event: start
      - platform: state
        entity_id: sensor.spotify_source
    action:
      service: input_select.select_option
      entity_id: input_select.spotify_source
      data_template:
        option: '{{  states.sensor.spotify_source.state  }}'

Additional Changes:

  • Volume Slider goes from 0-100
  • Volume Slider, Shuffle and Source are synced when Homeassistant starts or the state changed (i.e someone changed volume not in HASS)

Info:

  • The delay of 5 secs is enough for volume and shuffle to not rumble around
  • The (Sync) automations rely on the according sensors and if I’m right, HASS updates these attributes every 30 secs, so it might take a while to reflect in HASS

Happy Spotifying

12 Likes

This looks really good
Does this prevent Spotify from loosing the sources?

What do you mean?

Great project… i have just only one doubt: how to get the correct URI of my playlists to insert inside the package?

As you are in the Spotify app and on your playlist, click the three dots -> Share -> Copy Spotify URI

Thanks, and then i must put the whole link or only the last numbers?

the whole link…

1 Like

I don’t want to open my HASS to the internet. Is it possible to use spotify without portforward and use a dyndns service ? ( I don’t even know how :slight_smile: :slight_smile: )

As far as I know you need to connect to a spotify developer app and this needs a redirect url to your HASS. But it might only be needed for initial connection and you can disable portforward afterwards

After configuring all without any error from checking the various configurations, i get the following error when i try to send spotify playlist to one of my media players:

Error executing service <ServiceCall media_player.volume_set: volume_level=0.4, entity_id=[‘media_player.spotify’]>
Traceback (most recent call last):
File “/srv/homeassistant/lib/python3.5/site-packages/spotipy/client.py”, line 121, in _internal_call
r.raise_for_status()
File “/srv/homeassistant/lib/python3.5/site-packages/requests/models.py”, line 935, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://api.spotify.com/v1/me/player/volume?volume_percent=40

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File “/srv/homeassistant/lib/python3.5/site-packages/homeassistant/core.py”, line 1002, in _event_to_service_call
await service_handler.func(service_call)
File “/srv/homeassistant/lib/python3.5/site-packages/homeassistant/components/media_player/init.py”, line 403, in async_service_handler
yield from getattr(player, method[‘method’])(**params)
File “/usr/lib/python3.5/asyncio/futures.py”, line 380, in iter
yield self # This tells Task to wait for completion.
File “/usr/lib/python3.5/asyncio/tasks.py”, line 304, in _wakeup
future.result()
File “/usr/lib/python3.5/asyncio/futures.py”, line 293, in result
raise self._exception
File “/usr/lib/python3.5/concurrent/futures/thread.py”, line 55, in run
result = self.fn(*self.args, **self.kwargs)
File “/srv/homeassistant/lib/python3.5/site-packages/homeassistant/components/media_player/spotify.py”, line 216, in set_volume_level
self._player.volume(int(volume * 100))
File “/srv/homeassistant/lib/python3.5/site-packages/spotipy/client.py”, line 976, in volume
self._put(self._append_device_id(“me/player/volume?volume_percent=%s” % volume_percent, device_id))
File “/srv/homeassistant/lib/python3.5/site-packages/spotipy/client.py”, line 190, in _put
return self._internal_call(‘PUT’, url, payload, kwargs)
File “/srv/homeassistant/lib/python3.5/site-packages/spotipy/client.py”, line 126, in _internal_call
headers=r.headers)
spotipy.client.SpotifyException: http status: 403, code:-1 - https://api.spotify.com/v1/me/player/volume?volume_percent=40:
Not available for the current user

Can you help me in tracking and solving this?

Does the player itself work?

I’ve set up Spotify and it keeps loosing the source to play from. Meaning I can’t get any scripts or automations to work.

What you mean? I have the player on the chrome and on the phone and all of them are working… did you mean this?

I mean the media_player in HASS