简体   繁体   English

如何在 Pygame 中播放随机 Mp3 文件

[英]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?如何使用 Pygame 从一个文件夹中随机播放 Mp3? here is my code.这是我的代码。

path = "C:/Users/pc/Desktop/sample_songs/"
mixer.init()
mixer.music.load(path)
mixer.music.play()

First you have to get a list of all the files which ends with '.mp3' in the directory ( os.listdir , see os ):首先,您必须获得目录中以'.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')]

then select a random file from the list ( random.choice , see random ):然后从列表中选择一个随机文件( random.choice ,参见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()

You can use os.listdir() to get a list of all files in a folder.您可以使用os.listdir()获取文件夹中所有文件的列表。 Then use random.choice() to choose a random file.然后使用random.choice()选择一个随机文件。

If all files in the directory are MP3 files, you could use something like this:如果目录中的所有文件都是 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM