Sonos script only plays mp3 for about half a second

Hi all, any idea what is wrong with this automation and script? Only a very small part of the mp3 is heard.

The automation:

alias: Deurbel mp3
description: "2020-05-14"
trigger:
  - from: "off"
    platform: state
    to: "on"
    entity_id: binary_sensor.voordeur_ding
action:
  - service: script.sonos_mp3_script
    data:
      delay: "00:03:00"
      sonos_entity: media_player.woonkamer
      volume: 0.3
mode: single

The script:

alias: Sonos MP3 script
sequence:
  - data_template:
      entity_id: "{{ sonos_entity }}"
    service: sonos.snapshot
  - data_template:
      entity_id: "{{ sonos_entity }}"
    service: media_player.unjoin
  - data_template:
      entity_id: "{{ sonos_entity }}"
      volume_level: "{{ volume }}"
    service: media_player.volume_set
  - data_template:
      entity_id: "{{ sonos_entity }}"
      media_content_id: http://xxx.xxx.xxx.xxx:8123/local/doorbell.mp3
      media_content_type: music
    service: media_player.play_media
  - data_template:
      entity_id: "{{ sonos_entity }}"
    service: sonos.restore
mode: single

and the log:

It looks a bid as if the script order is wrong. But what to do? Any help would be nice.

You’re not waiting for the media to stop playing.

Actions are issued as quickly as possible, so HA sends the play_media command and immediately moves on to the next action.

You need either a fixed delay or some logic with a wait_template.

I have a delay of 3 seconds in the automation. If I remember correctly I needed this because I have a long TTS message, but I am not sure anymore. I will test if it doesn’t just delay time before the message is played. So should I use a delay in the script somewhere?

You have delay: "00:03:00" as data for the script, but your script doesn’t do anything with it.

I really appreciate the fact that you are trying to help me. But I have no indeep knowledge of what I am doing here. I just copy/past from what I can find and try if it works. So honestly I have no idea what to do.

Oh, data_template was deprecated in 2020, it’s just data

  - data_template:
      entity_id: "{{ sonos_entity }}"
      media_content_id: http://xxx.xxx.xxx.xxx:8123/local/doorbell.mp3
      media_content_type: music
    service: media_player.play_media
  - data_template:
      entity_id: "{{ sonos_entity }}"
    service: sonos.restore

You need to have a delay between those two actions.

  - data:
      entity_id: "{{ sonos_entity }}"
      media_content_id: http://xxx.xxx.xxx.xxx:8123/local/doorbell.mp3
      media_content_type: music
    service: media_player.play_media
  - delay: "{{ delay }}"
  - data:
      entity_id: "{{ sonos_entity }}"
    service: sonos.restore

Thank you! Only by adding this line (and changed data_template to just data) it made it work.

- delay: "{{ delay }}"

But I can see in the trace the sonos. restore does not take place. because the script is aborted. I did not yet specify a delay time. I will try!