Finding Duration of an MP3 file in Java

旧巷老猫 提交于 2019-12-18 09:39:15

问题


OK so I have tried using ID3 tags to get the duration and I also tried using JMF media player.getDuration().

player.getDuration().getSeconds()

The file is VBR. Are there any light weight libraries or something inside JMF that could be used to solve this problem.

Thanks.


回答1:


I use JAudioTagger to achieve this. The below code will get you the duration of an MP3 track.

int duration = 0;

try {
  AudioFile audioFile = AudioFileIO.read(new File("file.mp3"));
  duration = audioFile.getAudioHeader().getTrackLength();

} catch (Exception e) {
  e.printStackTrace();

}

You can alternatively cast audioFile.getAudioHeader() to MP3AudioHeader and use the method getPreciseTrackLength() to get a more precise duration. However, this (i believe) only applies to MP3 files and no other formats (such as WAV files).




回答2:


I using this lib and this code :

File f = new File("path/mp3");
    MediaLocator ml = null;
    Player p = null;
    try {
        ml = new MediaLocator(f.toURL());

        p = Manager.createPlayer(ml);
        p.start();
        while (true) {
            Thread.sleep(1000);
            System.out.println("Media Time :: "+p.getMediaTime().getSeconds());
            System.out.println("Duration :: "+p.getDuration().getSeconds());
            if(p.getMediaTime().getSeconds() == p.getDuration().getSeconds())
                break;
        }
        p.stop();
        p.deallocate();
        p.close();
    } catch (NoPlayerException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

Good luck.



来源:https://stackoverflow.com/questions/5759331/finding-duration-of-an-mp3-file-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!