Search code examples
javaandroidandroid-mediaplayer

MediaPlayer: Sounds playing over the top of each other


I have a soundboard with multiple buttons (approx 17), each linked to a .mp3 sound.

The issue is that when a sound is playing and I press another button, both are then playing in the background.

I would like to be able to stop the playing sound and start the new one when a different button is pressed. Also, is there the ability to stop the current playing sound by pressing on its button again?

Also, I don't really like the section of code that states: private MediaPlayer[] mPlayers = new MediaPlayer[17];

The number (in this case 17), determines the amount of times sounds can be played. After that, no further sounds can be played it seems. Is there a way of making this indefinite?

Rather than paste all of the code from my activity, I have attached the salient code and numbered it in the order in which it appears on my main activity .java file.

Thanks for your help all.

    private int mNextPlayer = 0;


2) a.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                v.startAnimation(animAlpha);

                startSound(R.raw.likethebattle);

            }

        });


3) public void onDestroy() {
        super.onDestroy(); // <---------------------- This needed to be there
        for (int i = 0; i < mPlayers.length; ++i)
            if (mPlayers[i] != null)
                try {
                    mPlayers[i].release();
                    mPlayers[i] = null;
                } catch (Exception ex) {
                    // handle...
                }
    }

4)    private void startSound(int id) {
        try {


            if (mPlayers[mNextPlayer] != null) {

                mPlayers[mNextPlayer].reset();
                mPlayers[mNextPlayer].prepare();

                mPlayers[mNextPlayer].stop();
                mPlayers[mNextPlayer].release();
                mPlayers[mNextPlayer] = null;
            }
            mPlayers[mNextPlayer] = MediaPlayer.create(this, id);
            mPlayers[mNextPlayer].start();
        } catch (Exception ex) {
            // handle
        } finally {
            ++mNextPlayer;
            mNextPlayer %= mPlayers.length;
        }

    }


Solution

  • It looks like you are not stoping currently playing MediaPlayer. startSound(id) does not stop currently playing sound. In finally { ++mNextPlayer; mNextPlayer %= mPlayers.length; } you move you counter to next player in array and next time you enter startSound() method your counter does not point to previously started player so it can not stop it.