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

心不动则不痛 提交于 2019-12-10 19:04:24

问题


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?


回答1:


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...




回答2:


First declare the 3 MediaPlayer files:

MediaPlayer song1;
MediaPlayer song2;
MediaPlayer song3;

Then initialize the MediaPlayer objects:

song1 = MediaPlayer.create(this, R.raw.exampleSong1);
song2 = MediaPlayer.create(this, R.raw.exampleSong2);
song3 = MediaPlayer.create(this, R.raw.exampleSong3);

Now start the first Media file with

song1.start();

Now with every instance created you should add to every MediaPlayer object a setOnCompletionListener like this:

song1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mp) {
        song2.start();
    }
});

Do the same for the Second and Third MediaPlayer files:

song2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mp) {
        song3.start();
    }
});

song3.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mp) {
        song1.start();
    } 
});


来源:https://stackoverflow.com/questions/32678910/how-to-play-a-lot-of-sounds-in-background-of-an-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!