当前位置: 首页 > news >正文

Python制作9行最简单音乐播放器?不,我不满足

嗨害大家好鸭~我是小熊猫

好久不见啦~这次就来给大家整个大福利 ~

源码资料电子书:点击此处跳转文末名片获取

在这里插入图片描述

最简单的9行代码音乐播放器如下:

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.8

在这里插入图片描述

完整代码,运行即可,记得三连👍👍👍

(直接明示了)

import os
import time
import tkinter
import tkinter.filedialog
import threading
import pygame  root = tkinter.Tk()
root.title('音乐播放器 #python学习交流裙:660193417#')
root.geometry('460x600+500+100')
root.resizable(False,False) folder =''
res = []
num = 0
now_music = ''def buttonChooseClick():"""添加文件夹:return:"""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('\\','/'))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:returnglobal playingplaying = TruebuttonPlay['state'] = 'normal'buttonStop['state'] = 'normal'# python学习交流裙:660193417#pause_resume.set('播放')def play():"""播放音乐:return:"""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))def buttonPlayClick():"""点击播放:return:"""buttonNext['state'] = 'normal'if pause_resume.get() == '播放':pause_resume.set('暂停')global folderif not folder:folder = tkinter.filedialog.askdirectory()if not folder:returnglobal playingplaying = Truet = threading.Thread(target=play)t.start()elif pause_resume.get() == '暂停':pygame.mixer.music.pause()pause_resume.set('继续')elif pause_resume.get() == '继续':pygame.mixer.music.unpause()pause_resume.set('暂停')def buttonStopClick():"""停止播放:return:"""global playingplaying = Falsepygame.mixer.music.stop()def buttonNextClick():"""下一首:return:"""global playingplaying = Falsepygame.mixer.music.stop()global numif len(res) == num:num = 0playing = Truet = threading.Thread(target=play)t.start()def closeWindow():"""关闭窗口:return:"""global playingplaying = Falsetime.sleep(0.3)try:pygame.mixer.music.stop()pygame.mixer.quit()except:passroot.destroy()def control_voice(value=0.5):"""声音控制:param value: 0.0-1.0:return:"""pygame.mixer.music.set_volume(float(value))def buttonPrevClick():"""上一首:return:"""global playingplaying = Falsepygame.mixer.music.stop()global numif num == 0:num = len(res) - 2elif num == len(res) - 1:num -= 2else:num -= 2print(num)playing = Truet = threading.Thread(target=play)t.start()root.protocol('WM_DELETE_WINDOW', closeWindow)buttonChoose = tkinter.Button(root,text='添加',command=buttonChooseClick)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)
buttonPlay.place(x=190,y=10,width=50,height=20)
buttonPlay['state'] = 'disabled'buttonStop = tkinter.Button(root, text='停止',command=buttonStopClick)
buttonStop.place(x=120, y=10, width=50, height=20)
buttonStop['state'] = 'disabled'buttonNext = tkinter.Button(root, text='下一首',command=buttonNextClick)
buttonNext.place(x=260, y=10, width=50, height=20)
buttonNext['state'] = 'disabled'
buttonPrev = tkinter.Button(root, text='上一首',command=buttonPrevClick)
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=10, y=30, width=260, height=20)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=200)root.mainloop()

效果展示

简易版的

在这里插入图片描述

半成品,代码没写完(诶嘿我懒)

在这里插入图片描述
在这里插入图片描述

导入模块

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

一、界面

root = tkinter.Tk()
root.title('音乐播放器')
root.geometry('460x600+500+100')
root.resizable(False,False) root.mainloop()

请添加图片描述

按钮

