java mp3 信息_java读取MP3的信息

标签头"TAG" 3字节

标题 30字节

作者 30字节

专辑 30字节

出品年份 4字节

备注信息 28字节

保留 1字节

音轨 1字节

类型 1字节

import java.io.File;

import java.io.IOException;

import java.io.RandomAccessFile;

import java.io.UnsupportedEncodingException;

/**

* 获得MP3文件的信息

*

*/

public class MP3Info {

public static void main(String[] args) {

// TODO 演示

File MP3FILE = new File("test.mp3");

try {

MP3Info info = new MP3Info(MP3FILE);

info.setCharset("gbk");

System.out.println(info.getSongName());

System.out.println(info.getArtist());

System.out.println(info.getAlbum());

System.out.println(info.getYear());

System.out.println(info.getComment());

} catch (IOException e) {

e.printStackTrace();

}

}

private String charset = "utf-8";// 解析MP3信息时用的字符编码

private byte[] buf;// MP3的标签信息的byte数组

/**

* 实例化一个获得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();// 关闭文件

if (buf.length != 128) {// 数据是否合法

throw new IOException("MP3标签信息数据长度不合法!");

}

if (!"TAG".equalsIgnoreCase(new String(buf, 0, 3))) {// 信息格式是否正确

throw new IOException("MP3标签信息数据格式不正确!");

}

}

/**

* 获得目前解析时用的字符编码

*

* @return 目前解析时用的字符编码

*/

public String getCharset() {

return charset;

}

/**

* 设置解析时用的字符编码

*

* @param charset

* 解析时用的字符编码

*/

public void setCharset(String charset) {

this.charset = charset;

}

public String getSongName() {

try {

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();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值