安卓MediaPlayerのprepare小记

第二次栽在MediaPlayer的prepare()上面了,报错内容都一样。

总而言之,不要prepare()两遍啊!

这次运气不错,Google后Stackoverflow上直接找到了原因[1],不像上次搜了半天,才发现是自己画蛇添足。

The documentation for MediaPlayer states:

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.

自行找到create(android.content.Context, int)
So your IllegalStateException occurs because prepare() requires the MediaPlayer to be in either a Initialized or Stopped state, but when create(Context context, int resid) is invoked, it calls prepare() resulting in the MediaPlayer being in the Prepared state which it must not be when prepare() is invoked.
In short: remove the prepare() call and the IllegalStateException should no longer occur.
A full State Diagram and list of valid states is presented in the documentation.

参考资料

  1. java.lang.IllegalStateException in MediaPlayer