请检查代码错误并修正然后优化代码。Pythonimport pygameimport osfrom collections import dequepygamemixerinitdef get_music_path while True music_folder_path = input请输入音乐文件夹路径: if ospathexistsmusic_folder
修改后的代码如下:
import pygame
import os
from collections import deque
pygame.mixer.init()
def get_music_path():
while True:
music_folder_path = input("请输入音乐文件夹路径:")
if os.path.exists(music_folder_path) and os.path.isdir(music_folder_path):
break
else:
print("输入的路径不存在或者不是文件夹,请重新输入!")
paths = []
names = []
for entry in os.scandir(music_folder_path):
if entry.is_file() and entry.name.endswith(".mp3"):
paths.append(entry.path)
names.append(entry.name)
return paths, names
def play_music(path):
pygame.mixer.music.load(path)
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 increase_volume(volume):
volume = min(1.0, volume + 0.1)
pygame.mixer.music.set_volume(volume)
return volume
def decrease_volume(volume):
volume = max(0.0, volume - 0.1)
pygame.mixer.music.set_volume(volume)
return volume
def music_player(paths, names):
if not paths:
print("曲库中没有歌曲,请添加后再试!")
return
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("输入的指令无效,请重新输入!若要退出,请输入空格后确定。")
if __name__ == "__main__":
music_paths, music_names = get_music_path()
print('''
************************************************
* 欢迎来到潘昱霖出品的专属音乐播放器 *
* 潘昱霖出品,必属精品 *
************************************************
''')
music_player(music_paths, music_names)
错误原因:with 语句需要一个上下文管理器,而 pygame.mixer.music 对象并不是一个上下文管理器,所以会报错。
修正方法:将 with pygame.mixer.music: 改为 pygame.mixer.music.load(path),pygame.mixer.music.play(loops=-1) 单独使用,不需要包在 with 语句中。同时,在切换歌曲时,需要先停止当前歌曲再播放下一首歌曲
原文地址: https://www.cveoy.top/t/topic/guG7 著作权归作者所有。请勿转载和采集!