Random music using Python

I want to automate playing random music as shown in Python Automation Scripts You Should Know. However, it wasn’t what I’d expected. When I finally make it work, it only play 1 fixed song, no loop.

How do I make it pay randomly, loop, and play all the music in that folder? And if possible, how to write a script that play all music from more than 1 folder without opening the folder at random?

Windows version

  1. If you want to play all music randomly in the folder → just need to shuffle order of the music and loop to it
songs = os.listdir(music_dir)
random.shuffle(songs)
for song_name in songs :
    song_path = os.path.join(music_dir, song_name)
    print(f'playing... {song_name}')
    os.startfile(song_path)
  1. if you want to play the song in specific folder → create answer 1 as a function and have argument with folder path
def randomly_music(folder_path: str) :
    songs = os.listdir(folder_path)
    random.shuffle(songs)
    print(f'playing music from {folder_path}')
    for song_name in songs :
        song_path = os.path.join(music_dir, song_name)
        print(f'playing... {song_name}')
        os.startfile(song_path)

folders_path = [path1, path2 ... ]
for folder_path in folders_path :
   randomly_music(folder_path)
  1. Only play 1 random music. It doesn’t play all the music in the music_dir, after each music ended.
  2. I was thinking of it play all the music in a range of folders, but at random.

I planned to listen to a range of random music from either 1 specific folder or ranges of folders, automatically while studying.

Another thing that would help greatly is not inputting the hard-coded folder path. Currently, my variable os.path.join and pathlib are not working. Maybe someone here can explain why is that.

Hello this is Gulshan Negi
Well, to play all music in one folder you can execute below code:

#!/usr/local/Microsoft/WindowsApps/python
import random, os
music_dirs = [‘C:/Users/XXXX/Music/XXX’, ‘C:/Users/XXXX/Music/YYY’]
songs =
for music_dir in music_dirs:
songs.extend(os.listdir(music_dir))

infinite loop to play music randomly

while True:
# get a random song from the list of songs
song = random.choice(songs)
# get the directory of the song
music_dir = None
for dir in music_dirs:
if song in os.listdir(dir):
music_dir = dir
break
# print the song name
print(song)
# play the song
os.startfile(os.path.join(music_dir, song))

Thanks

I’m sure I got something wrong, because nothing happened. There is no error too. Lastly, may I ask what with songs = []

As for the infinite loop, sorry if I don’t get it. Why is the directory path set to None? Was this part simply an extension to the previous main code above (as it lack the shebang; and import random, os)?

#!/usr/local/Microsoft/WindowsApps/python
import random, os
folder_A = “C:/Users/XXX/Music/YYY”
folder_B= “C:/Users/XXX/Music/ZZZ”
music_dirs = [folder_A, folder_B]
songs =
for music_dir in music_dirs:
songs.extend(os.listdir(music_dir))