SeekBar and media player in android

前端 未结 12 2027
天涯浪人
天涯浪人 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:14

    To create a 'connection' between SeekBar and MediaPlayer you need first to get your current recording max duration and set it to your seek bar.

    mSeekBar.setMax(mFileDuration/1000); // where mFileDuration is mMediaPlayer.getDuration();
    

    After you initialise your MediaPlayer and for example press play button, you should create handler and post runnable so you can update your SeekBar (in the UI thread itself) with the current position of your MediaPlayer like this :

    private Handler mHandler = new Handler();
    //Make sure you update Seekbar on UI thread
    MainActivity.this.runOnUiThread(new Runnable() {
    
        @Override
        public void run() {
            if(mMediaPlayer != null){
                int mCurrentPosition = mMediaPlayer.getCurrentPosition() / 1000;
                mSeekBar.setProgress(mCurrentPosition);
            }
            mHandler.postDelayed(this, 1000);
        }
    });
    

    and update that value every second.

    If you need to update the MediaPlayer's position while user drag your SeekBar you should add OnSeekBarChangeListener to your SeekBar and do it there :

            mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
    
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
    
            }
    
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
    
            }
    
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {                
                    if(mMediaPlayer != null && fromUser){
                        mMediaPlayer.seekTo(progress * 1000);
                    }
                }
        });
    

    And that should do the trick! : )

    EDIT: One thing which I've noticed in your code, don't do :

    public MainActivity() {
        mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
        mFileName += "/audiorecordtest.3gp";
    }
    

    make all initialisations in your onCreate(); , do not create constructors of your Activity.

提交回复
热议问题