Python制作音乐播放器

Python用tkinter库制作一个音乐播放器,自定义一个自己想要的播放器。虽然明天其他的播放器强大,如某易云,某狗。但是也是一个好玩的小插件。


1.制作需求


首先要会一点tkinter库的基础使用方法,当然其他gui库也行!这里只是博主这个废物不会其他gui库而用tkinter库来制作。其他的就是Python的一些基础操作而已。

这次播放音乐,博主使用pygame库的模块来制作音乐播放部分。因为这个模块支持很多音乐格式,而且不占用程序运行。用pip安装即可

pip install pygame

1.制作gui部分 

我们写制作gui部分,这样再去实现其他功能 

主体gui

"""
作者:PYmili
BUG请联系群:706128290
Python版本:3.9.7
"""
import tkinter as tk
import tkinter.messagebox
from tkinter import *
import tkinter.ttk
from PIL import ImageTk
from PIL import Image
import pygame
import time
import os
import re
import requests

"""
获取图片详细并处理
return: im
"""
def get_img(filename, width, height):
    im = Image.open(filename).resize((width, height))
    im = ImageTk.PhotoImage(im)
    return im

"""
窗口建立
"""
class gui:
    def __init__(self):
        #常用参数
        path,file=os.path.split(__file__)
        self.path=path
        self.file=file
        self.video={}
        self.tk=tk.Tk()
    def main(self):
        win=self.tk
        win.geometry("1000x563")
        win.resizable(False,False)
        win.title("藤和音乐播放器")
        win.iconbitmap("aum4e-67zg9-001.ico")
        win.iconbitmap()
        """
        背景图
        """
        canvas_root = tk.Canvas(win, width=1000, height=563)
        im_root = get_img(fr'{self.path}\img\20170924123431_RE8SX.png', 1000, 563)
        canvas_root.create_image(500, 277, image=im_root)
        canvas_root.pack()
        # VideoList
        videolist=Listbox(win,height=11, width=50)
        videolist.place(x=30,y=40)

        # Label
        tk.Label(win, text="输入文件完整路径:").place(x=1,y=1)
        # Entry
        var_path=tk.StringVar()
        filepath=tk.Entry(win, width=70, textvariable=var_path).place(x=120,y=1)

        win.mainloop()

大体gui就是一个有背景的窗口。有一个输入框用于获取用户输入的音乐文件夹。


按钮部分

 # Button
 get_video=Button(win, text="读取文件夹中所有歌曲", command=testing).place(x=80,y=250)
 play_video=Button(win, text="播放", command=play_video).place(x=35,y=250)
 delete_=Button(win, text="删除列表", command=delete_).place(x=1, y=300)
 for_play=Button(win, text="自动播放", command=for_play).place(x=1, y=350)
 urlvideo=Button(win, text="打开网络音乐播放器", command=url_gui).place(x=1, y=500)
 win.mainloop()

我们要做几个按钮来供用户操作。


主函数部分

"""
获取用户在输入框输入的文件夹路径
并且处理文件夹下所有音频文件并写入字典
在窗口的列表显示出来
"""
        # Entry
        var_path=tk.StringVar()
        filepath=tk.Entry(win, width=70, textvariable=var_path).place(x=120,y=1)

        
        def testing():
            if os.path.exists(var_path.get())==True:
                pathfile=var_path.get()
                videolists=[]
                for path,dirs,file in os.walk(pathfile):
                    if any(dirs) == False:
                        for fil in file:
                            videolists.append(path+f"\{fil}")
                    else:
                        for di in dirs:
                            for fil in file:
                                videolists.append(path+di+f"\{fil}")
                if any(videolists) == False:
                    apap=False
                else:
                    apap=videolists

            else:
                apap=None
            videolist.pack()
            video=[]
            mps=[]
            if apap == False:
                tk.messagebox.showinfo('提示', '你个笨蛋!你不会看你文件夹里面有没有文件吗!')
            elif apap == None:
                tk.messagebox.showinfo('提示', '你个笨蛋!你不会看你你的路径是否存在吗!')
            else:
                for vi in apap:
                    video.append(vi)
            yun=True
            for mp in video:
                file_ext=os.path.splitext(mp)[-1]
                #print(file_ext)
                if file_ext in ['.wav', '.mp3', '.ogg', '.flac', 'mp4a']:
                    mps.append(mp)
                else:
                    pass
            if yun == True:
                for mpp in mps:
                    p,f=os.path.split(mpp)
                    videolist.insert(END,f)
                    self.video[f]=mpp
                    videolist.place(x=30,y=40)
            else:
                tk.messagebox.showwarning("Error", "为识别到可播放文件")

"""
使用pygame播放音乐
"""
def play_video():
    lines=videolist.curselection()
    for line in lines:
        audio=self.video[videolist.get(line)]
        pygame.mixer.init()
        pygame.mixer.music.load(audio)
        pygame.mixer.music.play(2)
        pygame.mixer.music.get_busy()

"""
自动播放音乐部分
"""
def for_play():
    for key,msg in self.video.items():
        audio=self.video[key]
        try:
            pygame.mixer.init()
            pygame.mixer.music.load(audio)
            pygame.mixer.music.play(2)
            pygame.mixer.music.get_busy()
        except:
            continue

"""
删除音乐目录
"""
def delete_():
    for i in range(2000):
        videolist.delete(i,i)

最终成果及完整代码

源代码

藤和动漫.py

import tkinter as tk
import tkinter.messagebox
from tkinter import *
import tkinter.ttk
from PIL import ImageTk
from PIL import Image
import pygame
import time
import os
import re
import requests

