Python隨機播放音樂的代碼
就是找到硬盤中所有的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()
本文由用戶 cdfd 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!