使用Python下载歌词并嵌入歌曲文件中的实现代码
使用python扫描本地音乐并下载歌词
这次这个真的是干货哦,昨晚弄了半晚上,,,,从8点吃完饭就开始写,一直到了快12点才弄好,,,新手,伤不起呀。。。。
先简单的说下吧,百度提供了一个音乐搜索的api,你想百度请求类似于
http://box.zhangmen.baidu.com/x?op=12&count=1&title=最佳损友$$陈奕迅$$$$
的地址,百度会给你返回一段xml,如下所示
This XML file does not appear to have any style information associated with it. The document tree is shown below. <result> <count>1</count> <url> <encode> <![CDATA[ http://zhangmenshiting.baidu.com/data2/music/12762845/YmRqamdua21fn6NndK6ap5WXcJlrmG1xlJhobWibmGpjk5ZtmWiZcWRjZ5lqbGyelGKWlZtubGljZ5lka2uanWSXY1qin5t1YWBmZW5ocGlhaWdnbGtqbzE$ ]]> </encode> <decode> <![CDATA[ 12762845.mp3?xcode=e6b69cf593ea22ac9d2b9314e565fc0caf85125f065ce3e0&mid=0.31929107437537 ]]> </decode> <type>8</type> <lrcid>2829</lrcid> <flag>1</flag> </url> <durl> <encode> <![CDATA[ http://zhangmenshiting2.baidu.com/data2/music/7345405/aGVnaWlmbGaeomZzrZmmnJZvmGqXbHCbl2dsZ5qXaWqSlWpsmmdrb2mXamxpbXCclGNsmW2ba25mYmxtapmZcWqTWaGemnRoX2VkbWdvaGhoZmZramluOA$$ ]]> </encode> <decode> <![CDATA[ 7345405.mp3?xcode=e6b69cf593ea22ac78e1478e78479dc19e8e4650995cb99a&mid=0.31929107437537 ]]> </decode> <type>8</type> <lrcid>2829</lrcid> <flag>1</flag> </durl> <p2p> <hash>f98b6772aa97966550ec80617879becee0233bf4</hash> <url> <![CDATA[ ]]> </url> <type>mp3</type> <size>3778335</size> <bitrate>128</bitrate> </p2p> </result>
简单的说明下,由于我们要做的只是获取到歌曲的lrc歌词地址,所以有用的只有2829这个标签。
而encode和decode里面的拼接起来就是mp3的下载地址,如本例的
http://zhangmenshiting.baidu.com/data2/music/12762845/YmRqamdua21fn6NndK6ap5WXcJlrmG1xlJhobWibmGpjk5ZtmWiZcWRjZ5lqbGyelGKWlZtubGljZ5lka2uanWSXY1qin5t1YWBmZW5ocGlhaWdnbGtqbzE$12762845.mp3?xcode=e6b69cf593ea22ac9d2b9314e565fc0caf85125f065ce3e0&mid=0.31929107437537
就是下载地址,不过音质太差,有时间在研究下这个。
继续说歌词,注意lrcid标签里面的2829
http://box.zhangmen.baidu.com/bdlrc/ 这个是百度lrc歌词存放地址,
然后本例的歌词地址是http://box.zhangmen.baidu.com/bdlrc/28/2829.lrc
看到了吧,歌词地址后面的两个数字的计算方法是在lrcid除以100所获得的整数,就是第一个数字,然后第二个数字就是lrcid,然后后面加上后缀.lrc就搞定了
获得lrc地址之后就简单了,只要请求该地址,然后将获取到的内容写入文件就ok了。
好了,大概就是这样,下面是代码
import os import os.path import re import eyed3 import urllib2 import urllib from urllib import urlencode import sys import os reload(sys) sys.setdefaultencoding('utf8') music_path = r"E:\music" lrc_path = r"e:\lrc" os.remove('nolrc.txt') os.remove('lrcxml.txt') the_file = open('lrcxml.txt','a') nolrc_file = open('nolrc.txt','a') for root,dirs,files in os.walk(music_path): for filepath in files: the_path = os.path.join(root,filepath) if (the_path.find("mp3") != -1): print the_path the_music = eyed3.load(the_path) the_teg = the_music.tag._getAlbum() the_artist = the_music.tag._getArtist() the_title = the_music.tag._getTitle() # print the_teg # print the_title # print the_artist b = the_title.replace(' ','+') # print b a = the_artist.replace(' ','+') #print urlencode(str(b)) if isinstance(a,unicode): a = a.encode('utf8') song_url = "http://box.zhangmen.baidu.com/x?op=12&count=1&title="+b+"$$"+a+"$$$$ " the_file.write(song_url+'\n') page = urllib2.urlopen(song_url).read() print page theid = 0 lrcid = re.compile('<lrcid>(.*?)</lrcid>',re.S).findall(page) have_lrc = True if lrcid != []: theid = lrcid[0] else: nolrc_file.write(the_title+'\n') have_lrc = False print theid if have_lrc: firstid = int(theid)/100 lrcurl = "http://box.zhangmen.baidu.com/bdlrc/"+str(firstid)+"/"+theid+".lrc" print lrcurl lrc = urllib2.urlopen(lrcurl).read() if(lrc.find('html')== -1): lrcfile = open(lrc_path+"\\"+the_title+".lrc",'w') lrcfile.writelines(lrc) lrcfile.close() else: nolrc_file.write(the_title+'\n') the_file.close() nolrc_file.close() print "end!"
有用第一步请求所获取到底是xml格式的,所以本来想着解析xml来获取lrcid,但是在实现过程中遇到了各种问题,别的还容易,就在这一块儿浪费的时间最长,纠结未果之后,只能改用正则表达式来获取了。。。
使用python将歌词嵌入歌曲中
以前一直用的是Google Play Music来作为手机的音乐播放器,可是现在谷歌被墙的这么厉害的,从PC上传到Google Play的音乐在手机上面同步下来的话特麻烦,索性放弃之买了大名鼎鼎的Poweramp播放器,开始使用之后瞬间就被Poweramp强大的功能所吸引住了,不愧是安卓端的音乐播放器的王者!唯美的锁屏界面,强大的均衡器功能等等。唯一美中不足的就是歌词.如果要显示歌词的话必须安装第三方软件,或者是把歌词嵌入到音乐中。所以昨天下班之后就开始研究,所幸最后终于搞定了,先上下效果图
可以看到,效果还是很不错的呢。
好了,废话不多说,下面上程序
首先,必须安装eyed3模块,还有,我所有的歌词都在E:\lrc这个路径中的
import threading import time import datetime import re import os import eyed3 import sys reload(sys) sys.setdefaultencoding('utf8') def getstr(i): if i <10: return "0"+str(i) else: return str(i) musicpath=r'I:\music' lrcpath=r'E:\lrc' def deallrc(str): mystr=re.sub(r'\[\d\d:\d\d.\d\d\]','',str) mystr.replace('\n','') return mystr def checklrcfile(path,timespan): file=open(path,'r') mylrcstr='' #print timespan for line in file.readlines(100): #errorlog(line) if line.find(timespan)>0: return deallrc(line) else: continue return '' def getlrcstr(lrc): mylrcstr='' #print lrc for i in range(00,05): for j in range(00,59): for k in range(00,99): timespan=getstr(i)+":"+getstr(j)+"."+getstr(k) mylrcstr+=checklrcfile(lrc, timespan) #print timespan return mylrcstr def getlrc(musicname): musicname=u''.join(musicname) musicname=musicname.encode('gb2312') for root,dirs,files in os.walk(lrcpath): for filepath in files: the_path = os.path.join(root,filepath) if (the_path.find(musicname) != -1): print the_path return the_path def errorlog(path): file=open(r'e:\nolrc.txt','a') if path is None: path='' path=path+'\n' file.write(path) file.close() def writetag(themusic,lrcstr): music=eyed3.load(themusic) lrcstr=lrcstr.decode('utf8') lrcstr=u''.join(lrcstr) #lrcstr=unicode(lrcstr) music.tag.lyrics.set(lrcstr) music.tag.save() def dealmusic(path): print path the_music = eyed3.load(path) the_teg = the_music.tag._getAlbum() the_artist = the_music.tag._getArtist() the_title = the_music.tag._getTitle() #print the_title try: lrc=getlrc(the_title) lrcstr=getlrcstr(lrc) writetag(path, lrcstr) except: errorlog(path) class writelrc(threading.Thread): def __init__(self,the_path): threading.Thread.__init__(self) self.thepath=the_path def run(self): dealmusic(self.thepath) if __name__=='__main__': count=0 threads=[] for root,dirs,files in os.walk(musicpath): for filepath in files: the_path = os.path.join(root,filepath) if (the_path.find("mp3") != -1): count+=1 threads.append(writelrc(the_path)) if count%10==0: for t in threads: t.start() for t in threads: t.join() threads=[]
好了,大概就是这样,大家有什么问题可以直接提出来,我会尽快回复的。

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











PHP와 Python은 고유 한 장점과 단점이 있으며 선택은 프로젝트 요구와 개인 선호도에 달려 있습니다. 1.PHP는 대규모 웹 애플리케이션의 빠른 개발 및 유지 보수에 적합합니다. 2. Python은 데이터 과학 및 기계 학습 분야를 지배합니다.

CentOS 시스템에서 Pytorch GPU 가속도를 활성화하려면 Cuda, Cudnn 및 GPU 버전의 Pytorch를 설치해야합니다. 다음 단계는 프로세스를 안내합니다. CUDA 및 CUDNN 설치 CUDA 버전 호환성 결정 : NVIDIA-SMI 명령을 사용하여 NVIDIA 그래픽 카드에서 지원하는 CUDA 버전을보십시오. 예를 들어, MX450 그래픽 카드는 CUDA11.1 이상을 지원할 수 있습니다. Cudatoolkit 다운로드 및 설치 : NVIDIACUDATOOLKIT의 공식 웹 사이트를 방문하여 그래픽 카드에서 지원하는 가장 높은 CUDA 버전에 따라 해당 버전을 다운로드하여 설치하십시오. CUDNN 라이브러리 설치 :

Python과 JavaScript는 커뮤니티, 라이브러리 및 리소스 측면에서 고유 한 장점과 단점이 있습니다. 1) Python 커뮤니티는 친절하고 초보자에게 적합하지만 프론트 엔드 개발 리소스는 JavaScript만큼 풍부하지 않습니다. 2) Python은 데이터 과학 및 기계 학습 라이브러리에서 강력하며 JavaScript는 프론트 엔드 개발 라이브러리 및 프레임 워크에서 더 좋습니다. 3) 둘 다 풍부한 학습 리소스를 가지고 있지만 Python은 공식 문서로 시작하는 데 적합하지만 JavaScript는 MDNWebDocs에서 더 좋습니다. 선택은 프로젝트 요구와 개인적인 이익을 기반으로해야합니다.