import get_url_video as url_video

def get_img(filename, width, height):
    im = Image.open(filename).resize((width, height))
    im = ImageTk.PhotoImage(im)
    return im

def url_gui():
    root=tk.Tk()
    root.title("UrlVideo-请输入网络音乐完全地址")
    root.geometry("400x400")
    root.iconbitmap("aum4e-67zg9-001.ico")
    Label(root, text="URL地址:").place(x=60,y=1)
    var=tk.StringVar()
    url=Entry(root,textvariable=var).pack()
    def gets():
        _url_=var.get()
        try:
            path=url_video.get_url_video(_url_)
            Label(root, text="成功").pack()
            pygame.mixer.init()
            pygame.mixer.music.load(f"{path}")
            pygame.mixer.music.play(2)
            pygame.mixer.music.get_busy()
        except:
            Label(root, text="失败").pack()
    Button(root, text="播放", command=gets).pack()
    root.mainloop()

class gui:
    def __init__(self):
        path,file=os.path.split(__file__)
        self.path=path
        self.file=file
        self.video={}
        self.tk=tk.Tk()
    def main(self):
        win=self.tk
        win.geometry("1000x563")
        win.resizable(False,False)
        win.title("藤和音乐播放器")
        win.iconbitmap("aum4e-67zg9-001.ico")
        win.iconbitmap()
        """
        背景图
        """
        canvas_root = tk.Canvas(win, width=1000, height=563)
        im_root = get_img(fr'{self.path}\img\20170924123431_RE8SX.png', 1000, 563)
        canvas_root.create_image(500, 277, image=im_root)
        canvas_root.pack()
        # VideoList
        videolist=Listbox(win,height=11, width=50)
        videolist.place(x=30,y=40)

        # Label
        tk.Label(win, text="输入文件完整路径:").place(x=1,y=1)
        # Entry
        var_path=tk.StringVar()
        filepath=tk.Entry(win, width=70, textvariable=var_path).place(x=120,y=1)

        
        def testing():
            if os.path.exists(var_path.get())==True:
                pathfile=var_path.get()
                videolists=[]
                for path,dirs,file in os.walk(pathfile):
                    if any(dirs) == False:
                        for fil in file:
                            videolists.append(path+f"\{fil}")
                    else:
                        for di in dirs:
                            for fil in file:
                                videolists.append(path+di+f"\{fil}")
                if any(videolists) == False:
                    apap=False
                else:
                    apap=videolists

            else:
                apap=None
            videolist.pack()
            video=[]
            mps=[]
            if apap == False:
                tk.messagebox.showinfo('提示', '你个笨蛋!你不会看你文件夹里面有没有文件吗!')
            elif apap == None:
                tk.messagebox.showinfo('提示', '你个笨蛋!你不会看你你的路径是否存在吗!')
            else:
                for vi in apap:
                    video.append(vi)
            yun=True
            for mp in video:
                file_ext=os.path.splitext(mp)[-1]
                #print(file_ext)
                if file_ext in ['.wav', '.mp3', '.ogg', '.flac', 'mp4a']:
                    mps.append(mp)
                else:
                    pass
            if yun == True:
                for mpp in mps:
                    p,f=os.path.split(mpp)
                    videolist.insert(END,f)
                    self.video[f]=mpp
                    videolist.place(x=30,y=40)
            else:
                tk.messagebox.showwarning("Error", "为识别到可播放文件")

        def play_video():
            lines=videolist.curselection()
            for line in lines:
                audio=self.video[videolist.get(line)]
                pygame.mixer.init()
                pygame.mixer.music.load(audio)
                pygame.mixer.music.play(2)
                pygame.mixer.music.get_busy()

        def for_play():
            for key,msg in self.video.items():
                audio=self.video[key]
                try:
                    pygame.mixer.init()
                    pygame.mixer.music.load(audio)
                    pygame.mixer.music.play(2)
                    pygame.mixer.music.get_busy()
                except:
                    continue
        
        def delete_():
            for i in range(2000):
                videolist.delete(i,i)
        # Button
        get_video=Button(win, text="读取文件夹中所有歌曲", command=testing).place(x=80,y=250)
        play_video=Button(win, text="播放", command=play_video).place(x=35,y=250)
        delete_=Button(win, text="删除列表", command=delete_).place(x=1, y=300)
        for_play=Button(win, text="自动播放", command=for_play).place(x=1, y=350)
        urlvideo=Button(win, text="打开网络音乐播放器", command=url_gui).place(x=1, y=500)
        win.mainloop()

if __name__ in "__main__":
    g=gui()
    g.main()

get_url_video.py文件 

import requests
import os

def get_url_video(_url):
    r=requests.get(url=_url)
    if r.status_code == 200:
        path,file=os.path.split(__file__)
        urls,urlfile=os.path.split(_url)
        if os.path.exists(fr"{path}\video\{urlfile}") == False:
            with open(fr"{path}\video\{urlfile}", "wb")as f:
                f.write(r.content)
            return fr"{path}\video\{urlfile}"
        else:
            return fr"{path}\video\{urlfile}"
    else:
        return False

最终成果

 

 

 这个就是最终效果,虽然不怎么样.....但是还是实现了我们想要的功能,缺点是没有停止功能,下一首,上一首功能。

这个之后会添加大家可以加QQ群:706128290 关注更新或提交BUG!

群文件中会有文件源文件,而且博主打包了安装,程序可以直接安装到电脑上。

我是PYmili,喜欢就点个赞吧!下次再见!

  • 5
    点赞
  • 56
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Pymili

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值