Thomas shares makes

2020-05-02

Mutually Exclusive Media Players in Home Assistant

hass rpi mpd

I have Raspberry Pi's in different rooms, and one thing I use them for is to play music to speakers.

Each of them has two music player services on it (MPD, Spotify), and it's a bit annoying that I have to stop a player when I want to listen to the other one.

Since I'm running home assistant as an automation hub, I wrote two short automations that stop the already playing service when the second one kicks in.

I use two different audio players:

  • MPD: to play
    • internet streams like radio Willy
    • My CD collection that I ripped to my NAS server since some artists (like Daan) do not offer their complete discography on streaming services.
    • Music bought via Bandcamp.com
    • A lot of nice live show recordings, which you can find on www.archive.org
  • Raspotify: to use them as Spotify Connect speakers.

Turning off Spotify when MPD starts works flawlessly, this automation pauses Spotify when MPD starts playing:

- id: zolder_spotify_auto_off
  alias: "Zolder spotify auto uit"
  trigger:
  - entity_id: media_player.mpd_zolder
    platform: state
    to: 'playing'
  condition:
  - condition: template
    value_template: "{% if is_state_attr('media_player.spotify_thomas_langewouters','source','Zolder')  %}true{% endif %}"
  - condition: template
    value_template: "{% if is_state('media_player.spotify_thomas_langewouters', 'playing') %}true{% endif %}"
  action:
    service: media_player.media_pause
    data:
      entity_id: media_player.spotify_thomas_langewouters

Stopping MPD when Spotify starts is a bit less streamlined in practice:

- id: zolder_mpd_auto_off
  alias: "Zolder MPD auto off"
  trigger:
  - platform: template
    value_template: "{% if is_state_attr('media_player.spotify_thomas_langewouters','source','Zolder')  %}true{% endif %}"
  - entity_id: media_player.spotify_thomas_langewouters
    platform: state
    to: 'playing'
  condition:
  - condition: template
    value_template: "{% if is_state_attr('media_player.spotify_thomas_langewouters','source','Zolder')  %}true{% endif %}"
  - condition: template
    value_template: "{% if is_state('media_player.mpd_zolder', 'playing') %}true{% endif %}"
  action:
    service: media_player.media_stop
    data:
      entity_id: media_player.mpd_zolder

This is caused by the fact that Home Assistant's Spotify integration is polling, and it takes a few seconds for the automation to be triggered. Meanwhile both are playing. It does work eventually, which is the most important thing.

Note that I pause Spotify, and stop MPD, since I use MPD for streams (which I don't want to pause).


Liked something? Worked on something similar? Let me know what you think on Mastodon!
You can direct-message me, or mention me @thouters@hsnl.social
Follow me on Mastodon!