Random MP3 file

You now have a list of the files in your directory. Pick one at random from that list and play it.

4f81986d33c976ac30717b89ce2bb040e8fc3d96

media_content_id: "{{ state_attr('sensor.media', 'file_list')|random }}"

Note that the file path is part of the file list elements so you don’t need to specify it.

EDIT: looking closely at your file list you may not have specified the correct path for the sensor. It probably needs to be /media/local/music/

Thanks for these contributions.
I am also trying to get this working but without success so far. Having trouble with the paths.

Before attempting this I had

homeassistant:
  media_dirs:
    media: /media

and the Media Browser would play .mp3 files from various folders including /media/Music/Playlist. The full path being
/usr/share/hassio/media/Music/Playlist

The developer tool shows this when playing from this folder -

media_content_id: http://192.168.1.29:8123/media/media/Music/Playlist/Ike%20n%20Tina%20Turner%20-%20Nutbush%20City%20Limits.mp3?authSig=....

I set up

homeassistant:
  allowlist_external_dirs:
    - "/media/Music/Playlist"

and

sensor:
  - platform: folder
    folder: "/media/Music/Playlist/"

as the only valid config.yaml allowed.

I get this for the sensor-
image

so its seeing the tracks I want.

But when I launch my script using
media_content_id: “{{ state_attr(‘sensor.playlist’, ‘file_list’)|random }}”
the developer tool shows

media_content_id: http://192.168.1.29:8123/media/Music/Playlist/Ike%20n%20Tina%20Turner%20-%20Nutbush%20City%20Limits.mp3?authSig=....

i.e with one “media” folder level short, and the player does not play the track.

If I change media_dirs to this -
media_dirs:
media: /

the developer still shows

media_content_id: http://192.168.1.29:8123/media/Music/Playlist/Ike%20n%20Tina%20Turner%20-%20Nutbush%20City%20Limits.mp3?authSig=....

and the track does not play.

Where to go with this?
TIA

This is my script-

play_random_track:
  alias: Play a Random Music Track
  sequence:
  - service: media_player.play_media
    target:
      entity_id: media_player.living_room_speaker_2
    data:
      media_content_id: "{{ state_attr('sensor.playlist', 'file_list')|random }}"
      media_content_type: music

  mode: single

Try this:

media_content_id: "/media{{ state_attr('sensor.playlist', 'file_list')|random }}"

Of course. (Slaps forehead).
Thanks.

So how much trickery is required to loop continuously and randomly through the folder until manually stopped. I am not big on scripts as you may have guessed.
I guess it would be check the player state for idle and restart the sequence. Something like

play_again:
  alias: Play Again
  icon: hass:play
  sequence:
        repeat:
          while:
            - condition: state
              entity_id: media_player.living_room_speaker_2
              state: "idle"
            # Don't do it too many times
            - condition: template
              value_template: "{{ repeat.index <= 20 }}"
          sequence:
            - service: script.play_random_track
  mode: single

That’s one way.

Another way would be to automate it:

trigger:
  - platform: state
    entity_id: media_player.living_room_speaker_2
    to: idle
  - platform: state
    entity_id: input_boolean.continuous_play
action:
  - choose:
      - conditions:
          - condition: state
            entity_id: input_boolean.continuous_play
            state: 'on'
        sequence:
          - service: script.play_random_track
    default:
      - service: media_player.media_stop
        entity_id: media_player.living_room_speaker_2

You would have to create the input boolean obviously. When it is toggled on random tracks play continuously, when toggled off the music stops immediately.

1 Like

The automation works a treat. Thanks.
I didn’t get the play_again script to run properly. It stops after playing the one track.
Is there a function to replace random that could play sequentially by name alphabetically?

There is a next track service you could use: https://www.home-assistant.io/integrations/media_player/#services

Not sure what happens when either no track or the last track is playing.

1 Like

Hello Tom,

Sorry for delay, i’m almost done, but still have an issue :

here is my config :

  allowlist_external_dirs:
    - /media/aya_nahil/histoires
    - /media/Athan
    - /media/Encore une histoire
    - /media/English Story
    - /media/La puce à l oreille
    - /media/La famille

Here is developer Tools sensor result :

Screenshot 2021-07-31 202216

Here is my automation :

media_content_id: '{{ state_attr(''sensor.la_famille'', ''file_list'')|random }}'

But i had an issue with the URL.

2021-07-31 20:23:18 ERROR (Thread-10) [homeassistant.components.cast.media_player] Failed to cast media https://chuck-norris.duckdns.org:8123/media/La%20famille/48.mp3?authSig=ey... from external_url (https://chuck-norris.duckdns.org:8123). Please make sure the URL is: Reachable from the cast device and either a publicly resolvable hostname or an IP address

i could play all mp3 of those folders with the old way i used :

media_content_id: /media/local/La famille/{{range(1,10)|random}}.mp3

in external dirs : it should be /media/local/La famille or /media/La famille ?

because /media/local/La famille is not working

Any idea?

Thanks alot

Try this:

media_content_id: "/media{{ state_attr('sensor.la_famille', 'file_list')|random }}"

Here is the result, as you can see there is /media/media.
I think it should be /media/local/…
but when i add /media/local/ la famille to the configuration file, the schema didn’t pass

