Help to play a random sound file

I am hoping for help with a project. I have been doing a lot of research and just can’t quite figure it out.

I have a folder of sound files. When my automation is fired, I want it to play a random one.

What I was thinking is:

  1. have home assistant read the files in the folder and save them in an array

  2. pick a random number and use that to select the item in the array

after that, i can handle playing the file and whatever else.

Any help would be much appreciated.


As far as I am aware, Home Assistant cant do point 1 through the services available. You would probably need a Python script for that.

I’m thinking there might be a way with the command line sensor? can i just use ‘ls /path/to/folder’ and then feed that sensor data through a template to split the file names into discrete data points and then make an array?

That could work, as long as the result is under the 255 character limit for states.