Search code examples
androidmp3android-mediaplayer

How to play a lot of sounds in background of an activity?


For example, I want to play 3 songs. When the 1st song ends, the 2nd song begins, and when the 2nd song ends, the 3rd song begins, and when the 3rd song ends, the 1st song begins again and so on. Is the mp.setOnCompletionListener used here?


Solution

  • You are right. You can do something simple like this:

    public class MainActivity extends Activity {
    
        MediaPlayer mp1, mp2, mp3;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            mp1 = MediaPlayer.create(this, R.raw.music_1);
            mp2 = MediaPlayer.create(this, R.raw.music_2);
            mp3 = MediaPlayer.create(this, R.raw.music_3);
    
            mp1.start();
    
            mp1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mp2.start();
                }
            });
    
            mp2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mp3.start();
                }
            });
    
            mp3.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mp1.start();
                }
            });
        }
    }
    

    This will play mp1 and onCompletion of it, it will play mp2, and onCompletion of mp2, it will play mp3, and onCompletion of mp3, it will play mp1 again and so on...