Song History for Sonos

If you’re interested, here’s my version. It uses a single Trigger-based Template Sensor to maintain a record of the last 5 tracks played (artist, title, time). It can easily be expanded from 5 to whatever quantity is needed.

template:
  - trigger:
      - platform: state
        entity_id: media_player.kitchen
        attribute: media_title
    sensor:
      - name: Recent Tracks
        state: "{{ now().timestamp() | timestamp_custom() }}"
        attributes:
          tracks: >
            {% set current = this.attributes.get('tracks', []) %}
            {% set new = [{
                "artist": trigger.to_state.attributes.media_artist,
                "title": trigger.to_state.attributes.media_title,
                "time": now().isoformat() }]
                if is_state('media_player.kitchen', 'playing') else [] %}
            {{ (new + current)[:5] }}

Here’s the sensor’s information.

Here’s the content for the Markdown card.

|Artist||Title|
|:----|:-:|:----|
{% for x in state_attr('sensor.recent_tracks', 'tracks') | default([], true) -%}
  |{{x.artist}}||{{x.title}}|
{% endfor -%}

Here’s the appearance of the Markdown card.
image

5 Likes