Not much to say, directly on the code
public class Simplemediaplayeractivity extends Activity {//private static final Uri Mmusicuri = uri.fromfile (New File ("/sd Card/sound_file_1.mp3 "));p rivate static final Uri Mmusicuri = Uri.parse (" http://czanxi.azone.artron.net/users_info/ 88/czanxi/2009121322260351292.mp3 ");p rivate MediaPlayer mmediaplayer = null; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate);p layMusic1 ();} /** * In the first way, create */private void PlayMusic1 () {Stopcurrentmediaplayer () via Create, Mmediaplayer = Mediaplayer.create (This, Mmusicuri); Preparedmmediaplayer.start (); No need to call prepare (); Create () does this for you}/** * second way, created through new MediaPlayer (), via Prepare */private void PlayMusic2 () {Stopcurrentmediaplaye R (); mmediaplayer = new MediaPlayer (); Idlemmediaplayer.setaudiostreamtype (audiomanager.stream_music); try {Mmediaplayer.setdatasource ( Getapplicationcontext (), Mmusicuri); Mmediaplayer.prepare ();} catch (IllegalArgumentException e) {e.printstacktrace ();} catch (SeCurityexception e) {e.printstacktrace ()} catch (IllegalStateException e) {e.printstacktrace ();} catch (IOException e) { E.printstacktrace ();} Mmediaplayer.start ();} /** * Third Way, created through new MediaPlayer (), via Prepareasync */private void PlayMusic3 () {mmediaplayer = new MediaPlayer (); Mmediapla Yer.setaudiostreamtype (Audiomanager.stream_music); Mmediaplayer.setonpreparedlistener (new OnPreparedListener () {@ overridepublic void onprepared (MediaPlayer MediaPlayer) {Mediaplayer.start ();}}) ; try {Mmediaplayer.setdatasource (Getapplicationcontext (), Mmusicuri); Mmediaplayer.prepareasync ();//Asynchronous Load} catch ( IllegalArgumentException e) {e.printstacktrace (),} catch (SecurityException e) {e.printstacktrace ();} catch ( IllegalStateException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ()}} @Overrideprotected void OnDestroy () {stopcurrentmediaplayer (); Super.ondestroy ();} private void Stopcurrentmediaplayer () {if (Mmediaplayer! = null) {mmediaplayer.stop (); Mmediaplayer.release (); Mmediaplayer= null;}}}
The difference between the first and two or three is:
After new is the idle state, the Create is followed by the prepared state. This is why we do not need to manually call the prepare () method to change the state after calling create.
The first, second, and third differences are:
The first two are synchronous, because it involves the identification and decoding, such as IO time-consuming operation, easy to cause the main thread blockage. The third is asynchronous, which does not cause this problem and is recommended in this way.