一:使用 javasound api:
public void method1() { File file = new File("C:\\music\\test2.mp3"); long total = 0; try { AudioFileFormat aff = AudioSystem.getAudioFileFormat(file); Map props = aff.properties(); if (props.containsKey("duration")) { total = (long) Math.round((((Long) props.get("duration")).longValue()) / 1000); } System.out.println(total / 1000); } catch (Exception e) { e.printStackTrace(); } }
网上有些同志说这段代码无法运行,我猜应该是缺少了 mp3 的解码插件,下载地址为:http://www.javazoom.net/mp3spi/mp3spi.html
二:使用 jaudiotagger.jar 包实现,网上搜下就能找到,代码如下:
public void method2() { 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(); } }
三:java 中直接使用 AudioInputStream 类来操作音乐文件,获取时长,实例如下:、
import java.io.File; import java.io.IOException; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; public class AudioLength { public static void main(String[] args) throws LineUnavailableException, UnsupportedAudioFileException, IOException { File file = new File("d:/test.wav"); Clip clip = AudioSystem.getClip(); AudioInputStream ais = AudioSystem.getAudioInputStream(file); clip.open(ais); System.out.println( clip.getMicrosecondLength() / 1000000D + " s" );//获取音频文件时长 } }
这三种方法都只能获得本地音频文件的音乐时长,如果是获取网络音乐的时长,地址:http://www.javastar.net/?post=50
源码下载地址:http://download.csdn.net/detail/jys1109/5871797