简体   繁体   English

带 Seekbar 的音乐播放器 (Android Studio)

[英]Music player with Seekbar (Android Studio)

  • I was working in a very simple music player with a seek bar.我在一个带有搜索栏的非常简单的音乐播放器中工作。 But I got a problem with playing music,it doesn't work correctly every second - it backwards a while, then remain again like it's a buggy.但是我在播放音乐时遇到了问题,它不能每秒都正常工作 - 它向后倒退了一段时间,然后又像一辆马车一样保持不变。

    I know why but I can't solve it.我知道为什么,但我无法解决它。

    When the progress bar moves forward, the music recalibrates and vice versa, when the music moves forward, the progress bar recalibrates.当进度条向前移动时,音乐重新校准,反之亦然,当音乐向前移动时,进度条重新校准。 It's probably because of that that every time it goes back.大概是因为每次回去吧。 But I tried several things and still have the same problem.但我尝试了几件事,仍然有同样的问题。

  • Another problem is that when the music is paused, the progress bar goes in the opposite direction until it reaches zero.另一个问题是,当音乐暂停时,进度条会向相反的方向移动,直到达到零。 It doesn't stay where it was before the break.它不会停留在休息前的位置。

The full code :完整代码:

public class MainActivity extends AppCompatActivity {

private MediaPlayer mediaPlayer;
private SeekBar seekBar;
private boolean bool = false;

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

    this.seekBar = (SeekBar) findViewById(R.id.sound_bar);
    this.mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.music);

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            seekBar.setProgress(mediaPlayer.getCurrentPosition() * seekBar.getMax() / mediaPlayer.getDuration());
        }
    }, 500, 500);

    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            mediaPlayer.seekTo(seekBar.getProgress() * mediaPlayer.getDuration() / seekBar.getMax());
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });
}

public void playSound(View view) {

    Button button = (Button) view;

    if(bool) {
        mediaPlayer.pause();
        bool = false;
        button.setText("Jouer le son");
    } else {
        mediaPlayer.start();
        bool = true;
        button.setText("Mettre en pause");
    }
}

@Override
protected void onPause() {
    super.onPause();
    mediaPlayer.pause();
}

@Override
protected void onStart() {
    super.onStart();
    if(bool) {
        mediaPlayer.start();
    }
}

} }

Maybe use another thread to control the seekbar would help.也许使用另一个线程来控制搜索栏会有所帮助。

Take a look at this看看这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM