Make a seek bar for media player.

Haxor picture Haxor · Oct 8, 2012 · Viewed 10.4k times · Source

I am making a media player using JMF, I want to use my own control components Can anyone please help me in making a seek bar for media player so that it can play song according to the slider position.

Just suggest me some logic, I can figure out the coding part afterwards

if(player!=null){
    long durationNanoseconds = 
    (player.getDuration().getNanoseconds());
    durationbar.setMaximum((int) player.getDuration().getSeconds());
    int duration=(int) player.getDuration().getSeconds();
    int percent = durationbar.getValue();
    long t = (durationNanoseconds / duration) * percent;
    Time newTime = new Time(t);
    player.stop();
    player.setMediaTime(newTime);
    player.start();
    mousedrag=true;

Here is the code. Now how can I make the slider move along with the song? Slider works when I drag/click on it, but it doesn't move with the song.

Answer

Andrew Thompson picture Andrew Thompson · Oct 9, 2012

The problem with using a slider for this is that when the slider position is moved programmatically, it fires events. When an event is fired on a slider, it typically means the app. has to do something, such as move the song position. The effect is a never ending loop. There is probably a way around this by setting flags and ignoring some events, but I decided to go a different way.

Instead I used a JProgressBar to indicate the location in the track, and a MouseListener to detect when the user clicks on a separate position. Update the progress bar use a Swing Timer that checks the track location every 50-200 milliseconds. When a MouseEvent is detected, reposition the track.

The bar can be seen in the upper right of this GUI. Hovering over it will produce a tool tip showing the time in the track at that mouse position.

Duke Box using progress bar for track postion