python实现各大平台音乐搜索,下载,收听

先上效果图
各大平台的歌随便搜,随便听!

打包后软件地址:https://wws.lanzoui.com/iosS7rlgzmb 密码: 2gm4 (最好用这个)
下面是源码和测试版:
源码:链接: https://pan.baidu.com/s/1N98jNox7zipVBRcqqkh1Hw 提取码: z6pv
备用链接(github): https://github.com/hedy-bit/pyqt5-pygame-urllib-

大制作,1500多行代python码实现各大平台音乐爬取和,下载和收听,使用了pyqt5,pygame和beautifulsoup

之前没事干,看windows10自带的播放器有一(亿)点点不顺眼,然后再看见网易云之类的平台都要vip,所以想写一个播放器,正好有学了点pyqt5,然后就先整了个离线播音乐放器,耗时4天,后来又添加了爬虫模块,就做出来了这个音乐搜索器

分几个部分讲解代码

  • pyqt5界面
  • python爬虫
  • 下载
  • 功能模块
    爬虫线程,下载线程和进度条线程我都是新开了类的,因为在主线程进行爬虫会有一定的概率会触发关闭

界面

快不多说,先上代码
界面的话。。。我觉得挺好看的,由于代码太长我就不放出来了

pyhton爬虫

由于怕被各大平台起诉,所以都是通过第三方平台爬虫的
爬取搜索的歌曲,歌手和url,由于要使用多线程,所以新开了一个类

class PAThread(QThread):# 自定义信号对象。参数str就代表这个信号可以传一个字符串trigger = pyqtSignal(str)def __int__(self):# 初始化函数super(PAThread, self).__init__()def run(self):qmut.lock()try:global paingglobal stopglobal lrcsglobal urlsglobal songsglobal nameglobal songidglobal proxiesglobal picglobal tryedpaing = Trueprint('搜索软件{}'.format(type))print('开始搜索')name = nameheaders = {'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'}urls = []songs = []pic = []lrcs = []if int(page) == '' or int(page) < 1:pages = 2else:pages = int(page)print(pages)for a in range(1, pages + 1):if not stop:urlss = ['http://music.9q4.cn/', 'https://defcon.cn/dmusic/', 'http://www.xmsj.org/','http://music.laomao.me/']print(tryed)if tryed > 3:tryed = 0url = urlss[tryed]else:url = urlss[tryed]print(urlss[tryed])params = {'input': name,'filter': 'name','type': type,'page': a}if not stop:try:res = post(url, params, headers=headers, proxies=proxies)html = res.json()for i in range(0, 10):try:title = jsonpath(html, '$..title')[i]author = jsonpath(html, '$..author')[i]url1 = jsonpath(html, '$..url')[i]  # 取下载网址pick = jsonpath(html, '$..pic')[i]  # 取歌词lrc = jsonpath(html, '$..lrc')[i]print(title, author)lrcs.append(lrc)urls.append(url1)pic.append(pick)songs.append(str(title) + ' - ' + str(author))# self.textEdit.setText(lrc)  # 打印歌词# print(lrc)except:passexcept:stop = Falsepaing = Falseprint(urls)print(songs)self.trigger.emit(str('finish'))else:print('stop')self.trigger.emit(str('finish'))else:print('stop')self.trigger.emit(str('clear'))passstop = Falsepaing = Falseexcept:print('爬取歌曲出错')self.trigger.emit(str('unfinish'))stop = Falsepaing = Falseqmut.unlock()

然后就是从爬取的url下载歌曲

歌曲下载!

class WorkThread(QThread):# 自定义信号对象。参数str就代表这个信号可以传一个字符串trigger = pyqtSignal(str)def __int__(self):# 初始化函数super(WorkThread, self).__init__()def cbk(self, a, b, c):'''''回调函数@a:已经下载的数据块@b:数据块的大小@c:远程文件的大小'''per = 100.0 * a * b / cif per > 100:per = 100# print   ('%.2f%%' % per)self.trigger.emit(str('%.2f%%' % per))def run(self):global toglobal numberglobal pathglobal downloadingglobal picglobal lrctglobal lrcdif bo == 'boing':try:proxies = {'http': 'http://124.72.109.183:8118',' Shttp': '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 = pic[num]aqq = aq.split('/')except:passif 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 = pic[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)except:passurl1 = urls[num]print(url1)number = number + 1path = 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 = 0for content in r.iter_content(chunk_size=1024):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))to = 'downloadmusic\{}.mp3'.format(songs[num])makedirs('downloadmusic', exist_ok=True)except:passtry:if bo == 'boing':lrct = []f = lrcs[num]  # 按行读取# print (f)lines = f.split('\n')# print (lines)if not lines == ['']:for i in lines:if not i == '':line1 = i.split('[')try:line2 = line1[1].split(']')if line2 == '':passelse:linew = line2[1]# print(linew)lrct.append(linew)self.trigger.emit(str('lrcfinish'))except:print('{}的歌词错误'.format(str(line1)))else:passelse:self.trigger.emit(str('lrcnofinish'))print('没有歌词')except:print('歌词错误')try:copyfile(path, to)except:passdownloading = Falseself.trigger.emit(str('finish'))except:self.trigger.emit(str('nofinish'))

