'How to play random Mp3 files in Pygame
hi everyone i'm currently working on a project and i'm stuck with this problem. how can i randomly play Mp3 from one folder using Pygame? here is my code.
path = "C:/Users/pc/Desktop/sample_songs/"
mixer.init()
mixer.music.load(path)
mixer.music.play()
Solution 1:[1]
First you have to get a list of all the files which ends with '.mp3' in the directory (os.listdir, see 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')]
then select a random file from the list (random.choice, see random):
import random
randomfile = random.choice(all_mp3)
Play the random file:
import pygame
pygame.mixer.init()
pygame.mixer.music.load(randomfile)
pygame.mixer.music.play()
Minimal example:
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()
Solution 2:[2]
You can use os.listdir() to get a list of all files in a folder. Then use random.choice() to choose a random file.
If all files in the directory are MP3 files, you could use something like this:
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()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Maximouse |
