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/Desk
Solution 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()
Solution 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()
Post a Comment for "How To Play Random Mp3 Files In Pygame"