这是我的密码:
final MediaPlayer[] threeSound = new MediaPlayer[1];
threeSound[0] = new MediaPlayer();
final CountDownTimer playThreeSound = new CountDownTimer(1000, 1) {
boolean timerStarted = false;
@Override
public void onTick(long millisUntilFinished) {
torgText.setText("3...");
if (!timerStarted) {
timerStarted = true;
threeSound[0] = MediaPlayer.create(PlayActivity.this, R.raw.three);
try {
threeSound[0].prepare();
threeSound[0].start();
} catch (IOException e) {
e.printStackTrace();
Log.e("IOE", "Something went wrong");
}
}
}
@Override
public void onFinish() {
if (threeSound[0].isPlaying()) {
threeSound[0].stop();
}
playTwoSound.start();
}
};
它抛出了IllegalStateException。这些是原木:
FATAL EXCEPTION: main
Process: testapplication.android.com.guesstune_v2, PID: 3641
java.lang.IllegalStateException
at android.media.MediaPlayer._prepare(Native Method)
at android.media.MediaPlayer.prepare(MediaPlayer.java:1351)
at testapplication.android.com.guesstune_v2.PlayActivity$6.onTick(PlayActivity.java:316)
at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:133)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:7007)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
准备MediaPlayer有什么问题?我应该在代码中添加什么?我是个新手,为一个可能很愚蠢的问题和糟糕的英语感到抱歉。
发布于 2017-05-17 22:13:06
MediaPlayer
的文档声明:
为给定的资源id创建MediaPlayer的方便方法。一旦成功,
prepare()
就已经被调用了,不能再被调用了。
因此,您的IllegalStateException
之所以出现,是因为prepare()
要求MediaPlayer
处于初始化或停止状态,但是当调用create(Context context, int resid)
时,它会调用prepare()
,从而导致MediaPlayer
处于准备状态,而在调用prepare()
时则不能这样做。
简而言之:删除prepare()
调用,IllegalStateException
就不会再发生了。
文档中提供了一个完整的状态图和有效状态列表。
https://stackoverflow.com/questions/44035149
复制相似问题