【发布时间】:2020-02-16 15:40:28
【问题描述】:
大家好,我目前正在从事一个项目,但我遇到了这个问题。如何使用 Pygame 从一个文件夹中随机播放 Mp3?这是我的代码。
path = "C:/Users/pc/Desktop/sample_songs/"
mixer.init()
mixer.music.load(path)
mixer.music.play()
【问题讨论】:
大家好,我目前正在从事一个项目,但我遇到了这个问题。如何使用 Pygame 从一个文件夹中随机播放 Mp3?这是我的代码。
path = "C:/Users/pc/Desktop/sample_songs/"
mixer.init()
mixer.music.load(path)
mixer.music.play()
【问题讨论】:
首先,您必须获取目录中以'.mp3' 结尾的所有文件的列表(os.listdir,请参阅os):
import os
path = "C:/Users/pc/Desktop/sample_songs/"
all_mp3 = [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.mp3')]
然后从列表中选择一个随机文件(random.choice,参见random):
import random
randomfile = random.choice(all_mp3)
播放随机文件:
import pygame
pygame.mixer.init()
pygame.mixer.music.load(randomfile)
pygame.mixer.music.play()
小例子:
import os
import random
import pygame
directory = 'music'
play_list = [f for f in os.listdir(directory) if f.endswith('.mp3')]
print(play_list)
current_list = []
pygame.init()
window = pygame.display.set_mode((600, 100))
font = pygame.font.SysFont(None, 40)
clock = pygame.time.Clock()
window_center = window.get_rect().center
title_surf = None
run = True
while run:
clock.tick(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if not pygame.mixer.music.get_busy():
if not current_list:
current_list = play_list[:]
random.shuffle(current_list)
current_song = current_list.pop(0)
pygame.mixer.music.load(os.path.join(directory, current_song))
pygame.mixer.music.play()
title_surf = font.render(current_song, True, (255, 255, 0))
window.fill(0)
if title_surf:
window.blit(title_surf, title_surf.get_rect(center = window_center))
pygame.display.flip()
pygame.quit()
exit()
【讨论】:
您可以使用os.listdir() 获取文件夹中所有文件的列表。然后使用random.choice()随机选择一个文件。
如果目录中的所有文件都是 MP3 文件,你可以这样使用:
import os
import random
path = "C:/Users/pc/Desktop/sample_songs/"
file = os.path.join(path, random.choice(os.listdir(path)))
mixer.init()
mixer.music.load(file)
mixer.music.play()
【讨论】: