How to play random Mp3 files in Pygame

房东的猫 提交于 2021-02-02 09:40:30

问题


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()

回答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()



回答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()


来源:https://stackoverflow.com/questions/60250171/how-to-play-random-mp3-files-in-pygame

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!