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?
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))
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))