Use Python to download the lyrics and embed the implementation code in the song file,

Source: Internet
Author: User

Use Python to download the lyrics and embed the implementation code in the song file,

Use python to scan local music and download lyrics
This is really a dry product. I got it for half a night last night. Well, I started writing it from, and it was just 12 minutes later, sorry ....
To put it simply, Baidu provides an api for music search.

Http://box.zhangmen.baidu.com/x? Op = 12 & count = 1 & title = friend loss $ Chan Xun $

, Baidu will return you a piece of xml, as shown below

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>

In a simple description, we only need to obtain the lrc address of the song, so only the 2829 tag is useful.
However, the combination of encode and decode is mp3. In this example

http://zhangmenshiting.baidu.com/data2/music/12762845/YmRqamdua21fn6NndK6ap5WXcJlrmG1xlJhobWibmGpjk5ZtmWiZcWRjZ5lqbGyelGKWlZtubGljZ5lka2uanWSXY1qin5t1YWBmZW5ocGlhaWdnbGtqbzE$12762845.mp3?xcode=e6b69cf593ea22ac9d2b9314e565fc0caf85125f065ce3e0&mid=0.31929107437537

That is, but the sound quality is too poor. I have time to study this.
Continue with the lyrics. Pay attention to the 2829 in the lrcid label.
Http://box.zhangmen.baidu.com/bdlrc/ this is Baidu lrc lyrics storage address,
The lyrics in this example are then http://box.zhangmen.baidu.com/bdlrc/28/2829.lrc
You can see that the calculation method of the two numbers after the lyrics address is the integer obtained after dividing lrcid by 100, that is, the first number, the second number is lrcid, and then the suffix is added. lrc is done.
It is easy to get the lrc address. You only need to request the address and write the obtained content to the file.
Okay, this is probably the case. below is the code

import osimport os.pathimport reimport eyed3import urllib2import urllibfrom urllib import urlencodeimport sys import osreload(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!"

The first step is to get the request in xml format, so I was thinking about parsing xml to get the lrcid. But in the implementation process, I encountered various problems, and other problems are easy, this is the longest waste of time. After the tangle fails, you can only use a regular expression to obtain it...

Use python to embed lyrics into songs
Google Play Music was used as a Music player for mobile phones all the time, but now Google is so powerful by the wall, it is very troublesome to synchronize the music uploaded from PC to Google Play on the mobile phone. I simply gave up buying the famous Poweramp player, when I started using it, I was immediately attracted by the powerful features of Poweramp. It is the king of the android music player! Beautiful screen lock interface, powerful balancer functions and so on. The only weakness is the lyrics. If you want to display the lyrics, you must install a third-party software or embed the lyrics into the music. So I started my research after work yesterday. Fortunately, I finally got it done.

We can see that the effect is still very good.
Okay, you don't need to talk much about it. The program below
First, you must install the eyed3 module. Also, all my lyrics are in the path E: \ lrc.

import threadingimport timeimport datetimeimport reimport osimport eyed3import sysreload(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 mylrcstrdef 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_pathdef 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=[]     

Well, this is probably the case. If you have any questions, please submit them directly. I will reply as soon as possible.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.