请检查代码错误并修正然后将两段代码取其精华融合在一起最后优化代码。代码1:Pythonimport pygameimport osimport threadingfrom collections import dequepygamemixerinitdef get_music_path while True music_folder_path = input请输入音乐文件夹路径
代码错误及修正:
- 代码1中的
play_music函数没有设置循环次数,应该在play_music函数中加入while循环并设置循环次数为1或者-1。
修改后的代码:
def play_music(path):
try:
pygame.mixer.music.load(path)
pygame.mixer.music.play(loops=-1) # 设置循环次数为无限循环
while pygame.mixer.music.get_busy(): # 加入while循环保证音乐不会在播放完后立即停止
pygame.time.Clock().tick(10)
except pygame.error:
print("无法播放该音乐文件!")
- 代码1中的
music_player函数中的playlist应该初始化为deque(paths),而不是deque(names)。
修改后的代码:
def music_player(paths, names):
if not paths:
print("曲库中没有歌曲,请添加后再试!")
return
playlist = deque(paths) # 初始化playlist为deque(paths)
volume = 0.3
current_index = 0
play_music(playlist[current_index])
while True:
print("=" * 50)
print("曲库的歌曲列表为:")
for i, name in enumerate(names):
print(f"{i}: {name}")
print(f"当前正在播放:{names[current_index]}")
print("从键盘上键入以下字符可以执行对应命令,大小写均可:")
print("A/a: 暂停 Q/q: 播放")
print("S/s: 下一曲 W/w: 上一曲")
print("E/e: 增大音量 D/d: 减少音量")
print("空格: 退出程序")
print("=" * 50)
command = input("请输入下一步操作:")
if command in ["q", "Q"]:
print("继续播放音乐")
unpause_music()
elif command in ["a", "A"]:
pause_music()
elif command in ["s", "S"]:
current_index = (current_index + 1) % len(playlist)
stop_music()
play_music(playlist[current_index])
elif command in ["w", "W"]:
current_index = (current_index - 1) % len(playlist)
stop_music()
play_music(playlist[current_index])
elif command in ["e", "E"]:
volume = increase_volume(volume)
elif command in ["d", "D"]:
volume = decrease_volume(volume)
elif command == " ":
print("程序结束!")
stop_music()
return
else:
try:
command = int(command)
if 0 <= command < len(playlist):
current_index = command
stop_music()
play_music(playlist[current_index])
else:
print("输入的序号超出范围,请重新输入!")
except ValueError:
print("输入的指令无效,请重新输入!若要退出,请输入空格后确定。")
- 代码2中的
os.chdir(directory)和song_list = os.listdir()应该写在get_music_path()函数中。
修改后的代码:
def get_music_path():
while True:
music_folder_path = askdirectory()
if os.path.exists(music_folder_path) and os.path.isdir(music_folder_path):
break
else:
print("输入的路径不存在或者不是文件夹,请重新输入!")
os.chdir(music_folder_path) # 切换到音乐文件夹路径
song_list = os.listdir() # 获取音乐文件夹中的文件名列表
paths = []
names = []
for entry in song_list:
if os.path.isfile(entry) and entry.endswith(".mp3"):
paths.append(entry)
names.append(entry.split(".")[0])
return paths, names
- 代码2中的
play_list应该在music_player函数中创建,并将names作为参数传入。
修改后的代码:
def music_player(paths, names):
if not paths:
print("曲库中没有歌曲,请添加后再试!")
return
playlist = deque(paths)
volume = 0.3
current_index = 0
play_music(playlist[current_index])
play_list = t.Listbox(music_player, font="Helvetica 12 bold", bg='SkyBlue1', selectmode=t.SINGLE)
for name in names:
play_list.insert(t.END, name)
play_list.pack(fill="both", expand="yes")
while True:
print("=" * 50)
print("曲库的歌曲列表为:")
for i, name in enumerate(names):
print(f"{i}: {name}")
print(f"当前正在播放:{names[current_index]}")
print("从键盘上键入以下字符可以执行对应命令,大小写均可:")
print("A/a: 暂停 Q/q: 播放")
print("S/s: 下一曲 W/w: 上一曲")
print("E/e: 增大音量 D/d: 减少音量")
print("空格: 退出程序")
print("=" * 50)
command = input("请输入下一步操作:")
if command in ["q", "Q"]:
print("继续播放音乐")
unpause_music()
elif command in ["a", "A"]:
pause_music()
elif command in ["s", "S"]:
current_index = (current_index + 1) % len(playlist)
stop_music()
play_music(playlist[current_index])
elif command in ["w", "W"]:
current_index = (current_index - 1) % len(playlist)
stop_music()
play_music(playlist[current_index])
elif command in ["e", "E"]:
volume = increase_volume(volume)
elif command in ["d", "D"]:
volume = decrease_volume(volume)
elif command == " ":
print("程序结束!")
stop_music()
return
else:
try:
command = int(command)
if 0 <= command < len(playlist):
current_index = command
stop_music()
play_music(playlist[current_index])
else:
print("输入的序号超出范围,请重新输入!")
except ValueError:
print("输入的指令无效,请重新输入!若要退出,请输入空格后确定。")
代码优化:
- 代码中存在重复的代码块,如播放、暂停、停止等函数,可以将其合并为一个函数,通过参数来区分不同的操作。
修改后的代码:
def music_control(action):
if action == "play":
pygame.mixer.music.load(playlist[current_index])
pygame.mixer.music.play(loops=-1)
var.set(song_names[current_index])
elif action == "pause":
pygame.mixer.music.pause()
elif action == "unpause":
pygame.mixer.music.unpause()
elif action == "stop":
pygame.mixer.music.stop()
Button1 = t.Button(music_player, width=5, height=3, font="Helvetica 12 bold", text="播放", command=lambda: music_control("play"), bg="SeaGreen1", fg="white")
Button2 = t.Button(music_player, width=5, height=3, font="Helvetica 12 bold", text="停止", command=lambda: music_control("stop"), bg="red", fg="white")
Button3 = t.Button(music_player, width=5, height=3, font="Helvetica 12 bold", text="暂停", command=lambda: music_control("pause"), bg="Orchid1", fg="white")
Button4 = t.Button(music_player, width=5, height=3, font="Helvetica 12 bold", text="取消暂停", command=lambda: music_control("unpause"), bg="Yellow4", fg="white")
- 代码中存在重复的参数,如音乐文件路径和音乐文件名列表,可以将其合并为一个参数。
修改后的代码:
def music_player(playlist):
if not playlist:
print("曲库中没有歌曲,请添加后再试!")
return
volume = 0.3
current_index = 0
music_control("play")
play_list = t.Listbox(music_player, font="Helvetica 12 bold", bg='SkyBlue1', selectmode=t.SINGLE)
for name in song_names:
play_list.insert(t.END, name)
play_list.pack(fill="both", expand="yes")
while True:
print("=" * 50)
print("曲库的歌曲列表为:")
for i, name in enumerate(song_names):
print(f"{i}: {name}")
print(f"当前正在播放:{song_names[current_index]}")
print("从键盘上键入以下字符可以执行对应命令,大小写均可:")
print("A/a: 暂停 Q/q: 播放")
print("S/s: 下一曲 W/w: 上一曲")
print("E/e: 增大音量 D/d: 减少音量")
print("空格: 退出程序")
print("=" * 50)
command = input("请输入下一步操作:")
if command in ["q", "Q"]:
print("继续播放音乐")
music_control("unpause")
elif command in ["a", "A"]:
music_control("pause")
elif command in ["s", "S"]:
current_index = (current_index + 1) % len(playlist)
music_control("stop")
music_control("play")
elif command in ["w", "W"]:
current_index = (current_index - 1) % len(playlist)
music_control("stop")
music_control("play")
elif command in ["e", "E"]:
volume = increase_volume(volume)
elif command in ["d", "D"]:
volume = decrease_volume(volume)
elif command == " ":
print("程序结束!")
music_control("stop")
return
else:
try:
command = int(command)
if 0 <= command < len(playlist):
current_index = command
music_control("stop")
music_control("play")
else:
print("输入的序号超出范围,请重新输入!")
except ValueError:
print("输入的指令无效,请重新输入!若要退出,请输入空格后确定。")
if __name__ == "__main__":
music_paths, song_names = get_music_path()
print('''
************************************************
* 欢迎来到潘昱霖出品的专属音乐播放器 *
* 潘昱霖出品,必属精品 *
************************************************
''')
music_player(music_paths)
- 代码中存在重复的代码块,如播放音乐和获取音乐路径,可以将其封装成函数,提高代码的复用性。
修
原文地址: http://www.cveoy.top/t/topic/guUK 著作权归作者所有。请勿转载和采集!