2021-08-01 18:52:47 ERROR (Thread-10) [homeassistant.components.cast.media_player] Failed to cast media https://chuck-norris.duckdns.org:8123/media/media/La%20famille/56.mp3?authSig=eyJ0e... from external_url (https://chuck-norris.duckdns.org:8123). Please make sure the URL is: Reachable from the cast device and either a publicly resolvable hostname or an IP address

Finally got an automation that plays a folder’s content in order from the first file to the last.

action:
  - repeat:
      while:
        - condition: template
          value_template: >-
            {{ repeat.index <=
            states.sensor.dire_straits_brothers_in_arms.attributes.number_of_files
            }}
      sequence:
        - service: media_player.turn_on
          target:
            device_id: 9d7c215c6bbeb89d4e6496bxxxxxxxxxx
        - service: media_player.play_media
          target:
            device_id: 9d7c215c6bbeb89d4e6496bxxxxxxxxxx
          data:
            media_content_type: audio/mp3
            media_content_id: >-
              media-source://media_source{{
              states.sensor.dire_straits_brothers_in_arms.attributes.file_list[repeat.index
              - 1]  }}
        - delay:
            hours: 0
            minutes: 0
            seconds: 11
            milliseconds: 0
        - wait_template: '{{ is_state(''media_player.living_room_speaker_2'', ''idle'') }}'
mode: single

Works for sub folders in the path also.
Good option to random playing.

2 Likes

Wow this is complicated! Does it work on SMB shares also? I’m unable to add my NAS share to the allowlist or the Folder sensor.

Have almost the same problem. Did you solve this?

Have this setup:

homeassistant:
  media_dirs:
      media: /config/media
    allowlist_external_dirs:
      - /config/media/karacsony
      - /config
    allowlist_external_urls:
      - https://MYDNDNS/config/media/karacsony
    whitelist_external_dirs:
      - /config/media/karacsony
sensor
  - platform: folder
    folder: /config/media/karacsony

Get this:

path: /config/media/karacsony/
filter: '*'
number_of_files: 4
bytes: 27949440
file_list:
  - /config/media/karacsony/03.mp3
  - /config/media/karacsony/02.mp3
  - /config/media/karacsony/01.mp3
  - /config/media/karacsony/@eaDir
unit_of_measurement: MB
friendly_name: karacsony
icon: mdi:folder

On call service working good (you see no config folder)

service: media_player.play_media
data:
  media_content_id: media-source://media_source/media/karacsony/01.mp3
  media_content_type: audio/mp3
target:
  entity_id: media_player.google_home_mini

But if I want to play random mp3 from that folder:

alias: Karacsony
sequence:
  - service: media_player.play_media
    target:
      entity_id: media_player.google_home_mini
    data:
      media_content_id: >-
        media-source://media_source/{{ state_attr('sensor.karacsony',
        'file_list')|random }}
      media_content_type: audio/mp3
mode: single

Get this errors:

Failed to cast media media-source://media_source//config/media/karacsony/01.mp3. Please make sure the URL is: Reachable from the cast device and either a publicly resolvable hostname or an IP address
Failed to cast media media-source://media_source//config/media/karacsony/02.mp3. Please make sure the URL is: Reachable from the cast device and either a publicly resolvable hostname or an IP address

What I see this script:

media_content_id: >-
        media-source://media_source/{{ state_attr('sensor.karacsony',
        'file_list')|random }}

always insert a config path before /media/karacsony/ and thats why cant play the music on my google home. When i call form developer tools not write this config folder only media/karacsony and working good.

But in the configuration files must use config folder because I use Home Assistant in docker and only accept it with config and then the other folders.

How can I solve this problem?

Found the solution, this is working perfectly:

alias: Karacsony
sequence:
  - service: media_player.play_media
    target:
      entity_id: media_player.google_home_mini
    data:
      media_content_id: >-
        media-source://media_source/media/{{ state_attr('sensor.karacsony',
        'file_list')|random }}
      media_content_type: audio/mp3
mode: single
2 Likes

Thank you for sharing the solution.
By the way, have you tried to make a script to play the list of mp3 files in local media folder in ordering by file name?
For example there are 3 mp3 files in /media folder as below:
1.mp3
2.mp3
3.mp3

The expectation is when start the script, the file 1 will be played first then file 2, then file 3 etc.

Thank you.

Hi,
I know it’s old thread but it’s not working for me .
if i send random file :

media_content_id: >-
  http://10.0.0.11:8123/media/quran/064%20-%20At-Taghabun%20-%20Abdulbasit%20Abdulsamad.mp3

and not working

if i select file manually it’s working and i see extra /local/ on file path

media_content_id: >-
  http://10.0.0.11:8123/media/local/quran/002%20-%20Al-Baqarah%20-%20Abdulbasit%20Abdulsamad.mp3

my command:

service: media_player.play_media
data:
  enqueue: play
  media_content_type: audio/mp3
  media_content_id: "{{ state_attr('sensor.quran', 'file_list')|random }}"
target:
  entity_id: media_player.chrome_cast

Same issue here, did you manage to resolve the “local” issue?

edit: I found a workaround, in your example… just add a folder “local” to “media” and copy “quran” to “local” … this breaks the manual selection of a media file but the randomise works…

1 Like

This works for me

service: media_player.play_media
data:
  media_content_type: music
  media_content_id: media-source://media_source{{ state_attr('sensor.halloween_sounds', 'file_list')|random }}
target:
  entity_id: media_player.garage

1 Like