Python实现音乐播放器 -----------内附源码

2024-06-12 01:20

本文主要是介绍Python实现音乐播放器 -----------内附源码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Python做一个简易的音乐播放器
简易音乐播放器

import time
import pygamefile = 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.7

先看一下运行效果:

代码讲解:

导入模块

import os
import time
import tkinter
import tkinter.filedialog
import threading
import pygame 

一、界面

root = tkinter.Tk()
root.title('音乐播放器')
root.geometry('460x500+500+100')
root.resizable(False,False) # 不能拉伸# 创建一个 ttk 样式
style = ttk.Style()# 设置框架的背景颜色
# style.configure("TFrame", background="#98F5F9")# 设置前景颜色和边框颜色
style.configure("TFrame", background="#98F5F9", foreground="#000000", bordercolor="#000000")frame = ttk.Frame(root, width=460, height=500)
frame.pack()# 显示
root.mainloop()

按钮


# 添加按钮
buttonChoose = tkinter.Button(root,text='添加',command=buttonChooseClick,fg="#000000",bg="#EFCDF8")
# 布局
buttonChoose.place(x=50,y=10,width=50,height=20)# 播放按钮
pause_resume = tkinter.StringVar(root,value='播放')
buttonPlay = tkinter.Button(root,textvariable=pause_resume,command=buttonPlayClick,fg="#000000",bg="#B2F199")
buttonPlay.place(x=120,y=10,width=50,height=20)
buttonPlay['state'] = 'disabled'# 停止按钮
buttonStop = tkinter.Button(root, text='停止',command=buttonStopClick,fg="#000000",bg="#F8B6B6")
buttonStop.place(x=190, y=10, width=50, height=20)
buttonStop['state'] = 'disabled'# 下一首
buttonNext = tkinter.Button(root, text='下一首',command=buttonNextClick,fg="#000000",bg="#F6E3C4")
buttonNext.place(x=260, y=10, width=50, height=20)
buttonNext['state'] = 'disabled'
# 上一首
buttonPrev = tkinter.Button(root, text='上一首',command=buttonPrevClick,fg="#000000",bg="#F6E3C4")
buttonPrev.place(x=330, y=10, width=50, height=20)
buttonPrev['state'] = 'disabled'# 标签
musicName = tkinter.StringVar(root, value='暂时没有播放音乐...')
labelName = tkinter.Label(root, textvariable=musicName)
labelName.place(x=50, y=30, width=330, height=20)# 音量控制
# HORIZONTAL表示为水平放置,默认为竖直,竖直为vertical
s = tkinter.Scale(root, label='音量', from_=0, to=1, orient=tkinter.HORIZONTAL,length=240, showvalue=0, tickinterval=2, resolution=0.1,command=control_voice)
s.place(x=50, y=50, width=330)

 

二、功能
创建一个文件目录

folder =''
res = []
num = 0
now_music = ''

音乐读取功能

def buttonChooseClick():global folderglobal resif not folder:folder = tkinter.filedialog.askdirectory()musics = [folder + '\\' + musicfor 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('\\','/'))if not folder:returnglobal playingplaying = True# 根据情况禁用和启用相应的按钮buttonPlay['state'] = 'normal'buttonStop['state'] = 'normal'# buttonPause['state'] = 'normal'pause_resume.set('播放')

显示已加载的音乐

var2 = tkinter.StringVar()
var2.set(ret)
lb = tkinter.Listbox(root,listvariable=var2)
lb.place(x=50,y=100,width=260,height=300)

播放音乐

def play():if len(res):pygame.mixer.init()global numwhile 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 = 0else:num = num + 1netxMusic = netxMusic.split('\\')[1:]musicName.set('playing......' + ''.join(netxMusic))else:time.sleep(0.1)# 点击播放
def buttonPlayClick():buttonNext['state'] = 'normal'buttonPrev['state'] = 'normal'# 选择要播放的音乐文件夹if pause_resume.get() == '播放':pause_resume.set('暂停')global folderif not folder:folder = tkinter.filedialog.askdirectory()if not folder:returnglobal playingplaying = True# 创建一个线程来播放音乐,当前主线程用来接收用户操作t = threading.Thread(target=play)t.start()elif pause_resume.get() == '暂停':# pygame.mixer.init()pygame.mixer.music.pause()pause_resume.set('继续')elif pause_resume.get() == '继续':# pygame.mixer.init()pygame.mixer.music.unpause()pause_resume.set('暂停')

