1. 程式人生 > 程式設計 >pygame編寫音樂播放器的實現程式碼示例

pygame編寫音樂播放器的實現程式碼示例

1、準備工作

ide:pycharm
python:3.7
三方包:pygame、pyinstaller、mutagen
幾首mp3格式的歌

2、開始

2.1 設計說明

1、包含 上一首、下一首、暫停/播放、快進/快退、顯示當前播放的歌曲名稱、顯示播放進度條
2、使用pygame.mixer
3、隨機播放磁碟某個目錄及其子目錄下的mp3檔案
4、上一首、下一首用隨機選擇choice(list) 實現
5、進度條用按照一定速度移動進度圖片來實現,過程中處理暫停、快進
6、歌曲快進播放用pygame.mixer.music.play(0,d_song_time) 實現
7、暫停用pygame.mixer.music.pause() 實現

8、播放用pygame.mixer.music.unpause() 實現
9、用mutagen.mp3來獲取mp3資訊

2.2 程式碼邏輯

收集某個目錄下的所有mp3

# 收集某個目錄及子目錄下的MP3格式的檔案
# 返回歌曲路徑、歌曲時長
# [['E:\\musics\\Mirror_Yohee_128K.mp3',236],['E:\\musics\\over here_Nobigdyl_128K.mp3',188],['E:\\musics\\塵_薛之謙_128K.mp3',282],['E:\\musics\\aaa\\塵_薛之謙_128K.mp3',282]]
def collect_songs(fidir):
  musics =[]
  for root,dirs,files in os.walk(fidir):
    for file in files:
      tmp =[]
      if file.endswith('mp3'):
        file = os.path.join(root,file)
        song = MP3(file)
        duration = round(song.info.length)
        tmp.append(file)
        tmp.append(duration)
        musics.append(tmp)
  return musics

顯示歌曲名稱

# 把歌曲名字顯示在播放器上
def draw_song_name(music):
  # 取歌曲名
  music_name = music[0].split("\\")[-1]
  # print(music_name)
  wbk_obj = font_obj.render(music_name,True,(0,255,255))
  k_obj = wbk_obj.get_rect()
  k_obj.center = (340,200)
  screen.blit(wbk_obj,k_obj)
  pygame.display.update()

播放歌曲

# 隨機播放一首歌
def sing_a_song(musics):
  # 隨機選擇一首音樂
  music = choice(musics)
  print(type(musics))
  pygame.mixer.music.load(music[0])
  pygame.mixer.music.play()
  print('開始播放:%s -- %s秒'%(music[0],str(music[1])))
  return music

顯示播放進度

# 播放進度顯示
def move(current_time,start_time,pause_duration_time,c_music):
  if pause_end_time == 0 and pause_start_time != 0:
    duration_time = round(pause_start_time - start_time - pause_duration_time)
  else:
    duration_time = round(current_time - start_time - pause_duration_time)
  song_total_time = c_music[1]
  speed = (end_x-begin_x)/song_total_time
  current_x = begin_x + duration_time*speed
  try:
    screen.blit(dian,(current_x,148))
    pygame.display.update()
  except:
    print(current_time)
    print(start_time)
    print(pause_duration_time)
    exit()

快進快退功能

# 快進快退功能
def kuaijin(jindu_x,c_music):
  # 要跳轉到的距離d_x
  d_x = jindu_x - begin_x
  song_total_time = c_music[1]
  # 要跳轉到的時間d_song_time
  d_song_time = round(song_total_time*(d_x/560),1)
  # 將歌曲快進到d_song_time
  pygame.mixer.music.play(0,d_song_time)

畫播放控制元件

