Read and write ID3v1 information for MP3 files using python

Source: Internet
Author: User
Tags id3
1. Causes





has been crazy fan of "Winter Wu Theory of relativity", in order to tidy up the download of his MP3 spent a lot of effort, today suddenly found that the computer's MP3 imported into itunes, the file name is not recognized. #_ * itunes automatically recognizes the contents of the MP3 information. Many times, the filename is very good. The truth is, it makes me feel imperfect. Be sure to write the file name as well as MP3 information Central.



A search on the internet, a lot of Python code, are used eyeD3 this component package. Follow the example of a simple two to come out of a version, run the discovery latin_1 what the coding problem. OK put its tag and ID3 and frames package in the code of all changed to GBK can solve. But also found that if the file originally did not id3v1, get title directly error. I found two, and no one mentioned the question. It seems that I can do it by myself. Then there is no eyeD3 package at all. Because ID3v1 is really simple.



2. Analysis



Baidu has said that I want to write this information can be stored in the tail of the mp3 file.



ID3v1 is relatively simple, it is stored at the end of the MP3 file, with a 16-input editor open a MP3 file, view its end of the 128 sequential bytes, the data structure is defined as follows:



Char header[3]; /Tag header must be "tag" otherwise think no label/



Char title[30]; Title



Char artist[30]; Author



Char album[30]; Album



Char year[4]; /Vintage/



Char comment[30]; Notes



Char Genre; Type



ID3v1 information is stored in sequence, without any identity to separate it, such as the title information less than 30 bytes, then use ' "" to make up, or will cause information errors.



3. Resolve



Fortunately, the file structure is not complex, processing is relatively simple. The idea is very simple, read the tail of the MP3 file 128 bytes, to determine that there is a tag, there is the last 128 of our own information to replace, did not add 128 bytes up.



4. Code



The best document is the source code, of course I write the comments back. Do not rely on eyeD3 such a package, pure hand-written.


#encoding=utf8

__author__ ='pcode@qq.com'import os

importstructdefGetFiles(path):"""

    Read the file of the specified directory

    """FileDic=[]

    Files=os.listdir(path)for f in files:

        f=f[:-4]FileDic.append(f)returnFileDic,files

def_GetLast128K(path,file):

    Ff1=open(os.path.join(path,file),"rb")

    Ff1.seek(-128,2)

    Id3v1data=ff1.read()

    Ff1.close()return id3v1data

def_GetAllBinData(path,file):

    Ff1=open(os.path.join(path,file),"rb")

    Data=ff1.read()

    Ff1.close()return data

defSetTag(path,file,title,artist,album,year,comment,genre):"""

    Set some parameters of mp3 ID3 v1

    Char Header[3]; /* The tag header must be "TAG" or it is considered to have no tag */

    Char Title[30]; /*title*/

    Char Artist[30]; /*Author*/

    Char Album[30]; /* specials*/

    Char Year[4]; /*production age*/

    Char Comment[30]; /*Remarks*/

    Char Genre; /*type*/

    The 128 bytes of the mp3 file are id3v1 data. If there is data, the data is read and modified. If there is no data, it is added.

    """

    Header='TAG'# combines the data content of the last 128K id3V1

    Str =struct.pack('3s30s30s30s4s30ss',header,title,artist,album,year,comment,genre)#Get all the original data

    Data=_GetAllBinData(path,file)#Get the last 128 bytes of data

    Id3v1data=_GetLast128K(path,file)#Open the original file and prepare to write

    Ff=open(os.path.join(path,file),"wb")try:#Judge whether there is id3v1 data if id3v1data[0:3]!=header:# Countdown 128 bytes is not indicated by TAG #According to the structure of id3v1

            Ff.write(data+str)else:# There are cases to change

            Ff.write(data[0:-128]+str)

        Ff.close()print"OK"+title

    Except:

        Ff.write(data)print"Error "+title

    Finally:if ff :ff.close()if __name__=="__main__":#I store the mp3 file directory

    Path=u"K:\\reading\\Read\\Relativity"#Get the file name and full file name

    Names, files=GetFiles(path)# cool code for i in range(len(files)):#Note code decoding

        Title=names[i].encode('gbk')

        Artist=u'Author'.encode('gbk')

        Album=u'relativity '.encode('gbk')

        Year=''

        Comment=''

        Genre=''#call function handles SetTag(path,files[i],title,artist,album,year,comment,genre) 


5. Follow-up



After using the information of the ID3V1 is changed by the file name, the Settag function can also be migrated to other programs to change the ID3V1 information. But write the file there, regardless of whether the tag has to rewrite all the contents of the file. The efficiency is generally like. Speed does not eyeD3 this component fast. But at that time EyeD3 can not support Chinese, and the document was not ID3V1 information will be wrong, their own more relieved. Bingo.


  • 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.