python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python音乐播放器

Python开发简易音乐播放器的示例详解

作者:笨笨轻松熊

这篇文章主要为大家详细介绍了如何使用Python开发一个具有基本功能的音乐播放器,并解析其中涉及的Python编程知识点,感兴趣的小伙伴可以了解下

开发环境准备-音乐获取

从酷狗音乐中单个获取,需要先登录

import requests
import json
headers = {
    'accept': '*/*',
    'accept-language': 'zh-CN,zh;q=0.9',
    'cache-control': 'no-cache',
    'origin': 'https://www.kugou.com',
    'pragma': 'no-cache',
    'priority': 'u=1, i',
    'referer': 'https://www.kugou.com/',
    'sec-ch-ua': '"Chromium";v="136", "Google Chrome";v="136", "Not.A/Brand";v="99"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'empty',
    'sec-fetch-mode': 'cors',
    'sec-fetch-site': 'same-site',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36',
}

params = {
    'srcappid': '2919',
    'clientver': '20000',
    'clienttime': '1748689562754',
    'mid': '9c90f73615e8fc1dee91f84b68332ed8',
    'uuid': '9c90f73615e8fc1dee91f84b68332ed8',
    'dfid': '1Jbra41JOyPa2zrk752ps3YA',
    'appid': '1014',
    'platid': '4',
    'encode_album_audio_id': 'bwnubuc3',
    'token': '0837e5097e56fabd6e9164d753b05b7c073a6a393bf34fb687bd69cf80d623e8',
    'userid': '660825514',
    'signature': '63e40caebe53219e46622202bc5112a1',
}
# 获取内容
response = requests.get('https://wwwapi.kugou.com/play/songinfo', params=params, headers=headers).text
data = json.loads(response) # 转换成json格式
res = requests.get(data['data']['play_url'], headers=headers) # 再次发起请求,获取音乐
# 标题
title = data['data']['audio_name']
with open(f'{title}.mp3', 'wb') as f:
    f.write(res.content)
    print("下载完成")
    f.close()

那么单个音乐就下载好了菲菲公主(陆绮菲) - 第57次取消发送.mp3

核心功能概述

音乐文件选择:允许用户从文件系统中选择音乐文件

播放控制:播放、暂停、停止、调整音量

播放列表管理:添加、删除、显示音乐文件

界面显示:简洁的图形用户界面

代码实现与知识点解析

1. 导入必要的库

import pygame
import tkinter as tk
from tkinter import filedialog, messagebox
import os
import time
from threading import Thread

知识点:

2. 初始化pygame和音频系统

# 初始化pygame
pygame.init()
# 初始化音频系统
pygame.mixer.init()

知识点:

3. 创建音乐播放器类

class MusicPlayer:
    def __init__(self, root):
        self.root = root
        self.root.title("Python简易音乐播放器")
        self.root.geometry("500x400")
        self.root.resizable(False, False)
        self.root.configure(bg="#f0f0f0")

        # 音乐播放状态
        self.is_playing = False
        self.current_track = None
        self.playlist = []

        # 创建界面
        self.create_ui()
        
        # 更新播放状态的线程
        self.update_thread = Thread(target=self.update_play_state)
        self.update_thread.daemon = True
        self.update_thread.start()

知识点:

4. 创建用户界面

def create_ui(self):
    # 标题标签
    self.title_label = tk.Label(self.root, text="Python简易音乐播放器", font=("Arial", 16), bg="#f0f0f0")
    self.title_label.pack(pady=10)
    
    # 当前播放标签
    self.current_label = tk.Label(self.root, text="当前未播放任何音乐", font=("Arial", 10), bg="#f0f0f0", width=45)
    self.current_label.pack(pady=5)
    
    # 播放列表框
    self.listbox_frame = tk.Frame(self.root)
    self.listbox_frame.pack(pady=5)
    
    self.playlist_box = tk.Listbox(self.listbox_frame, width=60, height=10)
    self.playlist_box.pack(side=tk.LEFT, fill=tk.BOTH)
    
    self.scrollbar = tk.Scrollbar(self.listbox_frame)
    self.scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
    
    self.playlist_box.config(yscrollcommand=self.scrollbar.set)
    self.scrollbar.config(command=self.playlist_box.yview)
    
    # 播放控制按钮框
    self.control_frame = tk.Frame(self.root, bg="#f0f0f0")
    self.control_frame.pack(pady=10)
    
    # 播放按钮
    self.play_button = tk.Button(self.control_frame, text="播放", width=8, command=self.play_music)
    self.play_button.grid(row=0, column=0, padx=5)
    
    # 暂停按钮
    self.pause_button = tk.Button(self.control_frame, text="暂停", width=8, command=self.pause_music)
    self.pause_button.grid(row=0, column=1, padx=5)
    
    # 停止按钮
    self.stop_button = tk.Button(self.control_frame, text="停止", width=8, command=self.stop_music)
    self.stop_button.grid(row=0, column=2, padx=5)
    
    # 添加音乐按钮
    self.add_button = tk.Button(self.control_frame, text="添加音乐", width=8, command=self.add_music)
    self.add_button.grid(row=0, column=3, padx=5)
    
    # 删除音乐按钮
    self.remove_button = tk.Button(self.control_frame, text="删除音乐", width=8, command=self.remove_music)
    self.remove_button.grid(row=0, column=4, padx=5)
    
    # 音量控制框
    self.volume_frame = tk.Frame(self.root, bg="#f0f0f0")
    self.volume_frame.pack(pady=5)
    
    self.volume_label = tk.Label(self.volume_frame, text="音量:", bg="#f0f0f0")
    self.volume_label.grid(row=0, column=0, padx=5)
    
    self.volume_scale = tk.Scale(self.volume_frame, from_=0, to=100, orient=tk.HORIZONTAL, command=self.set_volume)
    self.volume_scale.set(70)  # 默认音量70%
    self.volume_scale.grid(row=0, column=1, padx=5)
    
    # 设置初始音量
    pygame.mixer.music.set_volume(0.7)
    
    # 双击播放
    self.playlist_box.bind("<Double-1>", self.play_selected)

