javafx UNKNOWN duration on Media object

后端 未结 2 382
没有蜡笔的小新
没有蜡笔的小新 2021-01-12 20:53

I am a newbie to both Java and JavaFX, I\'ve spent the last couple years developing on Python with QT, and I am now developing in Java and JavaFX.

I am developing a

相关标签:
2条回答
  • 2021-01-12 21:21

    If you read the javadoc for Media class, it says you should wait for the media player to be ready:

    The media information is obtained asynchronously and so not necessarily available immediately after instantiation of the class. All information should however be available if the instance has been associated with a MediaPlayer and that player has transitioned to Status.READY status

    So you just need to create an instance of MediaPlayer and listen for the Status.READY:

        File filestring = new File("my/file/dir/file.mp3");
        Media file = new Media(filestring.toURI().toString());  
    
        MediaPlayer mediaPlayer = new MediaPlayer(file);
    
        mediaPlayer.setOnReady(new Runnable() {
    
            @Override
            public void run() {
    
                System.out.println("Duration: "+file.getDuration().toSeconds());
    
                // display media's metadata
                for (Map.Entry<String, Object> entry : file.getMetadata().entrySet()){
                    System.out.println(entry.getKey() + ": " + entry.getValue());
                }
    
                // play if you want
                mediaPlayer.play();
            }
        });
    
    0 讨论(0)
  • 2021-01-12 21:32

    It looks like the Media needs some time to get fully initialized. Add a Thread sleep beforebthe getDuration line and try again!

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