Skip to content

Instantly share code, notes, and snippets.

@maride
Created April 14, 2014 13:34
Show Gist options
  • Save maride/10648356 to your computer and use it in GitHub Desktop.
Save maride/10648356 to your computer and use it in GitHub Desktop.
Python. Randomly plays music files off a directory, randomly. Awesome im combination with a Raspberry Pi and a car :)
import os,random,time,sys
mp3s = []
mediapath = "/media/Music"
for path,directory,element in os.walk(mediapath,False):
print("Loading music from" + path + "...")
tmparray = element
for i in range(0,len(tmparray)-1):
if(tmparray[i][-3:] == "mp3" and tmparray[i][:1] != "."):
mp3s.append(tmparray[i])
else:
print("Unuseable:",tmparray[i])
print("Loaded" + str(len(mp3s)) + "files, of" + str(len(element)) + "total")
random.shuffle(mp3s)
for i in range(0,len(tmparray)-1):
print(mp3s[i])
os.system("mpg123 '" + mediapath + mp3s[i] + "'")
time.sleep(1)
@shiv19july
Copy link

shiv19july commented Sep 21, 2020

        music_dir = "C:\\Users\\Aarav\\Downloads\\Python\\Jarvis\\Jarvis1\\songs\\"  
        files = os.listdir(music_dir)
        music = random.choice(files)
        os.startfile(os.path.join(music_dir, music))

this will work in python 3.8.5
I have tested it

@thomasdilts
Copy link

thomasdilts commented Nov 2, 2020

I know this entry is old as the hills but it is still useful! Thanks for sharing. Since my music can be in very complex directory structures the following code changes worked best for me.

import glob,os,random,time,sys

mediapath = "/media/thomas/CORSAIR/Music/"
# mediapath needs a trailing slash (i.e. /root/dir/)

mp3s = []
for filename in glob.iglob(mediapath + '**/*.mp3', recursive=True):
	mp3s.append(filename)
random.shuffle(mp3s)
for i in range(0,len(mp3s)-1):
	print(mp3s[i])
	os.system("play '" + mp3s[i] + "'")
	time.sleep(1)

@suhasbhoir
Copy link

Thanks for sharing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment