2012-10-17 38 views
1

我想从mp3文件中读取mp3标签:D并将其保存到txt文件。但我的代码不起作用:(我的意思是我有一些问题,在我的mp3文件中设置适当的位置,看看:(为什么它不想工作?)。我必须自己做,没有额外的库。如何读取C(unix)中的mp3文件标签?

#include <stdio.h> 
#include <fcntl.h> 
#include <unistd.h> 
#include <stdlib.h> 
#include <sys/stat.h> 
#include <sys/types.h> 

int getFileSize(const char *filename) 
{ 
    struct stat st; 
    if (stat(filename, &st) == 0) 
     return st.st_size; 
    return -1; 
} 


int main(int argc, char **argv) 
{ 
    char *infile = "in.mp3", *outfile = "out.txt"; 
    int infd, bytes_read = 0, buffsize = 255; 
    char buffer[255]; 

       infd = open(infile, O_RDONLY); 
       if (infd == -1) 
        return -1; 

       int outfd = open(outfile, O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR); 
       if (outfd == -1) 
        return -1; 

        if(lseek(infd, -128, SEEK_END) < 0) 
         return -1; 

       for(;;) 
       { 
        bytes_read = read(infd, buffer, buffsize); 
        if (bytes_read > 0) 
        { 
         write(outfd, buffer, bytes_read); 

        } 
        else 
        { 
         if (bytes_read == 0) 
         { 
          if (close(infd) < 0) 
           return -1; 
          break; 
         } 
         else if (bytes_read == -1) 
         { 
          break; 
          return -1; 
         } 
        } 
       } 

    return 0; 
} 
+1

你永远不会关闭'outfd' – Musa

+0

我认为你只需要读取ID3v1的信息? ID3v2标签可以位于文件中的任何位置,而不仅仅是最后。 –

+0

您可能想要以字节序列搜索Id3标头信息,然后您可以开始解码格式。您是否看过Id3参考文件以了解该标准的详细规格? – count0

回答

1

一种方法来解决这个问题:

你需要通过文件根据ID3的版本你正在使用扫描(问题有由史蒂芬指出未指定特定版本)找到整个标签或标签标头并从那里解码

对于ID3v2标头序列是10字节和如下(从ID3v2的规格):

ID3v2/file identifier  "ID3" 
ID3v2 version    $04 00 
ID3v2 flags    %abcd0000 
ID3v2 size    4 * %0xxxxxxx 

我的建议是,看看ID3v2的here的规范。检查第3.1章,因为部分工作正在进行背景研究。对于ID3v1检查概述规格here。对这些信息进行解码相当简单,其功能与您对问题的评论中所述完全相同。看看你的代码,这可能是你想要做的事情(在文件末尾跳到128字节并开始从那里读取)。

确保您有一个正确标记的文件,并确保在使用您的解码器之前使用的标记版本。