Choose random file in a service - automation

Hi

Is it possible that my automation, calling this service, selects a random mp3 from the chime path? There are some MP3 files there and I want an MP3 to be randomly selected and played.

service: chime_tts.say
data:
  chime_path: /media/sounds/test1.mp3
  tts_platform: tts.google_nl_com
  volume_level: 1
  message: test message
target:
  device_id: 66d5d1269b164cd50d3e6343354652410

Is the only possible way to use a template line like this?

  option: "{{['testmp1','testmp2', 'testmp3']|random}}"

but then I need to define all MP3 file names, what I would like to avoid. (there are a lot).
Thanks

Create a Folder Sensor using the Folder integration.

The sensor will have a file_list attribute containing a list of all files it found (as per how you configured the Folder Sensor).

Assuming the Folder Sensor is sensor.my_music, your template will look something like this:

chime_path: "{{ state_attr('sensor.my_music', 'file_list') | random }}"

NOTE

Ensure you follow the integration’s instructions. The usual problem is that the Folder Sensor doesn’t have permission to access the desired folder.

2 Likes

The disadvantage of the folder sensor is that it ignores sub folders.
If you have a folder structure like

➜  ~ tree /media/sounds                         
/media/sounds
β”œβ”€β”€ file with space.mp3
β”œβ”€β”€ file1.mp3
β”œβ”€β”€ file2.mp3
└── subfolder
    β”œβ”€β”€ file with space.mp3
    β”œβ”€β”€ file1.mp3
    └── file2.mp3

the files in the subfolder are not visible.

path: /media/sounds/
filter: "*"
number_of_files: 4
bytes: 0
file_list:
  - /media/sounds/file1.mp3
  - /media/sounds/file with space.mp3
  - /media/sounds/subfolder <---
  - /media/sounds/file2.mp3
unit_of_measurement: MB
device_class: data_size
icon: mdi:folder
friendly_name: sounds

So my approach is:
Create a little bash script

#!/bin/bash

MP3DIR='/media/sounds'
MP3PATH=`find $MP3DIR -type f -name '*.mp3' | shuf -n 1`
MP3=`basename $MP3PATH`

echo "{\"mp3\": \"$MP3\", \"mp3path\": \"$MP3PATH\"}"

make it executable

chmod +x /path/to/script.sh

now a command_line sensor

command_line:
  - sensor:
      name: random_mp3
      command: "/path/to/script.sh"
      value_template: "{{ value_json.mp3 }}"
      json_attributes:
        - mp3path

Now you can use the mp3path attribute of the command_line sensor

chime_path: "{{ state_attr('sensor.random_mp3', 'mp3path') }}"
1 Like

Thanks for this addition for files in subfolders!