When playing an audio file using Android MediaPlayer, there are sometimes prepareasync called in the State 8 error.
The following methods can prevent this exception from appearing.
The first method:
Private voidPlayaudio (String audiouri) {URI Uri=Uri.parse (Audiouri); Mmediaplayer=mediaplayer.create (Getapplicationcontext (), URI); Try { //before playing, judge whether the Playermusic is occupied, so that the error will not be if(Mmediaplayer! =NULL) {mmediaplayer.stop (); } mmediaplayer.prepare (); Mmediaplayer.start (); } Catch(IllegalStateException e) {e.printstacktrace ();}Catch(IOException e) {e.printstacktrace ();}}
The second method:
Try { if(!isplaying) {isplaying=true; //Loading ResourcesMediaPlayer = Mediaplayer.create (playsdmp3activity. This, r.raw.trouble); Isreleased=false; Mediaplayer.setlooping (true); Mediaplayer.start (); Mtextview.settext ("Music is currently playing!" "); }} Catch(IllegalStateException e) {//TODO auto-generated Catch blocke.printstacktrace ();}
Mediaplayer.create (CONTEXT,RESID) This way to configure the data source, it completes the initialization, so do not prepare can directly start, we must always remember Nullpoint Exception, so here to add judgment:
!isplaying and mmediaplayer! = null
Android (Java) Learning note 180:android MediaPlayer play Prepareasync called in the State 8 workaround