Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 356
John Avatar asked Oct 26 '25 00:10

John


1 Answers

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"

like image 86
Sathya Avatar answered Oct 27 '25 15:10

Sathya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!