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

使用Python编写的简单音乐播放器

发布时间:2023-12-04 15:03:31

下面是一个使用Python编写的简单音乐播放器的代码示例:

import pygame
import os

class MusicPlayer:
    def __init__(self):
        pygame.init()
        pygame.mixer.init()

    def play(self, file):
        pygame.mixer.music.load(file)
        pygame.mixer.music.play()

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

    def resume(self):
        pygame.mixer.music.unpause()

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

if __name__ == "__main__":
    player = MusicPlayer()
    
    while True:
        print("1. 播放音乐")
        print("2. 暂停音乐")
        print("3. 继续播放音乐")
        print("4. 停止音乐")
        print("5. 退出程序")

        choice = input("请输入您的选择:")

        if choice == "1":
            file = input("请输入音乐文件的路径:")
            if os.path.exists(file):
                player.play(file)
            else:
                print("文件不存在!")
        elif choice == "2":
            player.pause()
        elif choice == "3":
            player.resume()
        elif choice == "4":
            player.stop()
        elif choice == "5":
            break
        else:
            print("无效的选择!")

使用这个简单的音乐播放器,你可以选择播放、暂停、继续播放和停止音乐。它使用pygame库来实现音乐的播放功能。

运行程序后,你将看到一个菜单,可以根据输入选择功能。如果选择播放音乐,则需要输入音乐文件的路径。程序将检查文件是否存在,如果存在,则播放音乐;否则,会显示文件不存在的消息。

你可以使用任何音乐文件进行测试,只需提供正确的文件路径即可。