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 a
Solution 1:
You are right. You can do something simple like this:
publicclassMainActivityextendsActivity {
MediaPlayer mp1, mp2, mp3;
@OverrideprotectedvoidonCreate(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(newMediaPlayer.OnCompletionListener() {
@OverridepublicvoidonCompletion(MediaPlayer mp) {
mp2.start();
}
});
mp2.setOnCompletionListener(newMediaPlayer.OnCompletionListener() {
@OverridepublicvoidonCompletion(MediaPlayer mp) {
mp3.start();
}
});
mp3.setOnCompletionListener(newMediaPlayer.OnCompletionListener() {
@OverridepublicvoidonCompletion(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...
Solution 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
Baca Juga
song1.start();
Now with every instance created you should add to every MediaPlayer
object a setOnCompletionListener
like this:
song1.setOnCompletionListener(newMediaPlayer.OnCompletionListener() {
@OverridepublicvoidonCompletion(MediaPlayer mp) {
song2.start();
}
});
Do the same for the Second and Third MediaPlayer files:
song2.setOnCompletionListener(newMediaPlayer.OnCompletionListener() {
@OverridepublicvoidonCompletion(MediaPlayer mp) {
song3.start();
}
});
song3.setOnCompletionListener(newMediaPlayer.OnCompletionListener() {
@OverridepublicvoidonCompletion(MediaPlayer mp) {
song1.start();
}
});
Post a Comment for "How To Play A Lot Of Sounds In Background Of An Activity?"