前言:前几节课我们已经学会了很多知识点,欢迎大家可以去考古一下
今天我们将学习加载音乐,并且自制一个音乐播放器,界面功能包括:
- 加载背景封面
- 上一首
- 开始\暂停
- 下一首
- 重播
- 随机播放
- 快进
效果展示(GIF所以你们听不到声音)
分析
pygame.mixer.music.load(song)
pygame.mixer.music.set_volume(0.5)
'''
第一个参数1指播放一次,0指循环播放
time:指从第几毫秒开始播放
pygame.mixer.music.play(1, time)
'''
pygame.mixer.music.play()
pygame.mixer.music.pause()
pygame.mixer.music.unpause()
'''
第一个参数1指播放一次,0指循环播放
time:指从第几毫秒开始播放
pygame.mixer.music.play(1, time)
'''
pygame.mixer.music.play(1, time)
注意事项及解决
-
1,开始与暂定按钮的图标在同一个位置,设置变量来回切换
-
-
3、音乐每播放完一首,应自动跳转至下一首
素材获取(功能图标、音乐封面,音乐只能自己下载啦):点我
目录结构
文件\文件夹名 | 作用 |
---|
image2 | 播放器界面的功能图标图片存放 |
music | 存放音乐 |
封面 | 存放音乐封面 |
完整版代码:
import os
import pygame, random, sys, time
pygame.init()
sc = pygame.display.set_mode((300, 250))
bg = pygame.image.load("image2/bg.png")
pre_song = pygame.image.load("image2/上一首.png")
start = pygame.image.load("image2/播放.png")
pause = pygame.image.load("image2/暂停.png")
next_song = pygame.image.load("image2/下一首.png")
ff = pygame.image.load("image2/快进.png")
res = pygame.image.load("image2/重播.png")
rand = pygame.image.load("image2/随机播放.png")
bg_list = os.listdir("./封面/")
bg_list1 = []
for bg in bg_list:
bg_list1.append(pygame.image.load("./封面/"+bg))
btn = start
btn_flag = 0
song_list = ['./music/'+i for i in os.listdir('./music/')]
index = 0
song = song_list[index]
pygame.mixer.music.load(song)
pygame.mixer.music.set_volume(0.5)
pygame.mixer.music.play()
time = 0
print(time)
length = len(song_list)
while True:
if btn_flag % 2 == 0:
btn = start
pygame.mixer.music.pause()
else:
btn = pause
pygame.mixer.music.unpause()
sc.blit(bg_list1[index],(0,0))
sc.blit(pre_song, (20, 90))
sc.blit(next_song, (210, 90))
sc.blit(rand, (115, 170))
sc.blit(btn, (115, 90))
sc.blit(ff, (210, 170))
sc.blit(res, (20, 170))
pygame.display.update()
for event in pygame.event.get():
mouse_x, mouse_y = pygame.mouse.get_pos()
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if 115 < mouse_x < 185 and 90 < mouse_y < 160:
btn_flag += 1
if 210 < mouse_x < 280 and 90 < mouse_y < 160:
index = (index + 1) % len(song_list)
song = song_list[index]
pygame.mixer.music.load(song)
pygame.mixer.music.play(1, 0)
if 20 < mouse_x < 90 and 90 < mouse_y < 160:
index = (index + length - 1) % length
song = song_list[index]
pygame.mixer.music.load(song)
pygame.mixer.music.play(1, 0)
elif 210 < mouse_x < 280 and 170 < mouse_y < 240:
time += 10
print(time)
pygame.mixer.music.play(1, time)
print(time)
if pygame.mixer.music.get_busy() == False:
index = (index + 1) % length
song = song_list[index]
pygame.mixer.music.load(song)
pygame.mixer.music.play()
elif 20 < mouse_x < 90 and 170 < mouse_y < 240:
time = 0
pygame.mixer.music.play(1, time)
elif 115 < mouse_x < 185 and 170 < mouse_y < 240:
index = random.randint(0, 3)
song = song_list[index]
pygame.mixer.music.load(song)
pygame.mixer.music.play()
希望对大家有帮助
致力于办公自动化的小小程序员一枚#
都看到这了,关注+点赞+收藏=不迷路!!
如果你想知道更多关于Python办公自动化的知识各位大佬给个关注吧!