我正在尝试在for循环中创建一个MediaPlayer来播放数组中的声音。然而,应用程序在开始时使用以下代码崩溃。我做错了什么?
val songs = arrayOf(R.raw.c4, R.raw.e4)
for (song in songs) {
var mediaPlayer = MediaPlayer.create(getApplicationContext(),song)
mediaPlayer.prepare()
mediaPlayer.setOnPreparedListener { mediaPlayer -> mediaPlayer.start() }
}
//我认为这是错误
11-09 02:25:56.508 7033-7033/com.myapp.app D/MediaPlayer: setSubtitleAnchor in MediaPlayer
11-09 02:25:56.510 7033-7033/com.myapp.app E/MediaPlayer: prepareAsync called in state 8, mPlayer(0x9a2adde0)
11-09 02:25:56.510 7033-7033/com.myapp.app D/AndroidRuntime: Shutting down VM
11-09 02:25:56.510 7033-7033/com.myapp.app E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.myapp.app, PID: 7033
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp.app/com.myapp.app.NoteTrainerActivity}: java.lang.IllegalStateException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.IllegalStateException
at android.media.MediaPlayer._prepare(Native Method)
at android.media.MediaPlayer.prepare(MediaPlayer.java:1184)
at com.myapp.app.NoteTrainerActivity.onCreate(NoteTrainerActivity.kt:49)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
答案 0 :(得分:0)
当然,你有这个错误,为什么?您应首先检查create
方法Docs:
为给定资源ID创建MediaPlayer的便捷方法。成功时,prepare()已经被调用,不能再被调用。
您只需要执行以下操作:
MediaPlayer mediaPlayer = MediaPlayer.create(this, raw);
mediaPlayer.start(); // create is sychronize method, you just need to call it immediately after `create`.