Home Assistant value template count media players in specific states

As I was making some further improvements to my smart home dashboard I was trying to minimize the clutter and hide cards if they aren't actually useful at the time, this card below for example displays all the current active media players so that I can see what's streaming where.
However to be able to create a condition for this I needed a new entity that would either:
  • Count the number of media players currently in a paused or playing state
  • Have a value of true or false based on if there was at least one media player in these states

Both options are possible, but I decided to go with the count of media players as this could be a handy figure for other uses.

Home Assistant count media players playing or paused

The following value template was formulated to count the number of currently playing or currently paused media players.

{{ int(states.media_player|selectattr("state","equalto","playing")|list|length) + int(states.media_player|selectattr("state","equalto","paused")|list|length) }}


This Home Assistant value template calculates the total number of media players that are either in a "playing" or "paused" state, and returns the result as an integer.

Here's a breakdown of how the template works:

  • states.media_player retrieves a list of all media player entities in the current Home Assistant state.
  • |selectattr("state","equalto","playing") filters this list to only include entities whose state attribute is equal to "playing".
  • |list converts this filtered list into a standard Python list format.
  • |length returns the number of items in the resulting list as an integer.
  • The same process is repeated for the "paused" state, and the two resulting integers are added together using the + operator.

The end result is a single integer value that represents the total number of media players that are either playing or paused.

Adding this formula into your Home Assistant configuration file can be done with the following code.

 sensor:

 - platform: template

    sensors:

      active_media_players:

        friendly_name: 'Active media players'

        value_template: '{{ int(states.media_player|selectattr("state","equalto","playing")|list|length) + int(states.media_player|selectattr("state","equalto","paused")|list|length) }}'


Was this helpful?

Yes No


Comments