以下是一个使用 Python 制作的简单音乐播放器项目示例,适合音乐爱好者和 Python 初学者学习参考。

import os
from playsound import playsound

def print_menu():
    print('1. 播放音乐')
    print('2. 停止音乐')
    print('3. 退出程序')

def play_music():
    music_folder = './music'  # 音乐文件夹路径
    music_files = os.listdir(music_folder)  # 获取文件夹中的音乐文件
    if len(music_files) == 0:
        print('音乐文件夹中没有音乐文件!')
        return
    
    print('音乐列表:')
    for i, music_file in enumerate(music_files):
        print(f'{i+1}. {music_file}')

    choice = input('请选择要播放的音乐编号:')
    if not choice.isdigit() or int(choice) < 1 or int(choice) > len(music_files):
        print('无效的选择!')
        return
    
    music_path = os.path.join(music_folder, music_files[int(choice)-1])
    print(f'正在播放音乐:{music_files[int(choice)-1]}')
    playsound(music_path)

def stop_music():
    playsound(None)

def main():
    while True:
        print_menu()
        choice = input('请输入选项:')
        
        if choice == '1':
            play_music()
        elif choice == '2':
            stop_music()
        elif choice == '3':
            break
        else:
            print('无效的选项!')

if __name__ == '__main__':
    main()

此示例使用了playsound库来播放音乐。首先,用户可以选择播放音乐、停止音乐或退出程序。如果选择播放音乐,则程序将列出音乐文件夹中的音乐文件列表,并要求用户选择要播放的音乐。然后,程序将使用playsound库播放所选音乐。如果选择停止音乐,则程序将停止当前正在播放的音乐。如果选择退出程序,则程序将终止循环并退出。

Python 音乐播放器项目:简单易懂的入门指南

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

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