列表点击播放

下面就是QListwidge的点击和播放模块

    def bofang(self, num):print ('try bofang')try:import urllibglobal pauseglobal songsglobal musicglobal downloadingdownloading = Trueself.console_button_3.setIcon(qtawesome.icon('fa.pause', color='#F76677', font=18))pause = False# QMessageBox.information(self, "ListWidget", "你选择了: "+item.text())# 显示出消息提示框try:pygame.mixer.stop()except:passpygame.mixer.init()try:self.Timer = QTimer()self.Timer.start(500)except:passtry:self.label.setText('下载中')#调用开头的多线程下载歌曲self.work = WorkThread()self.work.start()self.work.trigger.connect(self.display)except:print ('song download error')downloading = Falsepassexcept:time.sleep(0.1)print ('system error')#self.next()pass#用于接收返回的信号def display(self,sd):if sd == 'finish':self.label.setText(songs[num])print ('music\{}.mp3'.format(number))pygame.mixer.music.load('music\{}.mp3'.format(number))  # 载入音乐pygame.mixer.music.play()# 播放音乐else:self.label.setText('下载错误')

功能函数

下面是双击播放和上一首还有下一首

   #QlistWidget的双击事件def change_func(self, listwidget):global numitem = QListWidgetItem(self.listwidget.currentItem())print(item.text())num = int(listwidget.currentRow())self.label.setText(songs[num])print(listwidget.currentRow())self.bofang(num)#下一首按钮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')pass

下面自动播放,有循环,随机和单曲循环,加上下一首,上一首,

   #随机播放def shui(self):global numglobal songsq = int(len(songs) - 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)#时间函数,与下面的进度条和时间显示有关self.label.setText(songs[num])self.bofang(num) # 播放音乐except:pass#下一首def next(self):print ('nexting')global numglobal songsif num == len(songs) - 1:print('冇')num = 0else:num = num + 1try:self.label.setText(songs[num])self.bofang(num)except:print ('next error')pass#单曲循环def always(self):try:self.bofang(num)self.label.setText(songs[num])except:pass#上一首def last(self):global numglobal songsif num == 0:print('冇')num = len(songs) - 1else:num = num - 1try:self.bofang(num)self.label.setText(songs[num])except:pass

下面是播放模式选择和循环判断是否要自动下一首
由于每秒钟判断一次,所以要使用多线程

   '''在init里面的循环判断打开方法t1 = threading.Thread(target=self.action)t1.setDaemon(True)t1.start()'''#选择播放模式def 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')pass#循环判断def action(self):a = 1global numwhile a < 2:# print ('checking')try:time.sleep(1)if not pygame.mixer.music.get_busy() and pause == False and not downloading: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()

还有就是进度条,线程

class barThread(QThread):# 自定义信号对象。参数str就代表这个信号可以传一个字符串trigger = pyqtSignal(str)def __int__(self):# 初始化函数super(barThread, self).__init__()def run(self):xun4 = 1# print ('begin')try:# print ('check')sleep(1)try:try:global timenumxun4 = 1while xun4 < 2:sleep(1)# print ('check')if not downloading or not paing:try:# print ('check pass')timenumm = timenum * 10000# print (timenumm)current = mixer.music.get_pos()  # 毫秒current %= timenummassq = current / timenumm * 10000# print(current)assq = int(assq * 10)# print(assq)if not assq > 10000:self.trigger.emit(str(assq))else:assq = 10000self.trigger.emit(str(assq))except:try:if mixer.music.get_busy():print('进度条错误')except:passexcept:passexcept:passexcept:pass

代码介绍在这里就结束了,如果有更好的修改方案请私信我

最后是全部代码,
https://github.com/hedy-bit/pyqt5-pygame-urllib-

