0

Im using the following code to play music.

if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.reset();
            mMediaPlayer = new MediaPlayer();
            try {
                mMediaPlayer.setDataSource(MainActivity.localTrackList.get(MainActivity.currentOffset).getPath());
            } catch (IOException e) {
                e.printStackTrace();
            }
            mMediaPlayer.prepareAsync();

        } else {
            mMediaPlayer = new MediaPlayer();

            try {
                mMediaPlayer.setDataSource(MainActivity.localTrackList.get(MainActivity.currentOffset).getPath());
            } catch (IOException e) {
                e.printStackTrace();
            }
            mMediaPlayer.prepareAsync();
        }

Explanation:

  • when the user clicks a song for the first time, else loop will be executed.
  • If the user clicks a song when the mediaplayer is playing a song already, if loop will be executed
  • In my if loop, Im resetting the mediaplayer before setting the data source so it calls the onCompletion listener.

Follwing is my onCompletionListener.

mMediaPlayer.setOnCompletionListener(mp -> {
                    MainActivity.nextTrackController.performClick();
        });

Following is my nextTrackController onClickListener.

 MainActivity.nextTrackController.setOnClickListener(v -> {
            try {
                if (MainActivity.currentOffset < (MainActivity.localTrackList.size() - 1)) {
                    if (mMediaPlayer.isPlaying()) {
                        mMediaPlayer.stop();
                        mMediaPlayer.reset();
                    } else {
                        mMediaPlayer.reset();
                    }

                    MainActivity.currentOffset = MainActivity.currentOffset + 1;
                    mMediaPlayer.setDataSource(MainActivity.localTrackList.get(MainActivity.currentOffset).getPath());
                    mMediaPlayer.prepareAsync();
                } else {

                    if (mMediaPlayer.isPlaying()) {
                        mMediaPlayer.stop();
                        mMediaPlayer.reset();
                    }
                    MainActivity.currentOffset = 0;
                    mMediaPlayer.setDataSource(MainActivity.localTrackList.get(MainActivity.currentOffset).getPath());
                    mMediaPlayer.prepareAsync();
                }
            } catch (Exception ex) {

            }
        });

the problem is that,

  1. If the media player is playing and if the user is clicking a song, it is not playing the specific song that had been clicked but it plays some random song.
  2. If the song finished playing, it plays a random song instead of the next song. How can i be able to sort this out?

0 Answers0