问题描述:

I'm making GUI music player using PyQt and I'm almost done exept that when i play the music when it is done the next music don't play automatically so how to it and this is the code

def playMusic():

global counter,music

counter += 1

pygame.mixer.init()

pygame.mixer.music.load(music_folder + "/" + music[counter])

pygame.mixer.music.play()

print 'playing ' + music[counter]

网友答案:

I don't have much experience with PyQt but if you know how long the music is, just do something like this:

import time  # Type this somewhere near the top of your program
  .
  .
  .       
x = 9001  # define this variable somewhere, it should be the length of your song in seconds
  .
  .
  .
while True: # infinite loop

    if not playing:  # if the song isn't already playing, 
        playMusic()  # start the song
        playing = True

    else:
        time.Sleep(x)     
        playing = False

If you want to be able to pause the song while it's playing, you may need to change your function playMusic() to something like this:

def playMusic(counter):    # add counter argument, remove "counter += 1"
    global counter,music
    pygame.mixer.init() 
    pygame.mixer.music.load(music_folder + "/" + music[counter])
    pygame.mixer.music.play()
    print 'playing ' + music[counter]

And then add to the counter variable outside of the function. Place your song lengths (in seconds) in the x variable somewhere above the loop:

x = (9001, 21, 1337, 711)
  .
  .
  .
while not paused: # stop if it's paused

    if playing:  
        time.Sleep(1) 
        songtime += 1      # if the song is playing, count the seconds until it's over
        if songtime >= x[counter]:
            playing = False

    else:
        playMusic(counter)       # start the song if it's not playing
        playing = True 
        counter += 1
相关阅读:
Top