# 畫播放控制元件
def draw_kongjian(is_sing,is_pause):
  # 畫進度條
  # 畫一條寬度為2的線,y高度為149,x從40到600,顏色為(0,100,100)
  pygame.draw.line(screen,100),(40,149),(600,2)
  # 畫播放、暫停按鈕
  # 先畫圓邊框,半徑20
  pygame.draw.circle(screen,255),(x + 80,20,2)
  # 畫三角形,開始播放
  pygame.draw.line(screen,(x + 73.7,107.5),93),2) # 豎線
  # 如果正在播放且沒有暫停
  if is_sing and not is_pause:
    # 隱藏三角形
    pygame.draw.line(screen,89,115),(x + 87.3,2)
    pygame.draw.line(screen,2)
    # 顯示第二條豎線
    pygame.draw.line(screen,(x+83.7,2)
  else:
    # 隱藏第二條豎線
    pygame.draw.line(screen,(x + 83.7,2)
    # 顯示三角形
    pygame.draw.line(screen,(x+73.7,(x+87.3,2)

  # 畫上一首按鈕
  pygame.draw.line(screen,(x - 10,110),90),2)
  pygame.draw.line(screen,(x + 10,85),2)

  # 畫下一首按鈕
  pygame.draw.line(screen,(x + 170,(x + 150,2)

主邏輯

1、畫介面
2、如果沒有在播放音樂,播放之
3、如果正在播放音樂,重新整理播放進度
4、點選了上一首的處理
5、點選了暫停/播放的處理
6、點選了下一首的處理
7、快進/快退的處理

while True:
  # 第一步畫背景
  screen.fill((0,0)) # ----------------新新增
  # 第二步新增背景圖片
  bg = pygame.image.load(music_bg)
  screen.blit(bg,0))
  # 第四步,畫控制元件
  draw_kongjian(is_sing,is_pause)

  # print("status:-------" + str(pygame.mixer.music.get_busy()))
  # 如果正在播放音樂,有bug == 當暫停後返回依舊是1
  if pygame.mixer.music.get_busy() == 1:
    is_sing = True
  else:
    is_sing = False

  # 如果沒有在播放音樂
  if not is_sing:
    # 第五步,開始唱歌
    c_music = sing_a_song(musics)
    # 記錄開始播放時間
    start_time = time.time()
    # 暫停時長置為0
    pause_start_time = pause_end_time = pause_duration_time = 0
    # 進度條開始位置重置為40
    begin_x = 40
    # 第六步,顯示歌名
    draw_song_name(c_music)
    # 更改播放狀態
    is_sing = not is_sing
  # 如果正在唱歌
  else:
    # 第六步,顯示歌名
    draw_song_name(c_music)
    current_time = time.time()
    move(current_time,c_music)


  for event in pygame.event.get():
    if event.type == QUIT:
      pygame.quit()
      exit()
    if event.type == MOUSEBUTTONDOWN:
      # 如果點選了滑鼠左鍵,取到當前滑鼠的座標
      pressed_array = pygame.mouse.get_pressed()
      if pressed_array[0] == 1:
        mouse_x,mouse_y = event.pos
        print('點選了左鍵,位置為(%d,%d)'%(mouse_x,mouse_y))
        # 判斷點選了哪個按鈕
        if 80 < mouse_y < 120:
          if x - 5 < mouse_x < x + 15:
            # 點選了上一首
            c_music = sing_a_song(musics)
            is_pause = False
            is_kuaijin = False
            # 記錄開始時間
            start_time = time.time()
            # 暫停時長置為0
            pause_start_time = pause_end_time = pause_duration_time = 0
            # 進度條開始位置置為40
            begin_x = 40
            # 第六步,顯示歌名
            draw_song_name(c_music)
            print('點選了上一首')
          elif x+60 < mouse_x < x+100:
            # 修改是否暫停的狀態
            is_pause = not is_pause
            # 如果沒有暫停
            if not is_pause:
              # 開始播放
              pygame.mixer.music.unpause()
              # 記錄結束暫定時間
              pause_end_time = time.time()
              # 計算暫停時長
              pause_duration_time = pause_duration_time + pause_end_time - pause_start_time
              # 暫停結束,暫停結束開始時間均置為0
              pause_end_time = pause_start_time = 0
            # 如果暫停了
            else:
              # 暫停播放
              pygame.mixer.music.pause()
              # 記錄開始暫定時間
              pause_start_time = time.time()

            print('點選了暫停')
          elif x+145 < mouse_x < x+170:
            # 點選了下一首
            c_music = sing_a_song(musics)
            is_pause = False
            is_kuaijin = False
            # 記錄開始時間
            start_time = time.time()
            # 暫停時長置為0
            pause_start_time = pause_end_time = pause_duration_time =0
            # 進度條開始位置置為40
            begin_x = 40
            # 第六步,顯示歌名
            draw_song_name(c_music)
            print('點選了下一首')
        # 如果點了進度條的某個位置
        elif 155> mouse_y >145:
          kuaijin(mouse_x,c_music)
          begin_x = mouse_x
          pause_end_time = pause_start_time = pause_duration_time = 0
          move(current_time,c_music)
          is_kuaijin = True
          print("快進")

    pygame.display.update()

3、效果圖

刺蝟牛逼!!!

4、完整程式碼

#-*- coding: utf-8 -*-
import os,time,sys
from sys import exit
import pygame
from pygame.locals import *
from mutagen.mp3 import MP3
from random import choice


def rp(relative_path):
  """ Get absolute path to resource,works for dev and for PyInstaller """
  try:
    # PyInstaller creates a temp folder and stores path in _MEIPASS
    base_path = sys._MEIPASS
  except Exception:
    base_path = os.path.abspath(".")

  return os.path.join(base_path,relative_path)

pygame.init()
screen = pygame.display.set_mode((640,480),32)
pygame.display.set_caption("music")
# 初始化音樂播放器
pygame.mixer.init()
# 背景圖片
music_bg = rp(os.path.join('src','music_bg.jpg'))
# 進度點圖片
dian_filename = rp(os.path.join('src','dian.jpg'))
dian = pygame.image.load(dian_filename)
# 字型
font_obj = pygame.font.Font('C:\Windows\Fonts\simsun.ttc',20)
# 偏移量基礎值
x = 80
# 進度條開始x座標
begin_x = 40
# 進度條結束x座標
end_x = 600
# 是否正在播放歌曲,預設未播放
is_sing = False
# 是否暫停,預設未暫停
is_pause = False
# 是否快進了
is_kuaijin = False
# 快進後x座標
jindu_x = -1
# 定義當前歌曲變數
global c_music
# 定義歌曲開始播放時間、當前時間、開始暫停時間、結束暫停時間
global start_time,current_time,pause_start_time,pause_end_time,pause_duration_time
pause_start_time =0
pause_end_time =0
pause_duration_time =0




# 把歌曲名字顯示在播放器上
def draw_song_name(music):
  # 取歌曲名
  music_name = music[0].split("\\")[-1]
  # print(music_name)
  wbk_obj = font_obj.render(music_name,k_obj)
  pygame.display.update()


# 收集某個目錄及子目錄下的MP3格式的檔案
# 返回歌曲路徑、歌曲時長
# [['E:\\musics\\Mirror_Yohee_128K.mp3',file)
        song = MP3(file)
        duration = round(song.info.length)
        tmp.append(file)
        tmp.append(duration)
        musics.append(tmp)
  return musics

musics = collect_songs('E:\\musics')
print(musics)

# 隨機播放一首歌
def sing_a_song(musics):
  # 隨機選擇一首音樂
  music = choice(musics)
  print(type(musics))
  pygame.mixer.music.load(music[0])
  pygame.mixer.music.play()
  print('開始播放:%s -- %s秒'%(music[0],str(music[1])))
  return music


# 畫代表當前進度的圓點
# 畫一個直徑為5個圓點,放在100,150的位置,顏色為(0,255)
# dian = pygame.draw.circle(screen,(begin_x,150),6)


# 畫播放控制元件
def draw_kongjian(is_sing,2)

# 播放進度顯示
def move(current_time,148))
    pygame.display.update()
  except:
    print(current_time)
    print(start_time)
    print(pause_duration_time)
    exit()

# 快進快退功能
def kuaijin(jindu_x,d_song_time)




while True:
  # 第一步畫背景
  screen.fill((0,c_music)
          is_kuaijin = True
          print("快進")

    pygame.display.update()
 

5、打包為exe

請檢視另一篇文章

pyinstaller打包exe踩過的坑

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。