buttonChoose = tkinter.Button(root,text='添加')
buttonChoose.place(x=50,y=10,width=50,height=20)pause_resume = tkinter.StringVar(root,value='播放')
buttonPlay = tkinter.Button(root,textvariable=pause_resume)
buttonPlay.place(x=190,y=10,width=50,height=20)
buttonPlay['state'] = 'disabled'buttonStop = tkinter.Button(root, text='停止')
buttonStop.place(x=120, y=10, width=50, height=20)
buttonStop['state'] = 'disabled'buttonNext = tkinter.Button(root, text='下一首')
buttonNext.place(x=260, y=10, width=50, height=20)
buttonNext['state'] = 'disabled'buttonPrev = tkinter.Button(root, text='上一首')
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=10, y=30, width=260, height=20)s = tkinter.Scale(root, label='音量', from_=0, to=1, orient=tkinter.HORIZONTAL,length=240, showvalue=0, tickinterval=2, resolution=0.1)
s.place(x=50, y=50, width=200)

在这里插入图片描述

二、功能

创建一个文件目录

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 = Truet = threading.Thread(target=play)t.start()

上一首

def buttonPrevClick():global playingplaying = Falsepygame.mixer.music.stop()global numif num == 0:num = len(res) - 2elif num == len(res) - 1:num -= 2else:num -= 2print(num)playing = Truet = 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()

在这里插入图片描述

👇问题解答 · 源码获取 · 技术交流 · 抱团学习请联系👇

相关文章:

Python制作9行最简单音乐播放器?不,我不满足

嗨害大家好鸭~我是小熊猫 好久不见啦~这次就来给大家整个大福利 ~ 源码资料电子书:点击此处跳转文末名片获取 最简单的9行代码音乐播放器如下: import time import pygamefile r歌曲路径 pygame.mixer.init() print(正在播放,file) track pygame.mixer.music.lo…...

零基础小白如何学会数据分析?

随着数字经济、大数据时代的发展,数据已然成为当下时代最重要的盈利资源,让企业在做决策和计划方案时更有针对性和依据,能提前预测市场发展方向,做好布局。由此而产生的数据分析岗位也逐渐被更多企业重视,特别是中大型…...

【Linux】vim的使用及常用快捷键(不会使用vim?有这篇文章就够了)

🔥🔥 欢迎来到小林的博客!!       🛰️博客主页:✈️小林爱敲代码       🛰️欢迎关注:👍点赞🙌收藏✍️留言 目录💖vim的基本概念vi…...

刷完这19道leetcode二分查找算法,不信进不了大厂

