Delice
Delice

Reputation: 856

How to stop multiple songs playing at same time?

I have a list of songs i put manually inside my app and it currently have 3 functions: start, pause and stop (using ImageViews).

The problem is that i can play multiple songs at the same time that is not supposed to be like that. I really cant find the issue here and hope someone can help.

This is a demonstration on my problem

I want it to STOP currently playing song when another song is being clicked on.

Here is my code for my play button:

viewholder.playB.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (currentSong == null || song != currentSong) {
                currentSong = song;

                mediaPlayer = MediaPlayer.create(context, song.getSong());
            }
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
                viewholder.playB.setImageResource(R.drawable.play_black);
            } else {
                mediaPlayer.start();
                viewholder.playB.setImageResource(R.drawable.pause_black);
            }
        }
    });

Upvotes: 0

Views: 640

Answers (1)

André Sousa
André Sousa

Reputation: 1730

Instead of always creating a new instance of MediaPlayer every time the event onClick is called, you should create a single instance and reused it.


To play a new song don't forget to reset your player first. Here is an example:

mPlayer.reset();
mPlayer.setDataSource(context, song.getSong());

Upvotes: 1

Related Questions