欢迎访问宙启技术站
智能推送

使用Python实现的简单音乐播放器

发布时间:2023-12-04 18:19:43

以下是使用Python实现的简单音乐播放器的代码:

import pygame
from tkinter.filedialog import askdirectory
import os

# 初始化
pygame.init()

# 设置窗口属性
window = pygame.display.set_mode((400, 400))
pygame.display.set_caption("Music Player")

# 设置图标
icon = pygame.image.load("music_icon.png")
pygame.display.set_icon(icon)

# 初始化音乐模块
pygame.mixer.init()


def play_music(music_file):
    pygame.mixer.music.load(music_file)
    pygame.mixer.music.play()


def stop_music():
    pygame.mixer.music.stop()


def pause_music():
    pygame.mixer.music.pause()


def resume_music():
    pygame.mixer.music.unpause()


# 选择文件夹
def choose_directory():
    directory = askdirectory()
    os.chdir(directory)

    # 遍历文件夹下所有音乐文件
    for file in os.listdir(directory):
        if file.endswith(".mp3"):
            play_music(file)


# 游戏循环
run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    # 背景颜色
    window.fill((0, 0, 0))

    # 添加按钮
    pygame.draw.rect(window, (255, 0, 0), (50, 50, 100, 50)) # 播放
    pygame.draw.rect(window, (0, 255, 0), (50, 150, 100, 50)) # 暂停
    pygame.draw.rect(window, (0, 0, 255), (50, 250, 100, 50)) # 停止
    pygame.draw.rect(window, (255, 255, 0), (50, 350, 300, 50)) # 选择文件夹

    # 添加文字
    font = pygame.font.Font("freesansbold.ttf", 16)
    play_text = font.render("Play", True, (255, 255, 255))
    window.blit(play_text, (75, 65))
    pause_text = font.render("Pause", True, (255, 255, 255))
    window.blit(pause_text, (65, 165))
    stop_text = font.render("Stop", True, (255, 255, 255))
    window.blit(stop_text, (70, 265))
    choose_folder_text = font.render("Choose Folder", True, (255, 255, 255))
    window.blit(choose_folder_text, (55, 365))

    # 鼠标点击事件
    mouse_pos = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    if click[0]:
        # 播放按钮被点击
        if 50 < mouse_pos[0] < 150 and 50 < mouse_pos[1] < 100:
            play_music("music.mp3")

        # 暂停按钮被点击
        if 50 < mouse_pos[0] < 150 and 150 < mouse_pos[1] < 200:
            pause_music()

        # 停止按钮被点击
        if 50 < mouse_pos[0] < 150 and 250 < mouse_pos[1] < 300:
            stop_music()

        # 选择文件夹按钮被点击
        if 50 < mouse_pos[0] < 350 and 350 < mouse_pos[1] < 400:
            choose_directory()

    pygame.display.update()

# 退出游戏
pygame.quit()

使用示例:

1. 将上述代码保存为music_player.py文件,并将music_icon.pngmusic.mp3文件放在同一目录下。

2. 打开命令行或终端,定位到代码所在的目录,并运行以下命令启动音乐播放器:

   python music_player.py
   

3. 单击按钮来控制音乐播放器的功能:

- 单击播放按钮,音乐将开始播放。

- 单击暂停按钮,音乐将暂停播放。

- 单击停止按钮,音乐将停止播放。

- 单击选择文件夹按钮,将弹出一个文件夹选择窗口,选择包含音乐文件的文件夹,然后播放器将循环播放该文件夹下的所有音乐文件。

请注意,以上示例中使用的音乐文件music.mp3仅作为演示目的,你可以将其替换为你自己的音乐文件。另外,你还可以根据自己的需要修改代码以实现更多功能。