Member Avatar for leegeorg07

i have made a simple music player that will randomly choose a song from the list (music)
how can i expand this to a whole directory of music without having to make a list with them all in
heres the code:

import webbrowser, random
music = [#music was here]
while 1:
	choice = float(raw_input("Press 1 to play a new song"))
	if choice == 1:
		song = random.choice(music)
		webbrowser.open(song)

Recommended Answers

All 3 Replies

I think Python cannot pick a random file in a directory. If that is the question....
Maybe you can walk through the files, and after a random time you play the current music. But that does not make much sense for me.

Is the music directory too large?

I would recommend a more straightforward method, first without recursion.

import webbrowser, random
import os
import os.path
DIR="your directory containing mp3- files"
music = filter(lambda x: x.lower().endswith("mp3"),os.listdir(DIR))
while 1:
    choice = int(raw_input("Press 1 to play a new song"))
    if choice == 1:
        song = random.choice(music)
        webbrowser.open(os.path.join(DIR,song))

Isn't file list a string? Then I guess it should be able to play that. But here is the way I suggest, instead of using directly file names, use indices and random module:
1. Load all paths into list
2. Load random module
3. After music has ended, use random module to select a random index
4. play the file whose index is chosen

here is the random module issue

http://www.google.co.tz/search?q=python+random+module&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-GB:official&client=firefox-a

Member Avatar for leegeorg07

thanks it worked but i needed to add

music = list(music)

otherwise it was a string like estevemd said

this is my code now

import webbrowser, random
import os
import os.path
DIR="C:/Documents and Settings/Owner/My Documents/georges poopy/main music"
music = filter(lambda x: x.lower().endswith("mp3"),os.listdir(DIR))
music = list(music)
while 1:
    choice = int(raw_input("Press 1 to play a new song"))
    if choice == 1:
        song = random.choice(music)
        webbrowser.open(os.path.join(DIR,song))
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.