setOnCompletionListener
is detecting the completion of a song the first time only. In the code below song1
and song2
are played one after the other but the remaining songs are not being played.
I want to play the songs one by one and add some silence between songs.
MediaPlayer song0=new MediaPlayer();
int track = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
song0=MediaPlayer.create(this,R.raw.song1);
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
function();
}
});
song0.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer song0) {
track++;
loadsong();
function();
}
});
}
void loadsong()
{
if(track==1) song0=MediaPlayer.create(this,R.raw.song2);
if(track==2) song0=MediaPlayer.create(this,R.raw.song3);
if(track==3) song0=MediaPlayer.create(this,R.raw.song4);
}**strong text**
void function(){
if(track<4) song0.start();
else
song0.stop();
}
Your onclickListener
event only starting for once. If you want to play song one by one you have to create a loop or have to do it recursively. Here's a snippet where I used song0.setOnCompletionListener
inside loadsong()
and in the event recursively called loadsong()
every time. Changed your loadsong()
method a little bit. Here is the code:
public class MainActivity extends AppCompatActivity {
private Button play;
MediaPlayer song0 = new MediaPlayer();
int track = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play = findViewById(R.id.play);
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
loadsong();
}
});
}
void loadsong() {
track++;
if (track == 1) {
song0 = MediaPlayer.create(this, R.raw.track1);
song0.start();
}else if (track == 2) {
song0 = MediaPlayer.create(this, R.raw.track2);
song0.start();
}else if (track == 3) {
song0 = MediaPlayer.create(this, R.raw.track3);
song0.start();
}else if (track > 3) {
song0.stop();
}
song0.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer song) {
song.stop();
loadsong();
}
});
}
}