pyqt5+pyagme实现音乐播放器,运用了pyqt5的list,可以双击播放,会自动提取音频文件的图片

源码下载**:自己往下翻**!!!,(但如果你想用积分下载我也拦不了你)
https://download.csdn.net/download/oys19812007/18974107?spm=1001.2014.3001.5501
之前没事干,看windows10自带的播放器有一(亿)点点不顺眼,然后想写一个播放器,
正好有学了点pyqt5,然后就整了这个东西,耗时4天,差不多也算是最终版本了吧,
如果接下来有时间的话也会继续更新下去,
但至少也要过多一年了,毕竟也快初三了,要认真复习了

( •̀ ω •́ )✧
python实现的音乐播放器,成品如下:

要用到的库

import sys
import re
import pygamefrom mutagen import File
import time
import os, math
from PIL import Image, ImageDraw, ImageFilter
# import requests
# import jsonpath
# from mutagen.mp3 import MP3
# from mutagen import File
# from urllib.request import urlretrieve
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QFileDialog, QMessageBox, QListWidget, QLabel, QListWidgetItem, QApplication, QWidget
from PyQt5.QtCore import QTimer, QDateTime, Qt
from PyQt5.QtGui import QIcon, QPixmap, QColor, QPainter, QPixmap
from PyQt5 import QtMultimedia, QtWidgets, QtCore
from PyQt5.QtGui import QFont, QCursor
import qtawesome
import threading
import random
import requests

下面是功能代码的分享

这里是item双击播放的源码,item绑定这个后可以调用pyagme播放

'''这里是item双击播放的源码,item绑定这个后可以调用pyagme播放
'''def change_func(self, listwidget):global numitem = QListWidgetItem(self.listwidget.currentItem())print (item.text())#print (item.flags())num = int(listwidget.currentRow())a,f = os.path.split(SongPath[num])#分割文件名  f,ex = os.path.splitext(f)#self.label.setText(wenjianming)#设置标签的文本为音乐的名字    self.label1.setText(f)print (listwidget.currentRow())self.bofang(num)def bofang(self, num):try:global pauseself.photo(num)self.console_button_3.setIcon(qtawesome.icon('fa.pause', color='#F76677', font=18))pause = False# QMessageBox.information(self, "ListWidget", "你选择了: "+item.text())# 显示出消息提示框fill = SongPath[num]print(fill)try:pygame.mixer.stop()except:passpygame.mixer.init()try:self.Timer = QTimer()self.Timer.start(500)except:passpygame.mixer.music.load(SongPath[num])  # 载入音乐pygame.mixer.music.play()  # 播放音乐except:time.sleep(0.1)print ('system error')self.next()pass

接下来是开始的代码块

    def start(self):try:global SongPathglobal numglobal filewglobal asasif not os.path.exists("2.png"):try:req = requests.get('https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fy.gtimg.cn%2Fmusic%2Fphoto_new%2FT001R300x300M000002ztBMe06cOx0.jpg%3Fmax_age%3D2592000&refer=http%3A%2F%2Fy.gtimg.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625464213&t=a30c07bda8c2ab7d8001a59353e936e0')checkfile  = open('ls2.png','w+b')for i in req.iter_content(100000):checkfile.write(i)checkfile.close()lsfile = './ls2.png'safile = './2.png'draw(lsfile,safile)except:print ('download error')passfileN = QtWidgets.QFileDialog.getExistingDirectory(None, "选取文件夹", "")filew = fileN + '/'asas = filewl1 = [name for name in os.listdir(fileN) if name.endswith('.mp3')]l2 = [name for name in os.listdir(fileN) if name.endswith('.flac')]l3 = [name for name in os.listdir(fileN) if name.endswith('wma')]SongName = l1 + l2 + l3SongPath = [filew + i for i in SongName]print(SongPath)pygame.mixer.init()self.Timer = QTimer()self.Timer.start(500)# self.Timer.timeout.connect(self.timercontorl)#时间函数,与下面的进度条和时间显示有关# self.label = os.path.splitext(SongName[num])#分割文件名和扩展名# self.label.setText(wenjianming)#设置标签的文本为音乐的名字print(SongPath[num])self.photo(num)a, f = os.path.split(SongPath[num])  # 分割文件名f, ex = os.path.splitext(f)# self.label.setText(wenjianming)#设置标签的文本为音乐的名字self.label.setText(f)pygame.mixer.music.load(SongPath[num])  # 载入音乐pygame.mixer.music.play()  # 播放音乐2self.label3.setText(str(pygame.mixer.music.get_volume()))r = 0for i in SongName:# self.listwidget.addItem(i)#将文件名添加到listWidgetself.listwidget.addItem(i)self.listwidget.item(r).setForeground(QtCore.Qt.white)r = r + 1# self.next(self)except:return

下面是音量加和音量减

    def voiceup(self): print ('up')global voicevoice+=0.1if voice>1:voice=1pygame.mixer.music.set_volume(voice)def voicedown(self):print ('down')global voicevoice-=0.1if voice<0:voice=0pygame.mixer.music.set_volume(voice)

这个是播放和暂停

    def pause(self):global pauseif pause:try:pygame.mixer.music.unpause()except:passself.console_button_3.setIcon(qtawesome.icon('fa.pause', color='#3FC89C', font=18))pause = Falseelse:try:pygame.mixer.music.pause()except:passself.console_button_3.setIcon(qtawesome.icon('fa.play', color='#F76677', font=18))pause = True