Docker는 Linux 커널 기능을 사용하여 효율적이고 고립 된 응용 프로그램 실행 환경을 제공합니다. 작동 원리는 다음과 같습니다. 1. 거울은 읽기 전용 템플릿으로 사용되며, 여기에는 응용 프로그램을 실행하는 데 필요한 모든 것을 포함합니다. 2. Union 파일 시스템 (Unionfs)은 여러 파일 시스템을 스택하고 차이점 만 저장하고 공간을 절약하고 속도를 높입니다. 3. 데몬은 거울과 컨테이너를 관리하고 클라이언트는 상호 작용을 위해 사용합니다. 4. 네임 스페이스 및 CGroup은 컨테이너 격리 및 자원 제한을 구현합니다. 5. 다중 네트워크 모드는 컨테이너 상호 연결을 지원합니다. 이러한 핵심 개념을 이해 함으로써만 Docker를 더 잘 활용할 수 있습니다.

Minio Object Storage : Centos System Minio 하의 고성능 배포는 Go Language를 기반으로 개발 한 고성능 분산 객체 저장 시스템입니다. Amazons3과 호환됩니다. Java, Python, JavaScript 및 Go를 포함한 다양한 클라이언트 언어를 지원합니다. 이 기사는 CentOS 시스템에 대한 Minio의 설치 및 호환성을 간단히 소개합니다. CentOS 버전 호환성 Minio는 다음을 포함하되 이에 국한되지 않는 여러 CentOS 버전에서 확인되었습니다. CentOS7.9 : 클러스터 구성, 환경 준비, 구성 파일 설정, 디스크 파티셔닝 및 미니를 다루는 완전한 설치 안내서를 제공합니다.

