代码错误:

  1. welcome()函数中,musicpath未定义,应该将其作为参数传入该函数。
  2. musicselect()函数中,未判断pathname列表是否为空,如果为空则会出现错误。
  3. musicselect()函数中,当输入数字选择歌曲时,可能会出现输入非数字的情况,需要用异常处理来避免程序崩溃。

代码优化:

  1. musiclujing()函数中,可以使用列表生成式来简化代码。
  2. musicselect()函数中,可以将一些重复的代码封装成函数来避免重复编写。

优化后的代码如下:

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 = [os.path.join(musicfolderpath, file) for file in os.listdir(musicfolderpath) if not os.path.isdir(os.path.join(musicfolderpath, 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

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 in range(len(name)):
            print("                    ", end="")
            print(str(r) + ":" + name[r])
        print("        ************************************************")

        print("当前正在播放的是:", name[i])
        n = input('请输入下一步操作哦:')
        if n in ["q", "Q"]:
            print('继续播放音乐')
            unpause_music()
        elif n in ["a", "A"]:
            pause_music()
        elif n in ["s", "S"]:
            i = next_music(path, i)
        elif n in ["w", "W"]:
            i = prev_music(path, i)
        elif n in ["e", "E"]:
            j = increase_volume(j)
        elif n in ["d", "D"]:
            j = decrease_volume(j)
        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)
``
请检查代码错误并修正然后优化代码。Pythonimport pygameimport ospygamemixerinitdef musiclujing while True musicfolderpath = input请输入音乐文件夹目录: if ospathexistsmusicfolderpath and ospathisdirmusicfolderpath

原文地址: https://www.cveoy.top/t/topic/gt6Y 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录