对于二分题,其实就是设定一个中间值 mid, 然后通过这个值进行一个判断 check(mid), 通过这个函数的返回值,判断将不可能的一半剪切掉; 在刷题的时候需要注意主要是两部分,check 函数的定义以及边界的选择(…...

四、Plugin Request and Sometimes pads

Request and Sometimes pads 到目前为止,我们只处理了总是可用的pad。然而,也有一些pad仅在某些情况下创建,或者仅在应用程序请求pad时创建。第一个有时被称为a;第二个被称为请求pad。pad的可用性(always, sometimes or request)可以在pad的…...

唤醒手腕 Java 后端 Springboot 结合 Redis 数据库学习笔记(更新中)

Redis 基本介绍 Redis Introduction The open source, in-memory data store used by millions of developers as a database, cache, streaming engine, and message broker. 基本概念:redis 是一个开源的、使用 C 语言编写的、支持网络交互的、可基于内存也可持…...

robotiq 2f 140安装在UR3机械臂后面在gazebo仿真中散架、抖动

robotiq 2f 140安装在UR3机械臂后面在gazebo仿真中散架、抖动 搭建环境: ubuntu: 20.04 ros: Nonetic sensor: robotiq_ft300 gripper: robotiq_2f_140_gripper UR: UR3 通过上一篇博客配置好ur3、力传感器和robotiq夹爪的gazebo仿真环境后,夹爪看起来…...

坐标系概念 四元数 欧拉角

1、四个概念:“地理”坐标系、“机体”坐标系、他们之间换算公式、换算公式用的系数。地理坐标系:东、北、天,以下简称地理。在这个坐标系里有重力永远是(0,0,1g),地磁永远是(0,1,x)…...

从0开始写Vue项目-SpringBoot整合Mybatis-plus实现登录、注册功能

1.从0开始写Vue项目-环境和项目搭建_慕言要努力的博客-CSDN博客 2. 从0开始写Vue项目-Vue2集成Element-ui和后台主体框架搭建_慕言要努力的博客-CSDN博客 3. 从0开始写Vue项目-Vue页面主体布局和登录、注册页面_慕言要努力的博客-CSDN博客 一、前言 在之前我们以及搭建好了基…...

K8s中gRpc通信负载均衡失效

上篇文章在做 整合K8sSpringCloudK8sSpringBootgRpc 时,发现K8s中使用gRpc通信,负载均衡功能失效查了下gRpc的最佳实践,找到这里Load balancingSome load balancers dont work effectively with gRPC. L4 (transport) load balancers operate…...

第三届区块链服务网络(BSN)全球合作伙伴大会在杭州成功举办

为持续推动分布式技术和产业创新发展,2023年2月17日,由杭州市人民政府指导,杭州市拱墅区人民政府、国家信息中心主办,中国移动通信集团有限公司、区块链服务网络(BSN)发展联盟承办,中国移动通信…...

人工智能基础部分13-LSTM网络:预测上证指数走势

大家好,我是微学AI,今天给大家介绍一下LSTM网络,主要运用于解决序列问题。 一、LSTM网络简单介绍 LSTM又称为:长短期记忆网络,它是一种特殊的 RNN。LSTM网络主要是为了解决长序列训练过程中的梯度消失和梯度爆炸问题…...

内网穿透/组网/设备上云平台EasyNTS上云网关的安装操作指南

EasyNTS上云网关的主要作用是解决异地视频共享/组网/上云的需求,网页对域名进行添加映射时,添加成功后会生成一个外网访问地址,在浏览器中输入外网访问地址,即可查看内网应用。无需开放端口,EasyNTS上云网关平台会向Ea…...

易点天下基于 StarRocks 全面构建实时离线一体的湖仓方案

作者:易点天下数据平台团队易点天下是一家技术驱动发展的企业国际化智能营销服务公司,致力于为客户提供全球营销推广服务,通过效果营销、品牌塑造、垂直行业解决方案等一体化服务,帮助企业在全球范围内高效地获取用户、提升品牌知…...

Tomcat的类加载机制

不遵循双亲委托 在JVM中并不是一次性地把所有的文件都加载到,而是按需加载,加载机制采用 双亲委托原则,如下图所示: BootStrapClassLoader 引导类加载器ExtClassLoader 扩展类加载器AppClassLoader 应用类加载器CustomClassLoad…...

【shell 编程大全】数组,逻辑判断以及循环

数组,逻辑判断以及循环1. 概述 大家好,我又来了。今天呢我们继续学习shell相关的知识。还是老样子我们先回顾下上一次【脚本交互 以及表达式】学习到的知识 登录shell 关联配置文件什么是子shellumask 修改默认权限read 基础表达式 简单计算表达式expr 计…...

Android13 Bluetooth更新

目录 Android 13 版本说明 LE Audio 代码更新 Android 12代码路径 Android 13代码路径 Android 13 版本说明 里面对蓝牙更新的描述较少,一出提到蓝牙的一...

手工测试混了5年,年底接到了被裁员的消息....

大家都比较看好软件测试行业,只是因为表面上看起来:钱多事少加班少。其实这个都是针对个人运气好的童人才会有此待遇。在不同的阶段做好不同阶段的事情,才有可能离这个目标更近,作为一枚软件测试人员,也许下面才是我们…...

Umi框架

什么是 umi umi 是由 dva 的开发者 云谦 编写的一个新的 React 开发框架。umi 既是一个框架也是一个工具,可以将它简单的理解为一个专注性能的类 next.js 前端框架,并通过约定、自动生成和解析代码等方式来辅助开发,减少开发者的代码量。 u…...

教你学git

前言 git是一种用于多人合作写项目。详细说明如下 文章目录前言什么是版本控制?什么是 Git?它就属于人工版本控制器版本控制工具常见版本控制工具怎么工作的?git 文件生命周期状态区域安装配置-- global检查配置创建仓库工作流与基本操作查看…...

Venera漫画阅读器:跨平台智能阅读的终极指南

Venera漫画阅读器:跨平台智能阅读的终极指南 【免费下载链接】venera A comic app 项目地址: https://gitcode.com/gh_mirrors/ve/venera 想要在Android、iOS、Windows、macOS和Linux上享受无缝的漫画阅读体验吗?Venera漫画阅读器正是您需要的终极…...

Windows右键菜单效率革命:ContextMenuManager极简操作与深度定制指南

Windows右键菜单效率革命:ContextMenuManager极简操作与深度定制指南 【免费下载链接】ContextMenuManager 🖱️ 纯粹的Windows右键菜单管理程序 项目地址: https://gitcode.com/gh_mirrors/co/ContextMenuManager 每天面对电脑上杂乱的右键菜单&…...

避坑指南:在K210上跑人脸68关键点,这些细节让你的疲劳检测更准

K210人脸疲劳检测实战:68关键点调优与工程化避坑指南 当你在车载监控或工业安全场景部署基于K210的疲劳检测系统时,是否遇到过这些情况?明明按照开源代码跑通了68关键点检测,但实际场景中闭眼判断总是不准;白天阳光直射…...

计算机毕业设计springboot基于Web的健身会员管理系统 基于SpringBoot的健身房智能化运营服务平台 SpringBoot框架下的健身俱乐部会员服务与课程预约系统

计算机毕业设计springboot基于Web的健身会员管理系统e7cr4n62(配套有源码 程序 mysql数据库 论文) 本套源码可以在文本联xi,先看具体系统功能演示视频领取,可分享源码参考。 随着全民健身意识的提升和健康管理需求的日益增长,传统…...

Qwen3-14B私有化效果:支持国密算法加密的API通信安全方案

Qwen3-14B私有化效果:支持国密算法加密的API通信安全方案 1. 私有部署镜像概述 Qwen3-14B私有部署镜像是基于通义千问大语言模型优化定制的专业解决方案,特别针对RTX 4090D 24GB显存配置进行了深度适配。这个镜像不仅提供了完整的运行环境和模型依赖&a…...

gh_mirrors/eg/eggs深度解析:一站式解决所有服务器部署难题

gh_mirrors/eg/eggs深度解析:一站式解决所有服务器部署难题 【免费下载链接】eggs Service eggs for the pterodactyl panel 项目地址: https://gitcode.com/gh_mirrors/eg/eggs 在服务器管理领域,快速部署和高效运维一直是开发者和管理员面临的核…...

AI大模型进化地图:小白也能看懂的技术架构与未来趋势(收藏版)

本文深入剖析AI模型的技术架构、能力瓶颈及商业压力,揭示未来AI模型的四类形态:通用基础大模型、深度推理模型、边缘轻量模型和垂直领域专业模型。文章通过DeepSeek-R1和Google Gemini的案例,量化分析不同模型类型的业务逻辑差异,…...

如何快速配置NoteGen快捷键:从新手到效率高手的完整指南

如何快速配置NoteGen快捷键:从新手到效率高手的完整指南 【免费下载链接】note-gen 一款专注于记录和写作的跨端 AI 笔记应用。 项目地址: https://gitcode.com/GitHub_Trending/no/note-gen 你是否曾经在使用笔记应用时,频繁切换鼠标点击菜单&am…...

从零开始:基于 Chroma+Ollama 的本地知识库搭建与智能问答实战指南

1. 为什么选择 ChromaOllama 组合? 如果你正在寻找一个既轻量又强大的本地知识库解决方案,Chroma 和 Ollama 的组合绝对值得考虑。我最初接触这个组合是因为需要一个完全离线的知识管理系统,经过多次对比测试后发现,这对搭档在易用…...

3分钟上手:ControlNet-v1-1_fp16_safetensors让你的AI绘画更精准可控 [特殊字符]

3分钟上手:ControlNet-v1-1_fp16_safetensors让你的AI绘画更精准可控 🎨 【免费下载链接】ControlNet-v1-1_fp16_safetensors 项目地址: https://ai.gitcode.com/hf_mirrors/comfyanonymous/ControlNet-v1-1_fp16_safetensors ControlNet-v1-1_f…...