I offer you another solution, based on a timer
.
Just like your solution, it uses one input_boolean to start/stop looping.
input_boolean:
loop_sound_bite:
name: loop sound bite
Create one timer. Its duration will be assigned by an automation.
timer:
looper:
Create three automations:
- Looping controller
- Looper timer started
- Looper timer finished
The first automation is triggered by input_boolean.loop_sound_bite
and simply starts/stops the timer (i.e. starts/stops looping).
The key feature here is that the timer’s duration
is determined by the media_duration
attribute of your sensor.sound_bite_player
. In other words, the timer runs for as long as the media requires to play.
- alias: 'Looping controller'
trigger:
platform: state
entity_id: input_boolean.loop_sound_bite
action:
service_template: "{{'timer.start' if trigger.to_state.state == 'on' else 'timer.finish'}}"
data_template:
entity_id: timer.looper
duration: >-
{% set x = state_attr(states('sensor.sound_bite_player'),'media_duration')|int %}
{{ x if trigger.to_state.state == 'on' else 0 }}
The second automation is triggered when the timer starts. It’s job is to simply start playing the media.
- alias: 'Looper timer started'
trigger:
- platform: event
event_type: timer.started
event_data:
entity_id: timer.looper
action:
- service: media_player.play_media
data_template:
entity_id: "{{states('sensor.sound_bite_player')}}"
media_content_id: "{{states('sensor.sound_bite')}}"
media_content_type: 'music'
The third and final automation is triggered when the timer finishes. It’s job is to restart the timer but only if input_boolean.loop_sound_bite
is on
.
- alias: 'Looper timer finished'
trigger:
- platform: event
event_type: timer.finished
event_data:
entity_id: timer.looper
condition:
condition: state
entity_id: input_boolean.loop_sound_bite
state: 'on'
action:
- service: timer.start
entity_id: timer.looper
I couldn’t test this solution using a media_player (I don’t have one available). However, I simply replaced the media_player with a light and made it toggle on/off every 5 seconds. It works well.
In practice you may need to add a second or two to the timer’s duration to ensure it provides enough time for the media_player to finish playing the media.