下面的添加目录:

    def add(self):try:global SongPathglobal numglobal filewglobal asasnum = 0fileN = QtWidgets.QFileDialog.getExistingDirectory(None,"选取文件夹","")self.listwidget.clear()filew = fileN +'/'asas = filewl1 = [name for name in os.listdir(fileN)if name.endswith('.mp3')]l2 = [name for name in os.listdir(fileN)if name.endswith('.flac')]l3 = [name for name in os.listdir(fileN)if name.endswith('wma')]SongName = l1 +l2+l3SongPath =[filew +i for i in SongName]print (SongPath)   #self.Timer.timeout.connect(self.timercontorl)#时间函数,与下面的进度条和时间显示有关#self.label = os.path.splitext(SongName[num])#分割文件名和扩展名   #self.label.setText(wenjianming)#设置标签的文本为音乐的名字    print (SongPath[num])  r = 0for i in SongName:#self.listwidget.addItem(i)#将文件名添加到listWidgetself.listwidget.addItem(i)self.listwidget.item(r).setForeground(QtCore.Qt.white)r = r +1#self.next(self)except:filew = asas

让pyqt5界面移动的代码块**

    def mousePressEvent(self, event):#if event.button()==QtWidgets.QPushButton:self.m_flag=Trueself.m_Position=event.globalPos()-self.pos() #获取鼠标相对窗口的位置event.accept()#self.setCursor(QCursor(Qt.OpenHandCursor))  #更改鼠标图标def mouseMoveEvent(self, QMouseEvent):#if QtWidgets.QPushButton and self.m_flag:  self.move(QMouseEvent.globalPos()-self.m_Position)#更改窗口位置QMouseEvent.accept()def mouseReleaseEvent(self, QMouseEvent):self.m_flag=False#self.setCursor(QCursor(Qt.ArrowCursor))

上面item绑定的是双击版本的,此外我还写了单击的版本,如下:

    def clicked(self,item):global pauseprint(str(item.text()))self.console_button_3.setIcon(qtawesome.icon('fa.pause', color='#F76677', font=18))pause = False#QMessageBox.information(self, "ListWidget", "你选择了: "+item.text())# 显示出消息提示框fill = filew +item.text()print (fill)pygame.mixer.stop()pygame.mixer.init()self.Timer=QTimer()    self.Timer.start(500)        pygame.mixer.music.load(fill)#载入音乐pygame.mixer.music.play()#播放音乐

由于这个还只是刚开始的版本,以后还会继续更新,目前版本的bug已被修复

2021/6/21

添加了提取音频文件的功能,效果图如下


上面的图片是经过画圆处理的,从文件提取出来的代码如下

    def photo(self,num):try:audio = File(SongPath[num])mArtwork = audio.tags['APIC:'].datawith open('ls.png', 'wb') as img:img.write(mArtwork)try:lsfile = './ls.png'safile = './1.png'draw(lsfile,safile)pix_img = QtGui.QPixmap('./1.png')pix = pix_img.scaled(300, 300, QtCore.Qt.KeepAspectRatio)self.label5.setPixmap(pix)except:print ('do error')pix_img = QtGui.QPixmap('./ls.png')pix = pix_img.scaled(300, 300, QtCore.Qt.KeepAspectRatio)self.label5.setPixmap(pix)except:print('no picture')if  os.path.exists("2.png"):pix_img = QtGui.QPixmap('./2.png')pix = pix_img.scaled(300, 300, QtCore.Qt.KeepAspectRatio)self.label5.setPixmap(pix)else:try:req = requests.get('https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fy.gtimg.cn%2Fmusic%2Fphoto_new%2FT001R300x300M000002ztBMe06cOx0.jpg%3Fmax_age%3D2592000&refer=http%3A%2F%2Fy.gtimg.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625464213&t=a30c07bda8c2ab7d8001a59353e936e0')checkfile  = open('ls2.png','w+b')for i in req.iter_content(100000):checkfile.write(i)checkfile.close()lsfile = './ls2.png'safile = './2.png'draw(lsfile,safile)except:print ('download error')pix_img = QtGui.QPixmap('./2.png')pix = pix_img.scaled(300, 300, QtCore.Qt.KeepAspectRatio)self.label5.setPixmap(pix)passpass

下面的是画圆的代码

