self.work.start()
self.work.trigger.connect(self.dispng)
r = 0
self.listwidget3.clear()
for i in loves:
self.listwidget3.addItem(i)
self.listwidget3.item(r).setForeground(Qt.white)
r = r + 1
print(loves)
else:
pass
通过右键音乐列表进行喜爱的歌曲添加
def addItem(self):
try:
global loves
global loveurls
global lovepics
global lovelrc
if list_confident == ‘boing’:
loves.append(songs[num_m])
loveurls.append(urls[num_m])
lovepics.append(pic[num_m])
lovelrc.append(lrcs[num_m])
else:
loves.append(songed[num_m])
loveurls.append(urled[num_m])
lovepics.append(picd[num_m])
lovelrc.append(lrcd[num_m])
self.work = firstThread()
self.work.start()
self.work.trigger.connect(self.dispng)
except:
pass
r = 0
self.listwidget3.clear()
for i in loves:
self.listwidget3.addItem(i)
self.listwidget3.item®.setForeground(Qt.white)
r = r + 1
print(‘done’)
print(loves)
这样我们就可以把歌曲添加到喜爱的歌子列表页面下,如下图所示。
![在这里插入图片描述](https://img-blog.csdnimg.cn/095ecc38a70049aa9a6b6af8f22ec59d.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBARHJhZ29u5bCR5bm0,size_20,color_FFFFFF,t_70,g_se,x_16)
##### 3. 喜爱的歌初始化读取显示及列表播放
对于添加到喜爱的歌曲列表,我们需要在退出音乐播放器程序时,将这些数据保存到本地文件,方便后面重新运行时初始化读取显示列表。
**喜爱歌曲本地保存:**
我们可以把喜爱的歌曲列表、喜爱歌曲图片、歌曲url链接、歌词等数据保存到本地。核心代码如下:
def close(self):
reply = QMessageBox.question(self, u’警告’, u’确定退出?', QMessageBox.Yes,
QMessageBox.No)
if reply == QMessageBox.Yes:
close = True
try:
mixer.music.stop()
except:
pass
try:
rmtree(str(data))
except Exception as e:
print(‘删除错误类型是’, e.class.name)
print(‘删除错误明细是’, e)
filepath = ‘{}/musicdata’.format(apdata)
try:
mkdir(filepath)
except:
pass
print(filepath)
with open(filepath + “/loves”, ‘w’, encoding=‘utf-8’) as f:
f.truncate(0)
print(f.write(str(loves)))
with open(filepath + “/lovepics”, ‘w’, encoding=‘utf-8’) as f:
f.truncate(0)
print(f.write(str(lovepics)))
with open(filepath + “/loveurls”, ‘w’, encoding=‘utf-8’) as f:
f.truncate(0)
print(f.write(str(loveurls)))
with open(filepath + “/lovelrc”, ‘w’, encoding=‘utf-8’) as f:
f.truncate(0)
print(f.write(str(lovelrc)))
with open(filepath + “/voice”, ‘w’, encoding=‘utf-8’) as f:
f.truncate(0)
print(f.write(str(voice)))
try:
rmtree(str(data))
except Exception as e:
print(‘删除错误类型是’, e.class.name)
print(‘删除错误明细是’, e)
exit()
else:
pass
**喜爱的歌初始化读取:**
重新运行音乐播放器时,我们需要加载保存在本地的喜爱歌曲数据,并将歌曲列表信息加载显示到喜爱的歌子列表页面中。核心代码如下:
def run(self):
try:
apdataas = getenv(“APPDATA”)
filepathas = ‘{}/musicdata’.format(apdataas)
global lovelrc
global loveurls
global loves
global lovepics
global voice
# 读取历史数据开始
try:
with open(filepathas + “/voice”, ‘r’, encoding=‘utf-8’) as f:
a = f.read()
# print(a)
voice = float(a)
print(voice)
self.trigger.emit(str(‘voicedone’))
except:
self.trigger.emit(str(‘voicedone’))
pass
with open(filepathas + “/loves”, ‘r’, encoding=‘utf-8’) as f:
a = f.read()
print(a)
strer = a
loves = literal_eval(strer)
with open(filepathas + “/lovepics”, ‘r’, encoding=‘utf-8’) as f:
a = f.read()
print(a)
strer = a
lovepics = literal_eval(strer)
with open(filepathas + “/loveurls”, ‘r’, encoding=‘utf-8’) as f:
a = f.read()
print(a)
strer = a
loveurls = literal_eval(strer)
with open(filepathas + “/lovelrc”, ‘r’, encoding=‘utf-8’) as f:
a = f.read()
print(a)
strer = a
lovelrc = literal_eval(strer)
self.trigger.emit(str(‘login’))
print(loves)
print(‘read finish’)
except:
print(‘read error’)
pass
# 读取数据结束
# 下载喜爱的歌列表中首项的歌曲封面
try:
req = get(lovepics[0])
checkfile = open(str(data + '/ls3.png'), 'w+b')
for i in req.iter_content(100000):
checkfile.write(i)
checkfile.close()
lsfile = str(data + '/ls3.png')
safile = str(data + '/first.png')
draw(lsfile, safile)
self.trigger.emit(str('first'))
except:
self.trigger.emit(str('nofirst'))
pass
**列表播放:**
对于加载的喜爱歌曲列表,我们可以对歌曲进行列表一键播放。
音乐播放
def bofang(self, num, bo):
print(‘尝试进行播放’)
try:
import urllib
global pause
global songs
global music
global downloading
downloading = True
self.console_button_3.setIcon(icon(‘fa.pause’, color=‘#F76677’, font=18))
pause = False
try:
mixer.stop()
except:
pass
mixer.init()
try:
self.Timer = QTimer()
self.Timer.start(500)
except:
pass
try:
self.label.setText(‘正在寻找文件…’)
self.work = WorkThread()
self.work.start()
self.work.trigger.connect(self.display)
except:
print(‘无法播放,歌曲下载错误’)
downloading = False
pass
except:
sleep(0.1)
print(‘播放系统错误’)
pass
播放所有歌曲
def playall(self, typer):
global num
global bo
try:
bo = typer
num = 0
self.bofang(bo, num)
except:
print(‘playall error’)
pass
播放喜爱歌曲
def allplaylove(self):
self.playall(‘love’)
##### 4. 歌词显示
对于播放的歌曲,我们可以进行歌词打印显示。核心代码如下:
def run(self):
if bo == ‘love’:
try:
proxies = {
‘http’: ‘http://124.72.109.183:8118’,
‘http’: ‘http://49.85.1.79:31666’
}
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
'X-Requested-With': 'XMLHttpRequest'}
try:
try:
try:
aq = lovepics[num]
aqq = aq.split('/')
except:
pass
if type == 'kugou' and len(aqq) - 1 == 6:
aqqe = str(aqq[0]) + str('//') + str(aqq[2]) + str('/') + str(aqq[3]) + str('/') + str(
'400') + str('/') + str(aqq[5]) + str('/') + str(aqq[6])
print(aqqe)
elif type == 'netease' and len(aqq) - 1 == 4:
aqn = aq.split('?')
b = '?param=500x500'
aqqe = (str(aqn[0]) + str(b))
print(aqqe)
else:
aqqe = lovepics[num]
req = get(aqqe)
checkfile = open(str(data + '/ls1.png'), 'w+b')
for i in req.iter_content(100000):
checkfile.write(i)
checkfile.close()
lsfile = str(data + '/ls1.png')
safile = str(data + '/back.png')
draw(lsfile, safile)
picno = True
except:
print('图片错误')
picno = False
pass
url1 = loveurls[num]
print(url1)
# os.makedirs('music', exist\_ok=True)
number = number + 1
path = str(data + '\{}.临时文件'.format(number))
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.110.430.128 Safari/537.36',
'X-Requested-With': 'XMLHttpRequest'
}
with get(url1, stream=True, headers=headers) as r, open(path, 'wb') as file:
total_size = int(r.headers['content-length'])
content_size = 0
for content in r.iter_content(chunk_size=1024):
if not stopdown:
file.write(content)
content_size += len(content)
plan = (content_size / total_size) \* 100
# print(int(plan))
develop = str(int(plan)) + str('%')
self.trigger.emit(str(develop))
else:
print ('down')
break
stopdown = False
to = 'downloadmusic\{}.mp3'.format(songed[num])
makedirs('downloadmusic', exist_ok=True)
except:
self.trigger.emit(str('nofinish'))
pass
try:
lrct = []
f = lovelrc[num] # 按行读取
# print(f)
lines = f.split('\n')
# print(lines)
for i in lines:
line1 = i.split('[')
try:
line2 = line1[1].split(']')
if line2 == '':
pass
else:
linew = line2[1]
# print(linew)
lrct.append(linew)
self.trigger.emit(str('lrcfinish'))
except:
print('歌词错误')
except:
pass
try:
copyfile(path, to)
except:
pass
downloading = False
self.trigger.emit(str('finish'))
except:
self.trigger.emit(str('nofinish'))
效果如下所示:
![在这里插入图片描述](https://img-blog.csdnimg.cn/b79c6688e9ac44cb85649c16795367f0.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBARHJhZ29u5bCR5bm0,size_20,color_FFFFFF,t_70,g_se,x_16)
##### 5. 本地歌曲读取播放
首先我们可以对本地文件夹目录下的音乐进行读取添加到本地歌曲列表中,根据歌曲的文件名进行列表显示。核心代码如下:
本地歌曲文件夹读取添加
def add(self):
try:
global SongPath
global SongName
global num
global filew
global asas
fileN = QFileDialog.getExistingDirectory(None, “选取文件夹”, “”)
if not fileN == ‘’:
self.listwidget5.clear()
filew = fileN + ‘/’
asas = filew
l1 = [name for name in listdir(fileN) if name.endswith(‘.mp3’) or name.endswith(‘.flac’) or name.endswith(‘.wma’) or name.endswith(‘.MP3’) or name.endswith(‘.FLAC’) or name.endswith(‘.WMA’)]
SongNameadd = l1
SongPathadd = [filew + i for i in SongNameadd]
SongName = SongName + SongNameadd
SongPath = SongPath + SongPathadd
print(SongPath)
r = 0
for i in SongName:
self.listwidget5.addItem(i) # 将文件名添加到listWidget
self.listwidget5.item®.setForeground(Qt.white)
r = r + 1
except:
filew = asas
当然我们还可以对本地加载歌曲进行双击播放,首先我们需要将本地歌曲子列表页面中进行双击事件绑定。
self.tab5 = QWidget()
self.tab5.setObjectName(“tab5”)
self.tab5_layout = QGridLayout()
self.tab5.setLayout(self.tab5_layout)
self.listwidget5 = QListWidget(self.tab5)
self.listwidget5.doubleClicked.connect(lambda: self.change(self.listwidget5))
self.listwidget5.setContextMenuPolicy(Qt.CustomContextMenu)
self.listwidget5.customContextMenuRequested[QPoint].connect(self.myListWidgetContext5)
对子列表页面进行绑定之后,接下来我们就可以完成双击事件,获取歌曲名称,并进行本地播放。
加载当前播放的本地歌曲
def change(self, listwidget):
global num
global bo
# print (item.flags())
bo = ‘local’
num = int(listwidget.currentRow())
print(num)
# self.label.setText(wenjianming)#设置标签的文本为音乐的名字
f = str(SongName[num]).split(‘.mp3’)
f = str(f[0]).split(‘.flac’)
f = str(f[0]).split(‘.MP3’)
f = str(f[0]).split(‘.FLAC’)
f = str(f[0]).split(‘.wma’)
f = str(f[0]).split(‘.WMA’)
self.label.setText(f[0])
print(listwidget.currentRow())
self.bofanglocal()
本地音乐播放
def bofanglocal(self):
try:
global pause
try:
self.photo(‘local’)
except:
pass
self.console_button_3.setIcon(icon(‘fa.pause’, color=‘#F76677’, font=18))
pause = False
fill = SongPath[num]
print(fill)
try:
global timenum
mp3 = str(SongPath[num])
xx = load(mp3)
timenum = xx.info.time_secs
global start
start = True
except:
print(‘进度条错误,播放失败’)
try:
mixer.stop()
except:
pass
如果你也是看准了Python,想自学Python,在这里为大家准备了丰厚的免费学习大礼包,带大家一起学习,给大家剖析Python兼职、就业行情前景的这些事儿。
一、Python所有方向的学习路线
Python所有方向路线就是把Python常用的技术点做整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。
二、学习软件
工欲善其必先利其器。学习Python常用的开发软件都在这里了,给大家节省了很多时间。
三、全套PDF电子书
书籍的好处就在于权威和体系健全,刚开始学习的时候你可以只看视频或者听某个人讲课,但等你学完之后,你觉得你掌握了,这时候建议还是得去看一下书籍,看权威技术书籍也是每个程序员必经之路。
四、入门学习视频
我们在看视频学习的时候,不能光动眼动脑不动手,比较科学的学习方法是在理解之后运用它们,这时候练手项目就很适合了。
四、实战案例
光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。
五、面试资料
我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。
成为一个Python程序员专家或许需要花费数年时间,但是打下坚实的基础只要几周就可以,如果你按照我提供的学习路线以及资料有意识地去实践,你就有很大可能成功!
最后祝你好运!!!
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!