做了一半。现在支持音乐的标签读取。包括ID3v1和ID3v2。本来打算继续写移动到手机或者mp3的。连上我的Windows Phone之后找不到WindowsPhone所在的盘符了=。=
- # -*- coding:utf-8 -*-
- import os
- import binascii
-
- class MusicManager(object):
- """Python音乐管理类"""
- ManagePath = os.getcwd() #音乐源文件目录
- _MusicEndNameList = ['.mp3']
-
- def seekMusic(self):
- """以列表形式返回指定目录的音乐文件"""
- return [filename for filename in os.listdir(self.ManagePath) if self.endsWith(filename, self._MusicEndNameList)]
-
- def checkID3(self, filename):
- """判断是否为音乐文件并判断是ID3v1还是ID3v2类型的音乐文件"""
- musicOpen = open(self.ManagePath + filename, 'r')
- try:
- if musicOpen.read(3) == 'ID3':
- musicOpen.seek(-128, 2)
- if musicOpen.read(3) == 'TAG':
- musicOpen.close()
- return 'ID3v1'
- else:
- musicOpen.seek(0, 0)
- if int(ord(musicOpen.read(4)[-1])) == 3:
- musicOpen.close()
- return 'ID3v2'
- else:
- error
- except:
- musicOpen.close()
- return 'illegal'
-
- def endsWith(self, filename, endings):
- """判断是否为音乐文件,返回布朗值"""
- endofile = '.' + filename.split('.')[-1]
- return endofile in endings
-
- def getID3(self, filename):
- """获取音乐信息的总调用"""
- if self.checkID3(i) == 'ID3v1':
- return self.getID3_1(filename)
- elif self.checkID3(i) == 'ID3v2':
- return self.getID3_2(filename)
-
- def getID3_1(self, filename):
- """获取ID3v1音乐的信息,返回字典"""
- musicOpen = open(self.ManagePath + filename, 'r')
- musicOpen.seek(-128, 2)
- musicOpen.read(3)
- return {'title':musicOpen.read(30), 'artist':musicOpen.read(30), 'album':musicOpen.read(30), 'file':self.ManagePath + filename}
-
- def getID3_2(self, filename):
- """获取ID3v2音乐的信息,返回字典"""
- isend = False
- musicOpen = open(self.ManagePath + filename, 'r')
- musicOpen.seek(10, 1)
- mark = musicOpen.read(4)
-
- #这里的算法我写的太蛋疼了,求高手封装成函数
- while isend == False:
- if mark == ' ':
- isend = True
- break
- if mark == 'TIT2':
- strlen = int(binascii.b2a_hex(musicOpen.read(4)), 16)
- musicOpen.read(2) #Flag
- title = musicOpen.read(strlen)
- mark = musicOpen.read(4)
- elif mark == 'TPE1':
- strlen = int(binascii.b2a_hex(musicOpen.read(4)), 16)
- musicOpen.read(2) #Flag
- artist = musicOpen.read(strlen)
- mark = musicOpen.read(4)
- elif mark == 'TALB':
- strlen = int(binascii.b2a_hex(musicOpen.read(4)), 16)
- musicOpen.read(2) #Flag
- album = musicOpen.read(strlen)
- mark = musicOpen.read(4)
- else:
- strlen = int(binascii.b2a_hex(musicOpen.read(4)), 16)
- if not strlen == 0:
- musicOpen.read(strlen + 2)
- mark = musicOpen.read(4)
- else:
- break
-
- return {'title':title, 'artist':artist, 'album':album, 'file':self.ManagePath + filename}
-
- def showMusicInfo(self, musicInfoDic):
- """因为字典排列顺序错乱,以一定格式打印字典"""
- print 'Path :', musicInfoDic['file']
- print 'Album :', musicInfoDic['album']
- print 'Article :', musicInfoDic['artist']
- print 'Title :', musicInfoDic['title'] , '\n'
-
-
- #DEMO
- Music = MusicManager()
- Music.ManagePath = os.getcwd() + '\\' #当前目录,如果有\要双写。比如D:\\Music\\。最后两个“\\”一定要加上
- MusicList = Music.seekMusic()
- for i in MusicList:
- Music.showMusicInfo(Music.getID3(i))
复制代码
|