前言
就是用Python做一个简易的音乐播放器,废话不多说,咱们直接开干
当然,今天做这个肯定不是最简单的,最简单的音乐播放器,9行代码足以
import time
import pygame
file = r'歌曲路径'
pygame.mixer.init()
print('正在播放',file)
track = pygame.mixer.music.load(file)
pygame.mixer.music.play()
time.sleep(130)
pygame.mixer.music.stop()
开始今天的代码之前,准备工作
知识点和所需模块
1.python基础知识
2.requests库
3.time
4.pygame
5.tkinter
6.线程
环境
- windows
- pycharm 2021.2
- python 3.8
完整代码,运行即可,记得???(直接明示了)
# 导入
import os
import time
import tkinter
import tkinter.filedialog
import threading
import pygame # pip
root = tkinter.Tk()
root.title('音乐播放器')
root.geometry('460x600+500+100')
root.resizable(False,False) # 不能拉伸
folder =''
res = []
num = 0
now_music = ''
def buttonChooseClick():
"""
添加文件夹
:return:
"""
global folder
global res
if not folder:
folder = tkinter.filedialog.askdirectory()
musics = [folder + '\' + music
for music in os.listdir(folder)
if music.endswith(('.mp3','.wav','.ogg'))]
ret = []
for i in musics:
ret.append(i.split('\')[1:])
res.append(i.replace('\','/'))
var2 = tkinter.StringVar()
var2.set(ret)
lb = tkinter.Listbox(root,listvariable=var2)
lb.place(x=50,y=100,width=260,height=300)
if not folder:
return
global playing
playing = True
# 根据情况禁用和启用相应的按钮
buttonPlay['state'] = 'normal'
buttonStop['state'] = 'normal'
# buttonPause['state'] = 'normal'
pause_resume.set('播放')
def play():
"""
播放音乐
:return:
"""
if len(res):
pygame.mixer.init()
global num
while playing:
if not pygame.mixer.music.get_busy():
netxMusic = res[num]
print(netxMusic)
print(num)
pygame.mixer.music.load(netxMusic.encode())
# 播放
pygame.mixer.music.play(1)
if len(res) -1 == num:
num = 0
else:
num = num + 1
netxMusic = netxMusic.