MediaPlayer不会从其他类的方法调用开始

时间:2015-05-09 17:33:13

标签: android media-player

我对此代码有一个奇怪的问题,而错误很简单,我不明白。

使用MediaPlayer声音和方法的类:

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();
        }
    });
}

现在调用方法的线程使用"声音"每个间隔

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();
    }
}

声音只播放一次然后应用程序会抛出此日志的异常:

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)

1 个答案:

答案 0 :(得分:0)

也许你应该尝试添加同步,它可能是线程的原因:

if(!auxStone.isPlaying())

编辑:如文档所述,此方法:抛出: IllegalStateException - 如果在无效状态下调用它。所以你需要检查它是否由String configPath = System.getenv("CONFIG_PATH");

进行播放