gpt4 book ai didi

MediaPlayer 中的 java.lang.IllegalStateException

转载 作者:太空宇宙 更新时间:2023-11-04 11:28:51 28 4
gpt4 key购买 nike

这是我的代码:

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有什么问题?我应该在代码中添加什么?我是新手,对于一个可能愚蠢的问题和糟糕的英语感到抱歉。

最佳答案

MediaPlayer 的文档指出:

MediaPlayer create (Context context, int resid) Convenience method to create a MediaPlayer for a given resource id. On success, prepare() will already have been called and must not be called again.

https://developer.android.com/reference/android/media/MediaPlayer.html#create(android.content.Context, int)

因此,发生 IllegalStateException 是因为 prepare() 要求 MediaPlayer 处于 InitializedStopped 状态,但是当调用 create(Context context, int resid) 时,它会调用 prepare() 导致 MediaPlayer 处于 Pre pared 状态,但在调用 prepare() 时不得处于此状态。

简而言之:删除 prepare() 调用,并且 IllegalStateException 不应再发生。

文档中提供了完整的状态图和有效状态列表。

关于MediaPlayer 中的 java.lang.IllegalStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44035149/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com