python如何随机播放音乐_Python随机播放音乐的代码详解

本文介绍了一种使用Python从硬盘中搜索并随机播放MP3和WMA音乐文件的方法。首先遍历指定磁盘路径寻找音乐文件,然后筛选大小超过1MB的文件以确保是音乐文件,最后通过`random.choice`选取一首音乐并用`os.startfile`播放。
摘要由CSDN通过智能技术生成

就是找到硬盘中所有的MP3文件和wma文件,再随机打开其中的一个。

import os,random

disk=['D','E','F','G','H']

def search_file(filename,search_path,pathsep=os.pathsep):

for path in search_path.split(pathsep):

candidate = os.path.join(path,filename)

if os.path.isfile(candidate):

return os.path.abspath(candidate)

def random_play():

music=[]

found=False

for i in range(0,5):

for dirpath, dirnames, filenames in os.walk(disk[i]+':/'):

for filename in filenames:

if os.path.splitext(filename)[1] == '.mp3':

filepath = os.path.join(dirpath, filename)

if os.path.getsize(filepath)>1048576:#这里是为了防止打开一些非音乐音频,比如游戏配音

music.append(filepath)

found=True

if not found:

for dirpath, dirnames, filenames in os.walk('C:/Users'):

for filename in filenames:

if os.path.splitext(filename)[1] == '.mp3':

filepath = os.path.join(dirpath, filename)

if os.path.getsize(filepath)>1048576:

music.append(filepath)

found=True

if not found:

for i in range(0,5):

for dirpath, dirnames, filenames in os.walk(disk[i]+':/'):

for filename in filenames:

if os.path.splitext(filename)[1] == '.wma':

filepath = os.path.join(dirpath, filename)

if os.path.getsize(filepath)>1048576:

music.append(filepath)

found=True

if not found:

for dirpath, dirnames, filenames in os.walk('C:/Users'):

for filename in filenames:

if os.path.splitext(filename)[1] == '.wma':

filepath = os.path.join(dirpath, filename)

if os.path.getsize(filepath)>1048576:

music.append(filepath)

found=True

random_music=random.choice(music)

os.startfile(random_music)

if not found:

print'没有找到音频文件'

if __name__=='__main__':

random_play()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值