使用Android Studio的音乐播放器Seekbar

时间:2015-09-27 16:50:55

标签: android audio-player

我在一个非常简单的音乐播放器中工作,有一个搜索栏。 我可以让它工作,但是我遇到了播放音乐的问题,它每秒都无法正常工作 - 它向后退了一段时间,然后再次像是一辆小车一样。

这是完整的代码:

private MediaPlayer mediaPlayer;
private Button button;
private TextView textView;
private SeekBar seek;
private Handler mHandler = new Handler();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    button = (Button)findViewById(R.id.button);
    textView = (TextView)findViewById(R.id.text);
    seek = (SeekBar)findViewById(R.id.seek);

    mediaPlayer = new MediaPlayer();
    mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.threedays);


    MainActivity.this.runOnUiThread(new Runnable() {

        @Override
        public void run() {



            if(mediaPlayer != null){
                int mCurrentPosition = mediaPlayer.getCurrentPosition() / 1000;
                seek.setProgress(mCurrentPosition);
            }
            mHandler.postDelayed(this, 1000);
        }
    });


    seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {


            seekBar.setMax(mediaPlayer.getDuration() / 1000);
            textView.setText(progress + "/" + seekBar.getMax());
            mediaPlayer.seekTo(progress*1000);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });


    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {

            pause();

        }
    });


    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (mediaPlayer.isPlaying()) {
                pause();
            } else {

                start();
            }

        }
    });
}

public void start(){
    if(mediaPlayer!=null) {
        mediaPlayer.start();
        button.setText("Pause");
    }
}

public void pause(){
    if(mediaPlayer!=null) {
        mediaPlayer.pause();
        button.setText("Play");
    }
}

@Override
protected void onDestroy() {

    if(mediaPlayer!=null && mediaPlayer.isPlaying()) {
        mediaPlayer.pause();
        mediaPlayer.release();
        mediaPlayer = null;
    }

    super.onDestroy();
}

1 个答案:

答案 0 :(得分:3)

seek.setOnSeekBarChangeListener

上试用此代码
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
{
    seekBar.setMax(mediaPlayer.getDuration() / 1000);
    textView.setText(progress + "/" + seekBar.getMax());

    if(fromUser)
    {
        mediaPlayer.seekTo(progress*1000);
    }
}