Python 音乐播放器代码优化:提高效率和可读性
import pygame
import os
pygame.mixer.init()
def musiclujing():
while True:
musicfolderpath = input("请输入音乐文件夹目录:")
if os.path.exists(musicfolderpath) and os.path.isdir(musicfolderpath):
break
else:
print("输入的路径不存在或者不是文件夹,请重新输入!")
path = [f.path for f in os.scandir(musicfolderpath) if f.is_file()]
name = [os.path.basename(file) for file in path]
return path, name
def welcome(musicpath):
print('''
************************************************
* 欢迎来到潘昱霖出品的专属音乐播放器 *
* 潘昱霖出品,必属精品 *
************************************************
''')
pygame.mixer.music.load(musicpath[0])
pygame.mixer.music.play(loops=-1)
pygame.mixer.music.set_volume(0.3)
def play_music(path, i):
pygame.mixer.music.load(path[i])
pygame.mixer.music.play(loops=-1)
def pause_music():
pygame.mixer.music.pause()
def unpause_music():
pygame.mixer.music.unpause()
def stop_music():
pygame.mixer.music.stop()
def next_music(path, i):
i = (i + 1) % len(path)
play_music(path, i)
return i
def prev_music(path, i):
i = (i - 1 + len(path)) % len(path)
play_music(path, i)
return i
def increase_volume(j):
j = min(1, j + 0.1)
pygame.mixer.music.set_volume(j)
return j
def decrease_volume(j):
j = max(0, j - 0.1)
pygame.mixer.music.set_volume(j)
return j
command_map = {
'q': unpause_music,
'a': pause_music,
's': next_music,
'w': prev_music,
'e': increase_volume,
'd': decrease_volume
}
def musicselect(path, name):
i = 0
j = 0.3
if not path or not name:
print('曲库中没有歌曲,请添加后再试!')
return
while True:
print('''
************************************************
* 从键盘上键入以下字符可以执行对应命令,大小写均可: *
A/a:暂停 Q/q:播放
S/s:下一曲 W/w:上一曲
E/e:增大音量 D/d:减少音量
空格:退出程序
* 直接输入数字: 直接播放对应序号的歌曲 *
------------------------------------------------
''')
print(" 曲库的歌曲列表为:")
for r, song in enumerate(name):
print(" ", end="")
print(str(r) + ":" + song)
print(" ************************************************")
print("当前正在播放的是:", name[i])
n = input('请输入下一步操作哦:')
if n in command_map:
if n == 's' or n == 'w':
i = command_map[n](path, i)
elif n == 'e' or n == 'd':
j = command_map[n](j)
else:
command_map[n]()
elif n == ' ': # 退出程序
print("程序结束!")
stop_music()
return
else:
try:
n = int(n)
if n < 0 or n >= len(path):
print("输入的序号超出范围,请重新输入!")
continue
i = n % len(path)
play_music(path, i)
except ValueError:
print("输入的指令无效,请重新输入!若要退出,请输入空格后确定")
continue
musicpath, musicname = musiclujing()
welcome(musicpath)
musicselect(musicpath, musicname)
优化说明:
-
使用
os.scandir()代替os.listdir()和os.path.join()os.scandir()比os.listdir()更高效,因为它直接返回DirEntry对象,而不是字符串列表,这样可以避免额外的字符串操作。- 使用
f.path获取DirEntry对象的路径,可以直接得到完整的路径,避免了使用os.path.join()连接路径的操作。
-
使用
enumerate()函数遍历列表- 在
musicselect()函数中,使用enumerate(name)可以同时获取列表元素的索引和值,避免了使用额外的循环变量。
- 在
-
使用字典存储命令与函数映射关系
- 将命令与对应函数的映射关系存储在
command_map字典中,这样可以避免使用大量的if语句来判断命令,使代码更加清晰和易于扩展。 - 通过
command_map[n]()就可以调用对应命令的函数。
- 将命令与对应函数的映射关系存储在
优化后的代码更简洁、高效、易于维护。
原文地址: https://www.cveoy.top/t/topic/ovVZ 著作权归作者所有。请勿转载和采集!