Question

I'm playing ogg sound files from a list generated from my selected music file directory. For some reason the first song is skipped and it plays starting from the second song. For some reason it plays a split second of the first song occasionally which leads me to believe there's an issue on how I'm trying to queue the songs from a list in a loop but I can't seem to fix it.

import pygame
import sys
import os
from pygame.locals import * 
surface = pygame.display.set_mode((640, 480))
musicDir = "/Users/user/Desktop/Dat Sound/Music/"
x = os.listdir(musicDir)
del(x[0]) # Deleting first element because it's DS Store file (Mac)
print x # The list is ['Bonfire.ogg', 'Voodoo Child.ogg']
n = ''
count = 1
pygame.mixer.init()
for i in range(len(x)):
    n = musicDir + str(x[i])
    print n  
    pygame.mixer.music.load(n)
    pygame.mixer.music.play()
    pygame.mixer.music.queue(musicDir + str(x[i]))
    # I'm queueing the next song in the list of songs from the folder + its location
    print pygame.mixer.music.get_busy() 
    # get_busy returns true for both files but only the second is playing
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
          running = False
Was it helpful?

Solution

It looks like you're loading and playing a song, then queueing it, but then loading and playing the second song on the next iteration of the loop, then queueing it again...

n = musicDir + str(x[i])
pygame.mixer.music.load(n) # so you load the song...
pygame.mixer.music.play()  # then you play it....
pygame.mixer.music.queue(musicDir + str(x[i])) # i hasn't changed, this is the same song 
                                               #  you just loaded and started playing

Then the for loops goes to the next iteration and you do the exact same thing, but with the next song.

Try something like this:

n = musicDir + str[0]   # let's load and play the first song
pygame.mixer.music.load(n)
pygame.mixer.music.play()
for song in x: 
    pygame.mixer.music.queue(musicDir + str(song)) # loop over and queue the rest
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top