停止播放

def buttonStopClick():global playingplaying = Falsepygame.mixer.music.stop()

下一首

def buttonNextClick():global playingplaying = Falsepygame.mixer.music.stop()global numif len(res) == num:num = 0playing = True# 创建线程播放音乐,主线程用来接收用户操作t = threading.Thread(target=play)t.start()

上一首

def buttonPrevClick():global playingplaying = Falsepygame.mixer.music.stop()## pygame.mixer.quit()global num# num += 1# num -= 1if num == 0:num = len(res) - 2# num -= 1elif num == len(res) - 1:num -= 2else:num -= 2# num -= 1print(num)playing = True# 创建一个线程来播放音乐,当前主线程用来接收用户操作t = threading.Thread(target=play)t.start()

音量控制

def control_voice(value=0.5):pygame.mixer.music.set_volume(float(value))

关闭窗口

def closeWindow():# 修改变量,结束线程中的循环global playingplaying = Falsetime.sleep(0.3)try:# 停止播放,如果已停止,# 再次停止时会抛出异常,所以放在异常处理结构中pygame.mixer.music.stop()pygame.mixer.quit()except:passroot.destroy()

完整代码已经上传到CSDN,0积分下载,有需要的朋友自行下载。

音乐播放器源码

感谢大家的阅读,觉得有所帮助的朋友点点关注点点赞!

这篇关于Python实现音乐播放器 -----------内附源码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1052801

相关文章

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

Nginx部署HTTP/3的实现步骤

《Nginx部署HTTP/3的实现步骤》本文介绍了在Nginx中部署HTTP/3的详细步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录前提条件第一步:安装必要的依赖库第二步:获取并构建 BoringSSL第三步:获取 Nginx

MyBatis Plus实现时间字段自动填充的完整方案

《MyBatisPlus实现时间字段自动填充的完整方案》在日常开发中,我们经常需要记录数据的创建时间和更新时间,传统的做法是在每次插入或更新操作时手动设置这些时间字段,这种方式不仅繁琐,还容易遗漏,... 目录前言解决目标技术栈实现步骤1. 实体类注解配置2. 创建元数据处理器3. 服务层代码优化填充机制详

Python实现Excel批量样式修改器(附完整代码)

《Python实现Excel批量样式修改器(附完整代码)》这篇文章主要为大家详细介绍了如何使用Python实现一个Excel批量样式修改器,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录前言功能特性核心功能界面特性系统要求安装说明使用指南基本操作流程高级功能技术实现核心技术栈关键函

Java实现字节字符转bcd编码

《Java实现字节字符转bcd编码》BCD是一种将十进制数字编码为二进制的表示方式,常用于数字显示和存储,本文将介绍如何在Java中实现字节字符转BCD码的过程,需要的小伙伴可以了解下... 目录前言BCD码是什么Java实现字节转bcd编码方法补充总结前言BCD码(Binary-Coded Decima

python获取指定名字的程序的文件路径的两种方法

《python获取指定名字的程序的文件路径的两种方法》本文主要介绍了python获取指定名字的程序的文件路径的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 最近在做项目,需要用到给定一个程序名字就可以自动获取到这个程序在Windows系统下的绝对路径,以下

SpringBoot全局域名替换的实现

《SpringBoot全局域名替换的实现》本文主要介绍了SpringBoot全局域名替换的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录 项目结构⚙️ 配置文件application.yml️ 配置类AppProperties.Ja

使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解

《使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解》本文详细介绍了如何使用Python通过ncmdump工具批量将.ncm音频转换为.mp3的步骤,包括安装、配置ffmpeg环... 目录1. 前言2. 安装 ncmdump3. 实现 .ncm 转 .mp34. 执行过程5. 执行结

Python实现批量CSV转Excel的高性能处理方案

《Python实现批量CSV转Excel的高性能处理方案》在日常办公中,我们经常需要将CSV格式的数据转换为Excel文件,本文将介绍一个基于Python的高性能解决方案,感兴趣的小伙伴可以跟随小编一... 目录一、场景需求二、技术方案三、核心代码四、批量处理方案五、性能优化六、使用示例完整代码七、小结一、

Python中 try / except / else / finally 异常处理方法详解

《Python中try/except/else/finally异常处理方法详解》:本文主要介绍Python中try/except/else/finally异常处理方法的相关资料,涵... 目录1. 基本结构2. 各部分的作用tryexceptelsefinally3. 执行流程总结4. 常见用法(1)多个e