SeekBar and media player in android

前端 未结 12 2043
天涯浪人
天涯浪人 2020-11-28 03:13

I have a simple player and recorder. Everything works great but have a one problem. I want to add seek bar to see progress in playing record and use this seek bar to set pl

12条回答
  •  半阙折子戏
    2020-11-28 04:08

    The below code worked for me.

    I've created a method for seekbar

    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        mp.start();
         getDurationTimer();
        getSeekBarStatus();
    
    
    }
    //Creating duration time method
    public void getDurationTimer(){
        final long minutes=(mSongDuration/1000)/60;
        final int seconds= (int) ((mSongDuration/1000)%60);
        SongMaxLength.setText(minutes+ ":"+seconds);
    
    
    }
    
    
    
     //creating a method for seekBar progress
    public void getSeekBarStatus(){
    
        new Thread(new Runnable() {
    
            @Override
            public void run() {
                // mp is your MediaPlayer
                // progress is your ProgressBar
    
                int currentPosition = 0;
                int total = mp.getDuration();
                seekBar.setMax(total);
                while (mp != null && currentPosition < total) {
                    try {
                        Thread.sleep(1000);
                        currentPosition = mp.getCurrentPosition();
                    } catch (InterruptedException e) {
                        return;
                    }
                    seekBar.setProgress(currentPosition);
    
                }
            }
        }).start();
    
    
    
    
    
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            int progress=0;
    
            @Override
            public void onProgressChanged(final SeekBar seekBar, int ProgressValue, boolean fromUser) {
                if (fromUser) {
                    mp.seekTo(ProgressValue);//if user drags the seekbar, it gets the position and updates in textView.
                }
                final long mMinutes=(ProgressValue/1000)/60;//converting into minutes
                final int mSeconds=((ProgressValue/1000)%60);//converting into seconds
                SongProgress.setText(mMinutes+":"+mSeconds);
            }
    
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
    
            }
    
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
    
            }
        });
    }
    

    SongProgress and SongMaxLength are the TextView to show song duration and song length.

提交回复
热议问题