How to play/pause a Media Player using variables

Hello Friends,

I have three media_players configured in HA.
media_player.mp1
media_player.mp2
media_player.mp3

Only one of them would be playing at a given time. The below script will store the entity_id of that media_player.

- variables:
    media_players: >
      {% set media_players = [
        states.media_player.mp1,
        states.media_player.mp2,
        states.media_player.mp3
        ] %}
      {{ media_players | selectattr('state','eq','playing') |
      map(attribute ='entity_id') | join()}}

A: In the below part I want to check if any one of the players or all are in off, idle, paused state then turn the boolean ON or OFF accordingly

- service_template: |-
    {% if states('media_player.mp1') and states('media_player.mp2') and states('media_player.mp3') in ['off','idle','paused'] %} 
        input_boolean.turn_off
    {% else %}
        input_boolean.turn_on
    {% endif %}
  entity_id: input_boolean.is_playing

B: In this part I want to check if any one of the player is playing it should get paused. How do I use the varibale media_players here ?

- service_template: |-
    {% if states('media_player.mp1') in ['off','idle'] %} 
        media_player.media_stop
    {% else %}
        media_player.media_pause
    {% endif %}
  entity_id: media_player.mp1

C: In this part I want to start the playback on that media_player that was paused in step B. How do I use the varibale media_players here ?

- if:
    - condition: state
      entity_id: input_boolean.is_playing
      state: "on"
  then:
    - service: media_player.media_play
      data: {}
      target:
        entity_id: media_player.mp1

Kindly help me fix this code or kindly suggest a better alternative.

Thanks in advance

What is the ultimate goal? Is it this:

Because if it is then I don’t see the need for an Input Boolean.

Need to dim the lights and change color if a music player is playing. I may be doing it wrongly that why need guidance

Then there’s no need for an Input Boolean. Just use a Template Condition to check if any are playing.

- if:
    - condition: template 
      value_template: >
        {{ expand('media_player.mp1', 'media_player.mp2', 'media_player.mp3')
          | selectattr('state', 'eq', 'playing') | list | count > 0 }}
  then:
    - service: light.turn_on
      ... etc ...

And how to only pause a player which is playing? I want to pause the player to announce via TTS.

- variables:
    players: >
      {{ expand('media_player.mp1', 'media_player.mp2', 'media_player.mp3')
        | selectattr('state', 'eq', 'playing')
        | map(attribute='entity_id') | list }}
- if:
    - condition: template 
      value_template: "{{ players | count > 0 }}"
  then:
    - service: media_player.media_pause
      target:
        entity_id: '{{ players }}'
1 Like

Thank you, I will try it and let you know

Thank you the code worked…

1 Like