如何在活动的背景中播放很多声音?

时间:2015-09-20 11:33:04

标签: android mp3 android-mediaplayer

例如,我想播放3首歌曲。当第一首歌曲结束时,第二首歌曲开始,第二首歌曲结束,第三首歌曲开始,第三首歌曲结束,第一首歌曲再次开始,依此类推。这里使用了{{1}}吗?

2 个答案:

答案 0 :(得分:2)

你是对的。你可以做这样简单的事情:

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();
            }
        });
    }
}

这将播放mp1和onCompletion它,它将播放mp2,并且onmpmpletion为mp2,它​​将播放mp3,并且onCompletion of mp3,它将再次播放mp1等等...

答案 1 :(得分:1)

首先声明3个MediaPlayer文件:

MediaPlayer song1;
MediaPlayer song2;
MediaPlayer song3;

然后初始化MediaPlayer个对象:

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

现在使用

启动第一个媒体文件
song1.start();

现在,每创建一个实例,您应该像这样添加MediaPlayersetOnCompletionListener对象:

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

对第二个和第三个MediaPlayer文件执行相同的操作:

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();
    } 
});