user3570933
user3570933

Reputation: 35

Music player for Python not working

I want to be able to play multiple songs through a playlist using python, but it will only play the last song on the list. Please help.

from pygame import mixer # Load the required library
from os import listdir
k = listdir('C:/LOCAL')
print(k)
mixer.init()
for x in k:
    y = "C:/LOCAL/" + x
    print y
    mixer.music.queue(y)
    mixer.music.load(y)
    mixer.music.play()

Upvotes: 1

Views: 267

Answers (1)

Lyrenhex
Lyrenhex

Reputation: 92

Your problem is that you assume that playing music with pygame will pause the program until the music is finished - which is not the case. As a result, it tries starting a song, and then it's starting another, and another, etc.

There are a few ways of trying to correct this. You could either:

  1. Use pygame events and "tell" pygame to fire an event when the song finishes (though this requires a display surface (window) to be opened within pygame), or
  2. Detect the length of the song, and sleep for that amount of time (which is more compatible with your current code).

I'm going to assume that you would like to do option 2, since your code works better with it.

To get the length of an MP3 file (I've not tried it with any other types), you could use the Mutagen library.

Some example code to get the length of an MP3 file (in seconds):

from mutagen.mp3 import MP3
tracklength = MP3("/path/to/song.mp3").info.length

Then you could substitute the path with y, and time.sleep for the amount of time returned, before continuing to the next iteration of the loop.

Hope that helps.

(also, you don't need to queue a file before loading it - just load and play)

Upvotes: 2

Related Questions