CentOS 시스템에 대한 Pytorch 분산 교육에는 다음 단계가 필요합니다. Pytorch 설치 : 전제는 Python과 PIP가 CentOS 시스템에 설치된다는 것입니다. CUDA 버전에 따라 Pytorch 공식 웹 사이트에서 적절한 설치 명령을 받으십시오. CPU 전용 교육의 경우 다음 명령을 사용할 수 있습니다. PipinStalltorchtorchvisiontorchaudio GPU 지원이 필요한 경우 CUDA 및 CUDNN의 해당 버전이 설치되어 있는지 확인하고 해당 PyTorch 버전을 설치하려면 설치하십시오. 분산 환경 구성 : 분산 교육에는 일반적으로 여러 기계 또는 단일 기계 다중 GPU가 필요합니다. 장소

CentOS 시스템에 Pytorch를 설치할 때는 적절한 버전을 신중하게 선택하고 다음 주요 요소를 고려해야합니다. 1. 시스템 환경 호환성 : 운영 체제 : CentOS7 이상을 사용하는 것이 좋습니다. Cuda 및 Cudnn : Pytorch 버전 및 Cuda 버전은 밀접하게 관련되어 있습니다. 예를 들어, pytorch1.9.0은 cuda11.1을 필요로하고 Pytorch2.0.1은 cuda11.3을 필요로합니다. CUDNN 버전도 CUDA 버전과 일치해야합니다. Pytorch 버전을 선택하기 전에 호환 CUDA 및 CUDNN 버전이 설치되었는지 확인하십시오. 파이썬 버전 : Pytorch 공식 지점

Centos의 최신 버전으로 Pytorch를 업데이트하면 다음 단계를 수행 할 수 있습니다. 방법 1 : PIP를 사용하여 PIP 업데이트 : 먼저 PIP의 PIP 버전이 최신 버전의 PyTorch를 제대로 설치하지 못할 수 있기 때문에 PIP가 최신 버전인지 확인하십시오. PipinStall-UpgradePip Unin Incalls of Pytorch (설치된 경우) : PipuninStalltorchtorchvisiontorchaudio 설치 최신 정보
