I have a weird problem with this code whilst the error is simple I don't understand it.
Class with MediaPlayer sound and methods:
public class Sounds {
private MediaPlayer stone;
private MediaPlayer gong;
public Sounds(Context con, int stoneSound, int gongSound){
this.stone = MediaPlayer.create(con, stoneSound);
this.gong = MediaPlayer.create(con, gongSound);
}
public void ActivateStone(){
MediaPlayer auxStone = this.stone;
auxStone.start(); //THIS IS THE LINE 19 of "Sounds.java:19" log error
auxStone.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
public void ActivateGong(){
MediaPlayer auxGong = this.gong;
auxGong.start();
auxGong.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
Now the thread that calls the method to use the "sound" each interval
public void run() {
while (!stoped) {
try {
this.sleep(interval);
if (stones == mode || stones == (mode * 2)) {
sounds.ActivateGong();
} else {
sounds.ActivateStone(); //THIS IS THE LINE 32 in "Counter.java:32" log error
}
} catch (InterruptedException e) {
e.printStackTrace();
}
stones += 1;
handler.setHcron(stones + "");
handler.act();
}
}
The sounds ONLY play once and then the app throws an exception with this log:
05-09 19:10:52.306: E/AndroidRuntime(479): FATAL EXCEPTION: Thread-9448
05-09 19:10:52.306: E/AndroidRuntime(479): Process: contador.piedras.jugger, PID: 479
05-09 19:10:52.306: E/AndroidRuntime(479): java.lang.IllegalStateException
05-09 19:10:52.306: E/AndroidRuntime(479): at android.media.MediaPlayer._start(Native Method)
05-09 19:10:52.306: E/AndroidRuntime(479): at android.media.MediaPlayer.start(MediaPlayer.java:1074)
05-09 19:10:52.306: E/AndroidRuntime(479): at contador.piedras.jugger.Sounds.ActivateStone(Sounds.java:19)
05-09 19:10:52.306: E/AndroidRuntime(479): at contador.piedras.jugger.Counter.run(Counter.java:32)
Maybe you should try to add sync, it can be cause of threads :
synchronized (auxStone) {
auxStone.start(); //THIS IS THE LINE 19 of "Sounds.java:19" log error
auxStone.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
EDIT: as documentation declares, this method : Throws:
IllegalStateException - if it is called in an invalid state. So you need to check it for playing by if(!auxStone.isPlaying())