【问题标题】:java.lang.IllegalStateException in MediaPlayerMediaPlayer 中的 java.lang.IllegalStateException
【发布时间】:2017-05-18 08:59:03
【问题描述】:

这是我的代码:

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

【问题讨论】:

    标签: java android media-player illegalstateexception


    【解决方案1】:

    MediaPlayer 的文档说明:

    MediaPlayer create (Context context, int resid) 为给定资源 ID 创建 MediaPlayer 的便捷方法。成功时,prepare() 将已被调用且不得再次调用。

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

    所以您的IllegalStateException 发生是因为prepare() 要求MediaPlayer 处于已初始化已停止 状态,但是当create(Context context, int resid) 被调用时,它调用prepare() 导致MediaPlayer 处于Prepared 状态,而在调用prepare() 时一定不能处于这种状态。

    简而言之:删除prepare() 调用,IllegalStateException 不应再出现。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-07
      • 2021-08-18
      • 1970-01-01
      • 1970-01-01
      • 2018-05-03
      • 1970-01-01
      相关资源
      最近更新 更多