John
John

Reputation: 63

Check and see if a sound is playing, wait for it to finish and then play another

What i am trying to acomplish is for me to click on a button and then play a sound based on a substring.

This is my current code for pressing the button :

display.setText("start");
thefull = thef.getText().toString();
for(int a=0;a<thefull.length();a++)
{
letter=thefull.substring(a,a+1);
if(letter=="m")
{
oursong = MediaPlayer.create(MainActivity.this, R.raw.m);
oursong.start();
while(oursong.isPlaying())
{
display.setText("start");
}
oursong.release();
}
else if(letter=="a")
{
oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
oursong.start();
while(oursong.isPlaying())
{
display.setText("start");
}
oursong.release();
}       
display.setText("done");

but for some reason when i click my button no sound is played. I am also new to android and java programming, so am i going right about doing this?

Because what i really want is for the program to keep checking if a sound is playing(in this case "oursound) when the button is clicked and if the sound is playing i want the program to wait for it to finish to start another sound right after it. But for now my code doesn´t play any sounds

Upvotes: 4

Views: 7388

Answers (1)

Sathya
Sathya

Reputation: 678

First of all you need to stop the media player before releasing it(its safer.)

Second, instead of using while(oursong.isPlaying()) { display.setText("start"); } ; you have to register OnCompletionListener using setOnCompletionListener method. When the song is played endCompletion will be called. Like so;

MediaPlayer mp = new MediaPlayer();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
public void onCompletion(MediaPlayer player) {
   player.release();          
}});

and inside the onComplete should reset the text "done"

Upvotes: 7

Related Questions