Finding Duration of an MP3 file in Java

前端 未结 2 1776
感情败类
感情败类 2020-12-22 01:16

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

player.getDuration().getSeconds()
相关标签:
2条回答
  • 2020-12-22 01:50

    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).

    0 讨论(0)
  • 2020-12-22 01:53

    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.

    0 讨论(0)
提交回复
热议问题