The problem is that your MediaPlayer does not have the information about the duration of the video until the playback has started.
If you execute the getLength()
method just after executing the play()
method, the video has not yet begun to play, and therefore, since the duration information is not available, the getLength()
method returns -1.
To obtain the duration of the video, you can do it in several ways. I leave you two that have occurred to me, one with events and the other with threads.
For both cases the video that I downloaded the following video
Get duration through events
Imports the following to your class:
import uk.co.caprica.vlcj.player.MediaPlayer;
import uk.co.caprica.vlcj.player.MediaPlayerEventAdapter;
Add an eventLister of type MediaPlayerEventAdapter
to your object EmbeddedMediaPlayer
emp.addMediaPlayerEventListener(new MediaPlayerEventAdapter()
{
@Override
public void playing(MediaPlayer mediaPlayer)
{
System.out.println("Duracion: " + (long)mediaPlayer.getMediaMeta().getLength() / 1000);
}
});
Get duration using a thread:
Hilo.java
import uk.co.caprica.vlcj.player.embedded.EmbeddedMediaPlayer;
public class Hilo implements Runnable{
long len;
EmbeddedMediaPlayer player = null;
public Hilo(EmbeddedMediaPlayer player){
this.player = player;
}
@Override
public void run() {
try {
// Dormimos el hilo para asegurarnos que la reproducción ha comenzado
// Pongo 1 segundo para que veas el funcionamiento. El tiempo lo tienes que ajustar
Thread.sleep(1000);
// Calculamos el tiempo del video en segundos.
len = (long)player.getMediaMeta().getLength() / 1000;
System.out.println(len);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
In your main class:
...
MediaPlayerFactory mpf=new MediaPlayerFactory();
emp = mpf.newEmbeddedMediaPlayer(new Win32FullScreenStrategy(this));
emp.setVideoSurface(mpf.newVideoSurface(c));
// Instanciamos el hilo
Runnable hilo = new Hilo(emp);
emp.prepareMedia("Video.mp4");
emp.play();
// Lanzamos el hilo
new Thread(hilo).start();
I hope it serves you.