我被我的python音频播放器困住了。我想要做的是在歌曲结束时获取活动,这样我就可以播放下一首歌。我可以切换播放列表文件夹并播放一首歌曲。但是我怎样才能切换到下一个呢?
以下是代码:
import pygame
from pygame.locals import *
import os
import sys
import random
import re
play_stereo = True
songNumber = 0
x = 0
SONG_END = pygame.USEREVENT + 1
pygame.display.set_caption("Pygame Audio player")
screen = pygame.display.set_mode((800, 800), 0, 32)
pygame.init()
def build_file_list():
file_list = []
for root, folders, files in os.walk(folderPath):
folders.sort()
files.sort()
for filename in files:
if re.search(".(aac|mp3|wav|flac|m4a|pls|m3u)$", filename) != None:
file_list.append(os.path.join(root, filename))
return file_list
def play_songs(file_list):
random.shuffle(file_list)
pygame.mixer.music.load(file_list[songNumber])
pygame.mixer.music.play(1)
while True:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_q:
folderPath = "/Users/dimitristeinel/Documents/git projects/pygame audioplayer/playlist1"
files = build_file_list()
play_songs(files)
if event.key == K_w:
folderPath = "/Users/dimitristeinel/Documents/git projects/pygame audioplayer/playlist2"
files = build_file_list()
print(files)
if event.key == K_ESCAPE:
sys.exit()
break
我真的希望有人可以提供帮助。提前谢谢......
答案 0 :(得分:1)
pygame.mixer.music.queue 也有错误,但您可以使用以下类:
mut
如下
import pygame
class PlayList:
playlist_on_play = None
def __init__(self, list_files):
self.list_files = list_files
self.song_num = 0
self.reproducing = False
def play(self):
if PlayList.playlist_on_play is not None:
PlayList.playlist_on_play.stop()
PlayList.playlist_on_play = self
def stop(self):
self.reproducing = False
self.song_num = 0
if PlayList.playlist_on_play is self:
PlayList.playlist_on_play = None
@staticmethod
def check(event):
if PlayList.playlist_on_play is not None:
pl = PlayList.playlist_on_play
if not pl.reproducing: # play first song
pl.play_song(pl.list_files[pl.song_num])
pl.reproducing = True
if event.type == MUSIC_END and pl.song_num < len(pl.list_files)-1: # play rest of songs
pl.song_num += 1
pl.play_song(pl.list_files[pl.song_num])
if event.type == MUSIC_END and pl.song_num == len(pl.list_files)-1: # end playlist
pl.stop()
print("end playlist")
def play_song(self, file):
pygame.mixer.music.load(file)
pygame.mixer.music.play()
对我有用
答案 1 :(得分:0)
使用pygame.mixer.music.queue
。
它排队了一首将在第一首歌结束后开始播放的歌曲:
def play_songs(file_list):
random.shuffle(file_list)
pygame.mixer.music.load(file_list[songNumber])
pygame.mixer.music.play(1)
for num, song in enumerate(file_list):
if num == songNumber:
continue # already playing
pygame.mixer.music.queue(song)