大制作,1500多行python代码实现各大平台音乐搜索,下载,收听相关推荐

  1. 50行Python代码绘制数据大屏,这个可视化框架真的太神了

    今天小编来为大家安利另外一个用于绘制可视化图表的Python框架,名叫Dash,建立在Flask.Plotly.js以及React.js的基础之上,在创建之出的目的是为了帮助前端知识匮乏的数据分析人员 ...

  2. 50 行 Python 代码绘制数据大屏,这个可视化框架真的太神了

    作者 | 俊欣 来源 | 关于数据分析与可视化 今天小编来为大家安利另外一个用于绘制可视化图表的Python框架,名叫Dash,建立在Flask.Plotly.js以及React.js的基础之上,在创 ...

  3. 40行python代码搞定王者荣耀全部壁纸下载

    大家好,我是才哥. 今天我们一起来采集王者荣耀英雄的全部皮肤地址,目标网址: https://pvp.qq.com/web201605/herolist.shtml 通过开发者工具发现 https:/ ...

  4. 用11行Python代码,实现动态二维码制作

    用11行Python代码,实现动态二维码制作 效果展示 Python实现 素材 其他工具 效果展示 Python实现 要预装myqr模块才行. windows键+R 打开cmd,输入pip insta ...

  5. python电子相册制作代码大全_20 行 Python 代码即可制作精美证件照

    无论是我们上学时还之后的工作中,基本都需要用到电子证件照片,这类照片基本都对照片尺寸.背景色有要求,本文我们来看一下如何只用不到 20 行 Python 代码完成证件照片的制作. 简介 制作证件照我们 ...

  6. 不到 20 行 Python 代码即可制作精美证件照!不需要去图文店了!

    无论是我们上学时还之后的工作中,基本都需要用到电子证件照片,这类照片基本都对照片尺寸.背景色有要求,本文我们来看一下如何只用不到 20 行 Python 代码完成证件照片的制作. 简介 制作证件照我们 ...

  7. python做出来的小程序、可以在win10上面运行_超详细,手把手教你用20行Python代码制作飞花令小程序!...

    原标题:超详细,手把手教你用20行Python代码制作飞花令小程序! 来源:早起Python 作者:陈熹 飞花令是古时候人们经常玩一种"行酒令"的游戏,是中国古代酒令之一,属雅令. ...

  8. 曝肝三天,两千行Python代码,制作B站视频下载工具(附源码)

    曝肝三天,两千行Python代码,制作B站视频下载工具(附源码) 文章目录 一.准备工作 二.预览 1.启动 2.解析 3.下载中 4.下载完成 5.结果 三.设计流程 1.bilibili_vide ...

  9. python 制作字符视频_20行Python代码实现视频字符化功能

    我们经常在B站上看到一些字符鬼畜视频,主要就是将一个视频转换成字符的样子展现出来.看起来是非常高端,但是实际实现起来确是非常简单,我们只需要接触opencv模块,就能很快的实现视频字符化.但是在此之前 ...

最新文章

  1. SQLserver数据库操作帮助类SqlHelper
  2. 新年到,献给从一线工程师到CTO的实用指南:《2019区块链开发者报告》
  3. 北京年会和关于数据仓库板块的思考
  4. 从C语言过渡到C++并不容易啊,大家说呢?
  5. yapi 界面修改_当Swagger遇上YApi,瞬间高大上了!(一个好用的接口管理工具)...
  6. 周期置换加密算法用c语言实现,古典密码实验报告.doc
  7. 加盟商最大的顾虑是什么?
  8. Python 手把手实现远程控制桌面
  9. C++面试题-面向对象-静态成员变量以及静态成员函数
  10. cad转dwf简易教程
  11. Ubuntu 训练深度学习模型的时候突然重启问题
  12. 华为员工能拿多少钱,揭秘一个真实的华为
  13. 目前1KB文件夹快捷方式病毒扫清方法
  14. TomExam开源在线考试系统
  15. 黑白照片一键变成彩色照片,怎么做?快来看看!
  16. VGA显示器字符显示
  17. python Stark 组件
  18. 上海精神卫生中心怎么样 (徐汇区)
  19. 愤世嫉俗的程序员,总在某乎发表言论,当起了“键盘侠”
  20. element-ui table中span-method(行合并)方法使用

热门文章

  1. vue3 关于子组件给父组件传值,详解
  2. SpringBoot使用Freemarker导出word模板(OpenXML)
  3. leetcode|剑指offter|面试题6:从尾到头打印链表
  4. VS2010黑色主题Dark完美设置!
  5. 华为ENSP AP上线失败-MAC认证 巨坑系列
  6. python爬取游戏数据,Python 爬虫之好游快爆游戏排行信息爬取
  7. 八式八段锦,动图指导
  8. 0基础小学生做的网站
  9. ORB-SLAM2的源码阅读(六):KeyFrameDataBase类
  10. 论文成功写作技巧之行之有效的写作从“结果”开始(上)