知识点:

5. 音乐播放控制功能

def add_music(self):
    """添加音乐到播放列表"""
    file_paths = filedialog.askopenfilenames(
        title="选择音乐文件",
        filetypes=(("音频文件", "*.mp3 *.wav *.ogg"), ("所有文件", "*.*"))
    )
    
    for path in file_paths:
        if path:
            # 获取文件名
            filename = os.path.basename(path)
            self.playlist.append(path)
            self.playlist_box.insert(tk.END, filename)

def remove_music(self):
    """从播放列表中删除选中的音乐"""
    try:
        selected_index = self.playlist_box.curselection()[0]
        self.playlist_box.delete(selected_index)
        self.playlist.pop(selected_index)
        
        # 如果删除的是正在播放的曲目,则停止播放
        if self.current_track == selected_index:
            self.stop_music()
            self.current_track = None
    except IndexError:
        messagebox.showinfo("提示", "请先选择要删除的音乐")

def play_selected(self, event=None):
    """播放选中的音乐"""
    try:
        selected_index = self.playlist_box.curselection()[0]
        self.play_music(selected_index)
    except IndexError:
        messagebox.showinfo("提示", "请先选择要播放的音乐")

def play_music(self, index=None):
    """播放音乐"""
    if not self.playlist:
        messagebox.showinfo("提示", "播放列表为空,请先添加音乐")
        return
        
    # 如果指定了索引,则播放指定音乐
    if index is not None:
        self.current_track = index
    # 否则,如果当前没有播放,则播放选中的或第一首
    elif self.current_track is None:
        try:
            self.current_track = self.playlist_box.curselection()[0]
        except IndexError:
            self.current_track = 0
    
    # 加载并播放音乐
    try:
        pygame.mixer.music.load(self.playlist[self.current_track])
        pygame.mixer.music.play()
        self.is_playing = True
        
        # 更新当前播放标签
        current_file = os.path.basename(self.playlist[self.current_track])
        self.current_label.config(text=f"当前播放: {current_file}")
        
        # 高亮显示当前播放的曲目
        self.playlist_box.selection_clear(0, tk.END)
        self.playlist_box.selection_set(self.current_track)
        self.playlist_box.activate(self.current_track)
        self.playlist_box.see(self.current_track)
    except pygame.error:
        messagebox.showerror("错误", "无法播放所选音乐文件")
        self.current_track = None

def pause_music(self):
    """暂停/恢复音乐播放"""
    if self.is_playing:
        pygame.mixer.music.pause()
        self.is_playing = False
        self.pause_button.config(text="恢复")
    else:
        pygame.mixer.music.unpause()
        self.is_playing = True
        self.pause_button.config(text="暂停")

def stop_music(self):
    """停止音乐播放"""
    pygame.mixer.music.stop()
    self.is_playing = False
    self.current_label.config(text="当前未播放任何音乐")
    self.pause_button.config(text="暂停")

def set_volume(self, val):
    """设置音量"""
    volume = float(val) / 100
    pygame.mixer.music.set_volume(volume)

def update_play_state(self):
    """更新播放状态(在后台线程中运行)"""
    while True:
        if self.is_playing and not pygame.mixer.music.get_busy():
            # 当前歌曲播放完毕,播放下一首
            self.root.after(100, self.play_next)
        time.sleep(0.1)

def play_next(self):
    """播放下一首音乐"""
    if not self.playlist:
        return
        
    if self.current_track is not None and self.current_track < len(self.playlist) - 1:
        self.current_track += 1
        self.play_music(self.current_track)
    else:
        # 播放列表结束,停止播放
        self.stop_music()
        self.current_track = None

知识点:

6. 主程序入口

def main():
    # 创建主窗口
    root = tk.Tk()
    # 创建音乐播放器实例
    app = MusicPlayer(root)
    # 运行主循环
    root.mainloop()
    
    # 退出时清理资源
    pygame.mixer.quit()
    pygame.quit()

if __name__ == "__main__":
    main()

效果图

从中添加音乐,就可以直接播放了,当然,可以打包成一个自己的播放器

总结

通过这个简易音乐播放器项目,我们学习了以下Python编程知识:

到此这篇关于Python开发简易音乐播放器的示例详解的文章就介绍到这了,更多相关Python音乐播放器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文