MP3内嵌信息的读取可以不用从系统的contentprovider获取的一些信息。
在最后128个字节中包含这些信息。
这些信息如果用notepad++打开的话都可以看见在结尾处。
其中从文件任意处读取byte的方法非常好用不止可以使用在MP3文件中在任意的文件都可以使用,最近在研究MP3时看到的一个类。
package com.cheerchip.mp3test;
import android.support.annotation.Nullable;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
/**
*获得MP3文件的信息
*/
public class MP3Info {
@Nullable
public static MP3Info getmp3() {
File MP3FILE = new File("/sdcard/test.mp3");
Log.e( "getmp3: ",MP3FILE.exists()+"" );
try {
MP3Info info = new MP3Info(MP3FILE);
info.setCharset("GBK");//使用gbk编码不然乱码
Log.e("getmp3: ",info.getSongName());
Log.e("getmp3: ",info.getArtist());
Log.e("getmp3: ",info.getAlbum());
Log.e("getmp3: ",info.getYear());
Log.e("getmp3: ",info.getComment());
return info;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private String charset = "GB2312";
private byte[] buf;
/**
* 实例化一个获得MP3文件的信息的类
* @param mp3 MP3文件
* @throws IOException 读取MP3出错或则MP3文件不存在
*/
public MP3Info(File mp3) throws IOException{
buf = new byte[128];//初始化标签信息的byte数组
RandomAccessFile raf = new RandomAccessFile(mp3, "r");//随机读写方式打开MP3文件
raf.seek(raf.length() - 128);//移动到文件MP3末尾
raf.read(buf);//读取标签信息
raf.close();//关闭
Log.e( "MP3Info: ","000000" );
if(buf.length != 128){//数据是否合法
Log.e( "MP3Info: ","1111111" );
throw new IOException("MP3标签信息数据长度不合法!");
}
if(!"TAG".equalsIgnoreCase(new String(buf,0,3))){//信息格式是否正确
Log.e( "MP3Info: ","222222" );
throw new IOException("MP3标签信息数据格式不正确!");
}
}
/**
* 获得目前解析时用的字符编码
* @return 目前解析时用的字符编码
*/
public String getCharset() {
return charset;
}
/**
* 设置解析时用的字符编码
* @param charset 解析时用的字符编码
*/
public void setCharset(String charset) {
this.charset = charset;
}
public String getSongName(){
try {
Log.e("getSongName: ",new String(buf) );
return new String(buf,3,30,charset).trim();
} catch (UnsupportedEncodingException e) {
return new String(buf,3,30).trim();
}
}
public String getArtist(){
try {
return new String(buf,33,30,charset).trim();
} catch (UnsupportedEncodingException e) {
return new String(buf,33,30).trim();
}
}
public String getAlbum(){
try {
return new String(buf,63,30,charset).trim();
} catch (UnsupportedEncodingException e) {
return new String(buf,63,30).trim();
}
}
public String getYear(){
try {
return new String(buf,93,4,charset).trim();
} catch (UnsupportedEncodingException e) {
return new String(buf,93,4).trim();
}
}
public String getComment(){
try {
return new String(buf,97,28,charset).trim();
} catch (UnsupportedEncodingException e) {
return new String(buf,97,28).trim();
}
}
}
注意:需要使用gbk编码utf-8会出现乱码的。