def crop_max_square(pil_img):return crop_center(pil_img, min(pil_img.size), min(pil_img.size))def crop_center(pil_img, crop_width, crop_height):img_width, img_height = pil_img.sizereturn pil_img.crop(((img_width - crop_width) // 2,(img_height - crop_height) // 2,(img_width + crop_width) // 2,(img_height + crop_height) // 2))def mask_circle_transparent(pil_img, blur_radius, offset=0):offset = blur_radius * 2 + offsetmask = Image.new("L", pil_img.size, 0)draw = ImageDraw.Draw(mask)draw.ellipse((offset, offset, pil_img.size[0] - offset, pil_img.size[1] - offset), fill=255)mask = mask.filter(ImageFilter.GaussianBlur(blur_radius))result = pil_img.copy()result.putalpha(mask)return resultdef draw(lsfile,safile):markImg = Image.open(lsfile)thumb_width = 600im_square = crop_max_square(markImg).resize((thumb_width, thumb_width), Image.LANCZOS)im_thumb = mask_circle_transparent(im_square, 0)im_thumb.save(safile)os.remove(lsfile)

全部代码如下

# coding:utf-8# from PyQt5 import QtCore,QtGui,QtWidgets
import sys
import re
import pygamefrom mutagen import File
import time
import os, math
from PIL import Image, ImageDraw, ImageFilter
# import requests
# import jsonpath
# from mutagen.mp3 import MP3
# from mutagen import File
# from urllib.request import urlretrieve
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QFileDialog, QMessageBox, QListWidget, QLabel, QListWidgetItem, QApplication, QWidget
from PyQt5.QtCore import QTimer, QDateTime, Qt
from PyQt5.QtGui import QIcon, QPixmap, QColor, QPainter, QPixmap
from PyQt5 import QtMultimedia, QtWidgets, QtCore
from PyQt5.QtGui import QFont, QCursor
import qtawesome
import threading
import random
import requestsplay = 'shun'
stop = False
SongPath = []
filew = 1
num = 0
voice = 0.5
pause = False
asas = 1
big = Falseclass MainUi(QtWidgets.QMainWindow):def __init__(self):super().__init__()self.init_ui()#self.start()try:icon_path = os.path.join(os.path.dirname(__file__), './logo.ico')icon = QIcon()icon.addPixmap(QPixmap(icon_path))  # 这是对的。self.setWindowIcon(icon)except:passt1 = threading.Thread(target=self.action)t1.setDaemon(True)t1.start()def init_ui(self):self.setFixedSize(960, 700)self.main_widget = QtWidgets.QWidget()  # 创建窗口主部件self.main_layout = QtWidgets.QGridLayout()  # 创建主部件的网格布局self.main_widget.setLayout(self.main_layout)  # 设置窗口主部件布局为网格布局self.close_widget = QtWidgets.QWidget()  # 创建关闭侧部件self.close_widget.setObjectName('close_widget')self.close_layout = QtWidgets.QGridLayout()  # 创建左侧部件的网格布局层self.close_widget.setLayout(self.close_layout)  # 设置左侧部件布局为网格self.left_widget = QtWidgets.QWidget()  # 创建左边侧部件self.left_widget.setObjectName('left_widget')self.left_layout = QtWidgets.QGridLayout()  # 创建左侧部件的网格布局层self.left_widget.setLayout(self.left_layout)  # 设置左侧部件布局为网格self.right_widget = QtWidgets.QWidget()  # 创建右侧部件self.right_widget.setObjectName('right_widget')self.right_layout = QtWidgets.QGridLayout()self.right_widget.setLayout(self.right_layout)  # 设置右侧部件布局为网格self.down_widget = QtWidgets.QWidget()  # 创建下面部件self.down_widget.setObjectName('down_widget')self.down_layout = QtWidgets.QGridLayout()self.down_widget.setLayout(self.down_layout)  # 设置下侧部件布局为网格self.label = QLabel(self)self.label.setText("first line")self.label.setStyleSheet("color:white")self.label.setMaximumSize(310, 20)self.main_layout.addWidget(self.right_widget, 0, 20, 90, 90)  # 22右侧部件在第0行第3列,占8行9列self.down_layout.addWidget(self.label, 1, 0, 1, 1)self.main_layout.addWidget(self.left_widget, 0, 0, 90, 20)self.main_layout.addWidget(self.down_widget, 100, 0, 10, 110)self.main_layout.addWidget(self.close_widget, 0, 107, 1, 3)  # 左侧部件在第0行第0列,占1行3列self.setCentralWidget(self.main_widget)  # 设置窗口主部件self.listwidget = QListWidget(self)self.listwidget.doubleClicked.connect(lambda: self.change_func(self.listwidget))self.right_layout.addWidget(self.listwidget, 3, 0, 100, 90)self.listwidget.setStyleSheet('''background-color:transparent''')self.left_close = QtWidgets.QPushButton("")  # 关闭按钮self.left_close.clicked.connect(self.close)self.left_visit = QtWidgets.QPushButton("")  # 空白按钮self.left_visit.clicked.connect(self.big)self.left_mini = QtWidgets.QPushButton("")  # 最小化按钮self.left_mini.clicked.connect(self.mini)self.close_layout.addWidget(self.left_mini, 0, 0, 1, 1)self.close_layout.addWidget(self.left_close, 0, 2, 1, 1)self.close_layout.addWidget(self.left_visit, 0, 1, 1, 1)self.left_close.setFixedSize(15, 15)  # 设置关闭按钮的大小self.left_visit.setFixedSize(15, 15)  # 设置按钮大小self.left_mini.setFixedSize(15, 15)  # 设置最小化按钮大小self.left_close.setStyleSheet('''QPushButton{background:#F76677;border-radius:5px;}QPushButton:hover{background:red;}''')self.left_visit.setStyleSheet('''QPushButton{background:#F7D674;border-radius:5px;}QPushButton:hover{background:yellow;}''')self.left_mini.setStyleSheet('''QPushButton{background:#6DDF6D;border-radius:5px;}QPushButton:hover{background:green;}''')self.left_add = QtWidgets.QPushButton("添加")  # 添加按钮self.left_layout.addWidget(self.left_add, 0, 0, 2, 2)self.left_add.setStyleSheet('''QPushButton{background:#F76677;border-radius:5px;}QPushButton:hover{background:red;}''')self.left_add.clicked.connect(self.add)self.label2 = QLabel(self)self.label2.setText("当前为顺序播放")self.label2.setStyleSheet("color:#6DDF6D")self.left_layout.addWidget(self.label2, 4, 0, 2, 2)self.label3 = QLabel(self)self.label3.setText("")self.label3.setStyleSheet("color:white")self.down_layout.addWidget(self.label3, 1, 3, 1, 1)self.label7 = QLabel(self)self.label7.setText("")self.label7.setStyleSheet("color:white")'''self.label1 = QLabel(self)self.label1.setText("first line")self.label1.setStyleSheet("color:white")'''self.label5 = QLabel(self)#self.label5.setScaledContents(True)pix_img = QtGui.QPixmap('./2.png')pix = pix_img.scaled(300, 300, QtCore.Qt.KeepAspectRatio)self.label5.setPixmap(pix)#self.label5.setMaximumSize(1,1)self.left_layout.addWidget(self.label5,2,0,2,2)self.label6 = QLabel(self)self.label6.setText("")self.label6.setStyleSheet("color:#6DDF6D")self.left_layout.addWidget(self.label6, 2, 0, 2, 2)self.right_process_bar = QtWidgets.QProgressBar()  # 播放进度部件self.right_process_bar.setValue(49)self.right_process_bar.setFixedHeight(3)  # 设置进度条高度self.right_process_bar.setTextVisible(False)  # 不显示进度条文字self.right_playconsole_widget = QtWidgets.QWidget()  # 播放控制部件self.right_playconsole_layout = QtWidgets.QGridLayout()  # 播放控制部件网格布局层self.right_playconsole_widget.setLayout(self.right_playconsole_layout)self.console_button_1 = QtWidgets.QPushButton(qtawesome.icon('fa.backward', color='#3FC89C'), "")self.console_button_1.clicked.connect(self.last)self.console_button_1.setStyleSheet('''QPushButton{background:#172940;border-radius:5px;}QPushButton:hover{background:#3684C8;}''')self.console_button_2 = QtWidgets.QPushButton(qtawesome.icon('fa.forward', color='#3FC89C'), "")self.console_button_2.clicked.connect(self.nextion)self.console_button_2.setStyleSheet('''QPushButton{background:#172940;border-radius:5px;}QPushButton:hover{background:#3684C8;}''')self.console_button_3 = QtWidgets.QPushButton(qtawesome.icon('fa.pause', color='#3FC89C', font=18), "")self.console_button_3.clicked.connect(self.pause)self.console_button_3.setStyleSheet('''QPushButton{background:#172940;border-radius:5px;}QPushButton:hover{background:#3684C8;}''')self.console_button_4 = QtWidgets.QPushButton(qtawesome.icon('fa.volume-down', color='#3FC89C', font=18), "")self.console_button_4.clicked.connect(self.voicedown)self.console_button_4.setStyleSheet('''QPushButton{background:#172940;border-radius:5px;}QPushButton:hover{background:#3684C8;}''')self.console_button_5 = QtWidgets.QPushButton(qtawesome.icon('fa.volume-up', color='#3FC89C', font=18), "")self.console_button_5.clicked.connect(self.voiceup)self.console_button_5.setStyleSheet('''QPushButton{background:#172940;border-radius:5px;}QPushButton:hover{background:#3684C8;}''')self.console_button_6 = QtWidgets.QPushButton(qtawesome.icon('fa.align-center', color='#3FC89C', font=18), "")self.console_button_6.clicked.connect(self.playmode)self.console_button_6.setStyleSheet('''QPushButton{background:#172940;border-radius:5px;}QPushButton:hover{background:#3684C8;}''')self.console_button_3.setIconSize(QtCore.QSize(30, 30))self.right_playconsole_layout.addWidget(self.console_button_1, 0, 1)self.right_playconsole_layout.addWidget(self.console_button_2, 0, 3)self.right_playconsole_layout.addWidget(self.console_button_3, 0, 2)self.right_playconsole_layout.addWidget(self.console_button_4, 0, 0)self.right_playconsole_layout.addWidget(self.console_button_5, 0, 4)self.right_playconsole_layout.addWidget(self.console_button_6, 0, 5)self.right_playconsole_layout.setAlignment(QtCore.Qt.AlignCenter)  # 设置布局内部件居中显示self.down_layout.addWidget(self.right_process_bar, 0, 0, 1, 4)  # 第0行第0列,占8行3列# 第0行第0列,占8行3列self.down_layout.addWidget(self.label7, 1, 2, 1, 1)#self.down_layout.addWidget(self.label1, 1, 0, 1, 2)self.down_layout.addWidget(self.right_playconsole_widget, 1, 0, 1, 4)self.right_process_bar.setStyleSheet('''QProgressBar::chunk {background-color: #F76677;}''')self.right_playconsole_widget.setStyleSheet('''QPushButton{border:none;}''')self.left_widget.setStyleSheet('''QPushButton{border:none;color:white;}QPushButton#left_label{border:none;border-bottom:1px solid white;font-size:18px;font-weight:700;font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;}QPushButton#left_button:hover{border-left:4px solid red;font-weight:700;}QWidget#left_widget{background:#2B2B2B;border-top:1px solid white;border-bottom:1px solid white;border-left:1px solid white;border-top-left-radius:10px;border-bottom-left-radius:10px;}''')self.close_widget.setStyleSheet('''QPushButton{border:none;color:white;}QPushButton#close_label{border:none;border-bottom:1px solid white;font-size:18px;font-weight:700;font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;}QPushButton#close_button:hover{border-left:4px solid red;font-weight:700;}QWidget#close_widget{background:#232C51;border-top:1px solid white;border-bottom:1px solid white;border-left:1px solid white;border-top-left-radius:10px;border-bottom-left-radius:10px;border-top-right-radius:10px;border-bottom-right-radius:10px;}''')self.right_widget.setStyleSheet('''QWidget#right_widget{color:#232C51;background:#191618;border-top:1px solid darkGray;border-bottom:1px solid darkGray;border-right:1px solid darkGray;border-top-right-radius:10px;border-bottom-right-radius:10px;}QLabel#right_lable{border:none;font-size:16px;font-weight:700;font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;}''')self.down_widget.setStyleSheet('''QWidget#down_widget{color:#172940;background:#172940;border-top:1px solid darkGray;border-bottom:1px solid darkGray;border-right:1px solid darkGray;border-top-right-radius:10px;border-bottom-right-radius:10px;border-top-left-radius:10px;border-bottom-left-radius:10px;}QLabel#down_lable{border:none;font-size:16px;font-weight:700;font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;}''')self.setWindowOpacity(0.9)  # 设置窗口透明度self.setAttribute(QtCore.Qt.WA_TranslucentBackground)self.setWindowFlag(QtCore.Qt.FramelessWindowHint)  # 隐藏边框self.main_layout.setSpacing(0)# 以下为窗口控制代码def big(self):global bigprint (big)if not big:self.setWindowState(Qt.WindowMaximized)big = Trueelif big:self.setWindowState(Qt.WindowNoState)big = False# print (windowState())def close(self):reply = QtWidgets.QMessageBox.question(self, u'警告', u'确定退出?', QtWidgets.QMessageBox.Yes,QtWidgets.QMessageBox.No)if reply == QtWidgets.QMessageBox.Yes:close = Truetry:pygame.mixer.music.stop()except:passsys.exit()else:passdef mini(self):self.showMinimized()def mousePressEvent(self, event):global bigbig = Falseself.setWindowState(Qt.WindowNoState)# if event.button()==QtWidgets.QPushButton:self.m_flag = Trueself.m_Position = event.globalPos() - self.pos()  # 获取鼠标相对窗口的位置event.accept()def mouseMoveEvent(self, QMouseEvent):global bigbig = Falseself.setWindowState(Qt.WindowNoState)# if QtWidgets.QPushButton and self.m_flag:self.move(QMouseEvent.globalPos() - self.m_Position)  # 更改窗口位置QMouseEvent.accept()def mouseReleaseEvent(self, QMouseEvent):global bigbig = Falseself.setWindowState(Qt.WindowNoState)self.m_flag = Falsedef closeEvent(self, event):reply = QtWidgets.QMessageBox.question(self, u'警告', u'是否退出?', QtWidgets.QMessageBox.Yes,QtWidgets.QMessageBox.No)if reply == QtWidgets.QMessageBox.Yes:sys.exit()else:event.ignore()# 以下为功能代码def dis(self):passdef photo(self,num):try:audio = File(SongPath[num])mArtwork = audio.tags['APIC:'].datawith open('ls.png', 'wb') as img:img.write(mArtwork)try:lsfile = './ls.png'safile = './1.png'draw(lsfile,safile)pix_img = QtGui.QPixmap('./1.png')pix = pix_img.scaled(300, 300, QtCore.Qt.KeepAspectRatio)self.label5.setPixmap(pix)except:print ('do error')pix_img = QtGui.QPixmap('./ls.png')pix = pix_img.scaled(300, 300, QtCore.Qt.KeepAspectRatio)self.label5.setPixmap(pix)except:print('no picture')if  os.path.exists("2.png"):pix_img = QtGui.QPixmap('./2.png')pix = pix_img.scaled(300, 300, QtCore.Qt.KeepAspectRatio)self.label5.setPixmap(pix)else:try:req = requests.get('https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fy.gtimg.cn%2Fmusic%2Fphoto_new%2FT001R300x300M000002ztBMe06cOx0.jpg%3Fmax_age%3D2592000&refer=http%3A%2F%2Fy.gtimg.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625464213&t=a30c07bda8c2ab7d8001a59353e936e0')checkfile  = open('ls2.png','w+b')for i in req.iter_content(100000):checkfile.write(i)checkfile.close()lsfile = './ls2.png'safile = './2.png'draw(lsfile,safile)except:print ('download error')pix_img = QtGui.QPixmap('./2.png')pix = pix_img.scaled(300, 300, QtCore.Qt.KeepAspectRatio)self.label5.setPixmap(pix)passpassdef bofang(self, num):try:global pauseself.photo(num)self.console_button_3.setIcon(qtawesome.icon('fa.pause', color='#F76677', font=18))pause = False# QMessageBox.information(self, "ListWidget", "你选择了: "+item.text())# 显示出消息提示框fill = SongPath[num]print(fill)try:pygame.mixer.stop()except:passpygame.mixer.init()try:self.Timer = QTimer()self.Timer.start(500)except:passpygame.mixer.music.load(SongPath[num])  # 载入音乐pygame.mixer.music.play()  # 播放音乐except:time.sleep(0.1)print ('system error')self.next()passdef playmode(self):global playtry:if play == 'shun':play = 'shui'print('随机播放')self.label2.setText("当前为随机播放")try:self.console_button_6.setIcon(qtawesome.icon('fa.random', color='#3FC89C', font=18))print('done')except:print('none')pass# self.left_shui.setText('切换为单曲循环')elif play == 'shui':play = 'always'print('单曲循环')self.label2.setText("当前为单曲循环")try:self.console_button_6.setIcon(qtawesome.icon('fa.retweet', color='#3FC89C', font=18))print('done')except:print('none')# self.left_shui.setText('切换为顺序播放')elif play == 'always':play = 'shun'print('顺序播放')self.label2.setText("当前为顺序播放")try:self.console_button_6.setIcon(qtawesome.icon('fa.align-center', color='#3FC89C', font=18))print('done')except:print('none')# self.left_shui.setText('切换为随机播放')except:print('error')passdef action(self):a = 1global numwhile a < 2:# print ('checking')try:time.sleep(1)if not pygame.mixer.music.get_busy() and pause == False:if play == 'shun':print('shuning')self.next()elif play == 'shui':print('shuiing')self.shui()elif play == 'always':print('alwaysing')self.always()except:print('no')passelse:pygame.mixer.music.stop()def nextion(self):try:if play == 'shun':print('shuning')self.next()elif play == 'shui':print('shuiing')self.shui()elif play == 'always':print('alwaysing')self.next()except:print('no')passdef add(self):try:global SongPathglobal numglobal filewglobal asasnum = 0fileN = QtWidgets.QFileDialog.getExistingDirectory(None, "选取文件夹", "")self.listwidget.clear()filew = fileN + '/'asas = filewl1 = [name for name in os.listdir(fileN) if name.endswith('.mp3')]l2 = [name for name in os.listdir(fileN) if name.endswith('.flac')]l3 = [name for name in os.listdir(fileN) if name.endswith('wma')]SongName = l1 + l2 + l3SongPath = [filew + i for i in SongName]print(SongPath)# self.Timer.timeout.connect(self.timercontorl)#时间函数,与下面的进度条和时间显示有关# self.label = os.path.splitext(SongName[num])#分割文件名和扩展名# self.label.setText(wenjianming)#设置标签的文本为音乐的名字print(SongPath[num])r = 0for i in SongName:# self.listwidget.addItem(i)#将文件名添加到listWidgetself.listwidget.addItem(i)self.listwidget.item(r).setForeground(QtCore.Qt.white)r = r + 1# self.next(self)except:filew = asasdef start(self):try:global SongPathglobal numglobal filewglobal asasif not os.path.exists("2.png"):try:req = requests.get('https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fy.gtimg.cn%2Fmusic%2Fphoto_new%2FT001R300x300M000002ztBMe06cOx0.jpg%3Fmax_age%3D2592000&refer=http%3A%2F%2Fy.gtimg.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625464213&t=a30c07bda8c2ab7d8001a59353e936e0')checkfile  = open('ls2.png','w+b')for i in req.iter_content(100000):checkfile.write(i)checkfile.close()lsfile = './ls2.png'safile = './2.png'draw(lsfile,safile)except:print ('download error')passfileN = QtWidgets.QFileDialog.getExistingDirectory(None, "选取文件夹", "")filew = fileN + '/'asas = filewl1 = [name for name in os.listdir(fileN) if name.endswith('.mp3')]l2 = [name for name in os.listdir(fileN) if name.endswith('.flac')]l3 = [name for name in os.listdir(fileN) if name.endswith('wma')]SongName = l1 + l2 + l3SongPath = [filew + i for i in SongName]print(SongPath)pygame.mixer.init()self.Timer = QTimer()self.Timer.start(500)# self.Timer.timeout.connect(self.timercontorl)#时间函数,与下面的进度条和时间显示有关# self.label = os.path.splitext(SongName[num])#分割文件名和扩展名# self.label.setText(wenjianming)#设置标签的文本为音乐的名字print(SongPath[num])self.photo(num)a, f = os.path.split(SongPath[num])  # 分割文件名f, ex = os.path.splitext(f)# self.label.setText(wenjianming)#设置标签的文本为音乐的名字self.label.setText(f)pygame.mixer.music.load(SongPath[num])  # 载入音乐pygame.mixer.music.play()  # 播放音乐2self.label3.setText(str(pygame.mixer.music.get_volume()))r = 0for i in SongName:# self.listwidget.addItem(i)#将文件名添加到listWidgetself.listwidget.addItem(i)self.listwidget.item(r).setForeground(QtCore.Qt.white)r = r + 1# self.next(self)except:returndef change_func(self, listwidget):global numitem = QListWidgetItem(self.listwidget.currentItem())print(item.text())# print (item.flags())num = int(listwidget.currentRow())a, f = os.path.split(SongPath[num])  # 分割文件名f, ex = os.path.splitext(f)# self.label.setText(wenjianming)#设置标签的文本为音乐的名字self.label.setText(f)print(listwidget.currentRow())self.bofang(num)def pause(self):global pauseif pause:try:pygame.mixer.music.unpause()except:passself.console_button_3.setIcon(qtawesome.icon('fa.pause', color='#3FC89C', font=18))pause = Falseelse:try:pygame.mixer.music.pause()except:passself.console_button_3.setIcon(qtawesome.icon('fa.play', color='#F76677', font=18))pause = Truedef voiceup(self):print('up')global voicevoice += 0.1if voice > 1:voice = 1pygame.mixer.music.set_volume(voice)self.label3.setText(str(pygame.mixer.music.get_volume()))def voicedown(self):print('down')global voicevoice -= 0.1if voice < 0:voice = 0pygame.mixer.music.set_volume(voice)self.label3.setText(str(pygame.mixer.music.get_volume()))def shui(self):global numglobal SongPathq = int(len(SongPath) - 1)num = int(random.randint(1, q))try:print('shui')pygame.mixer.init()self.Timer = QTimer()self.Timer.start(500)# self.Timer.timeout.connect(self.timercontorl)#时间函数,与下面的进度条和时间显示有关a, f = os.path.split(SongPath[num])  # 分割文件名f, ex = os.path.splitext(f)# self.label.setText(wenjianming)#设置标签的文本为音乐的名字self.label.setText(f)pygame.mixer.music.load(SongPath[num])  # 载入音乐pygame.mixer.music.play()  # 播放音乐except:passdef next(self):global numglobal SongPathif num == len(SongPath) - 1:print('冇')num = 0else:num = num + 1try:self.photo(num)print('next')pygame.mixer.init()self.Timer = QTimer()self.Timer.start(500)# self.Timer.timeout.connect(self.timercontorl)#时间函数,与下面的进度条和时间显示有关a, f = os.path.split(SongPath[num])  # 分割文件名f, ex = os.path.splitext(f)# self.label.setText(wenjianming)#设置标签的文本为音乐的名字self.label.setText(f)pygame.mixer.music.load(SongPath[num])  # 载入音乐pygame.mixer.music.play()  # 播放音乐except:passdef always(self):try:self.photo(num)print('always')pygame.mixer.init()self.Timer = QTimer()self.Timer.start(500)# self.Timer.timeout.connect(self.timercontorl)#时间函数,与下面的进度条和时间显示有关a, f = os.path.split(SongPath[num])  # 分割文件名f, ex = os.path.splitext(f)# self.label.setText(wenjianming)#设置标签的文本为音乐的名字self.label.setText(f)pygame.mixer.music.load(SongPath[num])  # 载入音乐pygame.mixer.music.play()  # 播放音乐except:passdef last(self):global numglobal SongPathif num == 0:print('冇')num = len(SongPath) - 1else:num = num - 1try:self.photo(num)pygame.mixer.init()self.Timer = QTimer()self.Timer.start(500)a, f = os.path.split(SongPath[num])  # 分割文件名f, ex = os.path.splitext(f)# self.label.setText(wenjianming)#设置标签的文本为音乐的名字self.label.setText(f)pygame.mixer.music.load(SongPath[num])  # 载入音乐pygame.mixer.music.play()  # 播放音乐except:passdef keyPressEvent(self, QKeyEvent):if QKeyEvent.modifiers() == Qt.ControlModifier and QKeyEvent.key() == Qt.Key_A:  # 键盘某个键被按下时调用print('surpise')def crop_max_square(pil_img):return crop_center(pil_img, min(pil_img.size), min(pil_img.size))def crop_center(pil_img, crop_width, crop_height):img_width, img_height = pil_img.sizereturn pil_img.crop(((img_width - crop_width) // 2,(img_height - crop_height) // 2,(img_width + crop_width) // 2,(img_height + crop_height) // 2))def mask_circle_transparent(pil_img, blur_radius, offset=0):offset = blur_radius * 2 + offsetmask = Image.new("L", pil_img.size, 0)draw = ImageDraw.Draw(mask)draw.ellipse((offset, offset, pil_img.size[0] - offset, pil_img.size[1] - offset), fill=255)mask = mask.filter(ImageFilter.GaussianBlur(blur_radius))result = pil_img.copy()result.putalpha(mask)return resultdef draw(lsfile,safile):markImg = Image.open(lsfile)thumb_width = 600im_square = crop_max_square(markImg).resize((thumb_width, thumb_width), Image.LANCZOS)im_thumb = mask_circle_transparent(im_square, 0)im_thumb.save(safile)os.remove(lsfile)def main():app = QtWidgets.QApplication(sys.argv)gui = MainUi()gui.show()sys.exit(app.exec_())if __name__ == '__main__':main()#啦啦啦啦啦啦啦啦啦,今天2021/6/1,儿童节快乐鸭[]~( ̄▽ ̄)~*

接下来还会出网络版本,敬请期待
先透露一点源码吧

import requests
import re
from bs4 import BeautifulSoupheaders = {'Host': 'music.163.com','Referer': 'http://music.163.com/','User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36'
}url = 'http://music.163.com/discover/toplist'
r = requests.session()
r = BeautifulSoup(r.get(url, headers=headers).content,features="lxml")
result = r.find('ul', {'class': 'f-hide'}).find_all('a')
# print(reslut)music = []  # 用于接受返回值
musicpath = []
for mu in result:# print('{}:{}'.format(music.text,music['href']))c = '{}:{}'.format(mu.text, mu['href'])k,p = c.split('=')#a = filter(str.isdigit,  p)b = ("https://music.163.com/song/media/outer/url?id=" + str(p) + ".mp3")music.append(c)musicpath.append(b)
print(music)
music[1]
from pprint import pprint  # 格式化输出
print(musicpath)
num = 1
print (musicpath[num])
url = 'https://music.163.com/song/media/outer/url?id=1835009703.mp3'
data = requests.get(str(url)).content
with open('1.mp3','wb')as f:f.write(data)

pyqt5+pygame实现音乐播放器,可以自动提取文件图片,最终版本相关推荐

  1. 使用pygame实现音乐播放器(一)

    目录 一.pygame的安装 1 图形界面安装 2 命令行安装 3 pygame最简结构 二.音乐播放器的实现 1 图片显示 2 播放音乐 Pygame 是一组用来开发游戏软件的Python程序模块, ...

  2. pygame编写音乐播放器

    pygame编写音乐播放器 1.准备工作 2.开始 2.1 设计说明 2.2 代码逻辑 收集某个目录下的所有mp3 显示歌曲名称 播放歌曲 显示播放进度 快进快退功能 画播放控件 主逻辑 3.效果图 ...

  3. PyQt5实现简易音乐播放器

    PyQt5实现简易音乐播放器 环境 vscode python 3.10.0 PyQt5 5.15.4 功能目标 能够读取本地的音乐文件,并实现播放的开关.曲目的切换和音量的加减 具体实现 新建一个文 ...

  4. 基于Python+tkinter+pygame的音乐播放器完整源码

    import os import tkinter import tkinter.filedialog import random import time import threading import ...

  5. Pygame制作音乐播放器

    使用pygame制作的包含基本功能和画面效果的简单音乐播放器 实现如下功能: 基本音乐播放器功能:播放,暂停,继续播放,上一曲,下一曲,可以在图形界面或键盘操作 (播放:小键盘回车, 暂停:p, 继续 ...

  6. 利用PyQt5制作本地音乐播放器

    介绍 本文是对之前的音乐播放器的一些改进和功能实现.只写了有变化的部分,具体部分请看上一篇博客. [利用PyQt5和QSS制作本地音乐播放器(初稿)](https://blog.csdn.net/we ...

  7. 音乐播放器:打开文件对话框

    制作了一个简单的音乐播放器.具有打开电脑里面的文件,选择歌曲播放 主要是为了掌握,打开文件夹,选择文件的 1 private void Frm_Load(object sender, EventArg ...

  8. 用Python自带的tkinter制作一款简易音乐播放器(附工程文件)

    tkinter GUI 界面: 基于tkinter库实现简易可视化界面,并调用pygame等第三方库实现播放歌曲.切换歌曲.歌曲进度调整.批量导入曲库等基本功能:程序设置为单曲循环模式,需要手动切换歌 ...

  9. java歌词高亮显示滚动_js如何处理音乐播放器的歌词文件达到高亮以及滚动的效果?...

    原理 把每句歌词都输出为一个li元素,添加data-timeline为该歌词的时间 监听 audio的timeupdate时间,遍历第1步添加的歌词,检测data-timeline为当前audio播放 ...

最新文章

  1. cocos lua 加密方案
  2. 为什么ConcurrentHashMap的读操作不需要加锁?
  3. 病毒导致分区双击无法打开的解决方法
  4. Codeforces Round #108 (Div. 2)
  5. AssetManager asset的使用
  6. ubuntu双系统时间同步_解决Ubuntu 16.04.6 + Win10 双系统时间错误且不一致问题
  7. 剪纸窗花PSD分层素材|春节的常见元素,轻松应用到海报设计
  8. 555定时器的应用——多谐振荡器
  9. 阶段3 1.Mybatis_03.自定义Mybatis框架_1.自定义Mybatis的分析-执行查询所有分析
  10. 【云计算】Netflix 开源持续交付平台 Spinnaker
  11. centos7修改ip(centos7修改时区)
  12. 智慧医疗整体解决方案(图文)
  13. golang操作sqlite3
  14. OneAPIConnect(一) 欧姆龙FINS协议实现源代码
  15. Linux Mint 19 Tara x86_64安装Docker-ce
  16. 不要迷恋哥,哥只是个传说 - 生活至上,美容至尚!
  17. 在labview中实现jk触发器使用JK触发器实现时序逻辑电路
  18. 如何快速的登陆github
  19. 【GPU】Nvidia CUDA 编程基础教程——利用基本的 CUDA 内存管理技术来优化加速应用程序
  20. A段架构设计_隽语集(Business Thinking _1301)

热门文章

  1. 蛋花花:人工智能写的诗版权到底算谁的
  2. 看PDF时点击书签页面变小的解决方法
  3. 苹果或将微信下架系谣言,苹果微信牵手ios11
  4. canvas制作钟表小案例
  5. python 中右移、左移运算符的作用
  6. IMP-00017: following statement failed with ORACLE error 20005:(表统计信息被锁)
  7. Basler工业相机python开发(Pypylon)
  8. android手机到iphone6s,iPhone6s相当于现在什么档次的安卓手机?结果让国产手机品牌汗颜...
  9. shell 脚本获取接口返回值
  10. program received signal sigsegv,需要注意的问题!!!!!!