Search code examples
javaeclipsemedia-playerjslider

SeekBar (JSlider) has very choppy seeking (MediaPlayer, Java Swing)


You can see the problem here:

(gif)

How can I fix this? It only occasionally works if I 'throw' the slider's cursor with my mouse, and doesn't work if I wait and release. (my goal is to have seeking similar to 'foobar2000's seekbar.

timeSlider = new JSlider();
    timeSlider.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent e) {
                try{
                    int dv = timeSlider.getValue() * 1000;
                    timeSlider.setValue(dv);
                    Duration draggedVal = new Duration(dv);
                    mediaPlayer.seek(draggedVal);
                }catch (Exception e3){

                }
            }
    });

Solution

  • I've found a solution, and my problem lied in the way I set it to listen for dragging.

    Instead of using common sense and listening for actual drags, I instead listened for a "Mouse Release" (i.e, drag and release causes it to update the value to the released point) but this didn't do me any good, and caused the lag in the gif above.

    timeSlider.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent arg0) {
                isDragging = true;
                try{
                    int dv = timeSlider.getValue() * 1000;
                    timeSlider.setValue(dv);
                    Duration draggedVal = new Duration(dv);
                    mediaPlayer.seek(draggedVal);
                }catch (Exception e3){
    
                } finally {
                    isDragging = false;
                }
            }
        });
    

    Now, using an actual "mouseDragged" action listener, I can smoothly seek any mp3 file, and hear the music as I'm seeking :)