📚 前言
編程基礎第一期《12-30》–音樂播放器是日常生活中常用的應用程序,使用Python和pygame庫可以輕松實現一個簡易的音樂播放器。本教程將詳細講解如何開發一個具有基本功能的音樂播放器,并解析其中涉及的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
請求頭如何獲取在Python爬蟲實戰:抓取百度15天天氣預報數據-CSDN博客這篇文章中講過了
- pygame庫
- tkinter庫(Python標準庫,用于GUI界面)
安裝pygame庫:
pip install pygame
🧩 核心功能概述
- 音樂文件選擇:允許用戶從文件系統中選擇音樂文件
- 播放控制:播放、暫停、停止、調整音量
- 播放列表管理:添加、刪除、顯示音樂文件
- 界面顯示:簡潔的圖形用戶界面
💡 代碼實現與知識點解析
1. 導入必要的庫
import pygame
import tkinter as tk
from tkinter import filedialog, messagebox
import os
import time
from threading import Thread
知識點:
pygame
:Python游戲開發庫,提供音頻處理功能tkinter
:Python標準GUI庫,用于創建圖形界面os
:操作系統接口,用于文件路徑處理threading
:線程管理,用于后臺播放音樂
2. 初始化pygame和音頻系統
# 初始化pygame
pygame.init()
# 初始化音頻系統
pygame.mixer.init()
知識點:
pygame.init()
:初始化所有pygame模塊pygame.mixer.init()
:初始化音頻系統,為音樂播放做準備
3. 創建音樂播放器類
class MusicPlayer:def __init__(self, root):self.root = rootself.root.title("Python簡易音樂播放器")self.root.geometry("500x400")self.root.resizable(False, False)self.root.configure(bg="#f0f0f0")# 音樂播放狀態self.is_playing = Falseself.current_track = Noneself.playlist = []# 創建界面self.create_ui()# 更新播放狀態的線程self.update_thread = Thread(target=self.update_play_state)self.update_thread.daemon = Trueself.update_thread.start()
知識點:
- 類的定義與初始化:面向對象編程
- GUI窗口配置:設置標題、大小、背景色
- 線程使用:創建后臺線程監控播放狀態
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)
知識點:
- tkinter布局管理:pack、grid布局方式
- 控件使用:Label、Button、Listbox、Scrollbar、Scale等
- 事件綁定:將雙擊事件綁定到播放功能
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 = Noneexcept 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 = Nonedef pause_music(self):"""暫停/恢復音樂播放"""if self.is_playing:pygame.mixer.music.pause()self.is_playing = Falseself.pause_button.config(text="恢復")else:pygame.mixer.music.unpause()self.is_playing = Trueself.pause_button.config(text="暫停")def stop_music(self):"""停止音樂播放"""pygame.mixer.music.stop()self.is_playing = Falseself.current_label.config(text="當前未播放任何音樂")self.pause_button.config(text="暫停")def set_volume(self, val):"""設置音量"""volume = float(val) / 100pygame.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:returnif self.current_track is not None and self.current_track < len(self.playlist) - 1:self.current_track += 1self.play_music(self.current_track)else:# 播放列表結束,停止播放self.stop_music()self.current_track = None
知識點:
- 文件對話框:使用
filedialog
選擇音樂文件 - 音樂控制:使用pygame.mixer.music控制音樂播放
- 異常處理:使用try/except處理可能的錯誤
- 線程同步:使用after方法在主線程中執行函數
- 事件驅動編程:基于用戶操作觸發相應功能
6. 主程序入口
def main():# 創建主窗口root = tk.Tk()# 創建音樂播放器實例app = MusicPlayer(root)# 運行主循環root.mainloop()# 退出時清理資源pygame.mixer.quit()pygame.quit()if __name__ == "__main__":main()
效果圖
從中添加音樂,就可以直接播放了,當然,可以打包成一個自己的播放器
📝 總結
通過這個簡易音樂播放器項目,我們學習了以下Python編程知識:
- pygame庫的音頻處理功能
- tkinter GUI編程
- 多線程編程
- 事件驅動編程模型
- 文件操作和路徑處理
- 面向對象編程思想
- 異常處理
心平能愈三千疾 , 心靜可通萬事理
魚不與鳥比翱翔 , 鳥不與魚比暢游