最近有一个用java获取mp3播放时长的需求,有两种,一种本地文件,一种网络文件,其中获取网络mp3播放时间的方法找了挺久终于找到个能用的了。
第一种很简单,下载个jar包 jaudiotagger.jar
File file = new File("C:\music\test2.mp3"); try { MP3File f = (MP3File)AudioFileIO.read(file); MP3AudioHeader audioHeader = (MP3AudioHeader)f.getAudioHeader(); System.out.println(audioHeader.getTrackLength()); } catch(Exception e) { e.printStackTrace(); }
第二种,网络地址引入 jl1.0.1.jar
import java.io.BufferedInputStream; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import javazoom.jl.decoder.Bitstream; import javazoom.jl.decoder.BitstreamException; import javazoom.jl.decoder.Header; public class Test { public static void main(String[] args) throws IOException, BitstreamException { URL urlfile = new URL("http://sc1.111ttt.com/2015/1/06/06/99060941326.mp3"); URLConnection con = null; try { con = urlfile.openConnection(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } int b = con.getContentLength();// BufferedInputStream bis = new BufferedInputStream(con.getInputStream()); Bitstream bt = new Bitstream(bis); Header h = bt.readFrame(); int time = (int) h.total_ms(b); System.out.println(time / 1000); } }