从豆瓣自动获取mp3封面。 MP3与id3 名称互换,封面id3,[Python]代码#


[Python]代码

# -*- coding:utf-8 -*-'''脚本名称:MP3.py设计背景:苹果产品盛行,当下itunes如果用不正确的MP3名字或者id3信息就会在itunes出显乱码,        同步到苹果设备上就不能正常显示。itunes自带自动下载专辑封面的功能,但该功能鸡肋,没        有一次下载成功。脚本优势:可以正常获取 id3 ,用户可以根据自己的选择在 mp3的名称和 id3 之间相互批量转换,以        避免乱码出现的问题。可自动根据id3 的 artist、(album or title)自动匹配豆瓣上的        专辑封面自动获取专辑封面,输出到cover/album目录下。存在问题:引用了搜索函数search(),可以完美的支持英文MP3搜索,        1.中文搜索仍存在一些问题,就是可以正确的转换成unicode读出,但是输出的时候转换出问题,        目前正在想办法解决。        2.暂时还没能将封面自动导入到mp3文件中,待完善。'''import osimport reimport sysimport urllibfrom urllib import urlopenfrom mutagen.mp3 import MP3 import mutagen.id3 from mutagen.easyid3 import EasyID3default_encoding = 'gbk'if sys.getdefaultencoding() != default_encoding:    reload(sys)    sys.setdefaultencoding(default_encoding)def search(base,pattern):    fileresult = []    cur_list = os.listdir(base)    for item in cur_list:        full_path = os.path.join(base, item)        if os.path:            if full_path.endswith(pattern):                fileresult.append(full_path)    return fileresult    def Mp3toID3(base):    for result in search(base,'.mp3'):        filename_ext = os.path.basename(result)        filename,_= os.path.splitext(filename_ext)        print filename        id3info = MP3(result, ID3=EasyID3)        id3info['title'] = filename        id3info.save()        print id3infodef ID3toMp3(base):    for result in search(base,'.mp3'):        filename_ext = os.path.basename(result)        dirname = os.path.dirname(result)        filename,_= os.path.splitext(filename_ext)        id3info = MP3(result, ID3=EasyID3)        name = ''.join(id3info['title']) + '.mp3'        print name        full_path = dirname + os.sep + name        new_filename = os.rename(result,full_path)        print new_filenamedef getcover(base):    for result in search(base,'.mp3'):        filename_ext = os.path.basename(result)        filename,_= os.path.splitext(filename_ext)        id3info = MP3(result, ID3=EasyID3)        artist = ''.join(id3info['artist'])        album = ''.join (id3info['album'])        title = ''.join (id3info['title'])        if os.path.exists(base) == False:            os.makedirs(base)        else:            pass        img_name = title + '.jpg'        file_name = os.path.join(base,img_name)        keyword = urllib.quote(artist + ' ' + (album or title))        #keywords = unicode(keywords,'utf-8')        print keyword        searchurl='http://api.douban.com/music/subjects?q=' + keyword + '&max-results=2'        result  = urlopen(searchurl).read()        result_img = 'http://img3.douban.com/spic/s(\d+)'        match = re.search(result_img, result, re.IGNORECASE)        imgFileName = os.path.basename(match.group())        imgurl = 'http://img1.douban.com/lpic/' + imgFileName + '.jpg'        print imgurl        path = base + os.sep + 'cover' + os.sep + album        jpgName = title + '.jpg'        jpg_Path = os.path.join(path,jpgName)        if os.path.exists(path) == False:            os.makedirs(path)        else:            pass        try:            urllib.urlretrieve(imgurl , jpg_Path)        except:            print '\tError retrieving the URL:', jpg_PathKeyWord = {'m':Mp3toID3,'i':ID3toMp3,'g':getcover}def main(base):    words = """    What do u want?    (M)p3toID3    (I)D3toMp3    (G)etcover    (Q)uit    Entrt chice on Keywords:"""    while True:        while True:                try:                    choice = raw_input(words).strip()[0].lower()                except (EOFError,KeyboardInterrupt):                    choice = 'q'                print '\nYou picked:[%s]'%choice                if choice not in 'migq':                    print 'Enter Error, Try again'                else:                    break        if choice == 'q':            break        KeyWord[choice](base)if __name__ == '__main__':    base = u'D:\Kugou'    main(base)

评论关闭