Brief introduction:
There are two kinds of playing sound, one is soundpool and the other is MediaPlayer.
Sundpool is used to play short music, such as special effects in the game, key tones and so on.
MediaPlayer can play video and audio.
1. Using Soundpool
package com.shao;import android.app.activity;import android.media.audiomanager;import android.media.mediaplayer;import android.media.soundpool;import android.os.bundle;import android.view.view;import android.widget.button;public class mainactivity extends Activity {public soundpool soundpool;public button btnsoundpool;public button btnMediaPlay;public int x;public MediaPlayer mediaPlayer; @Overrideprotected Void oncreate (bundle savedinstancestate) {super.oncreate (savedinstancestate); SetContentView ( R.layout.activity_main); This.soundpool = new soundpool (1, audiomanager.stream_music, 0); Final int x = this.soundpool.load (this,r.raw.hacker, 1); this.btnSoundPool = (Button) findviewbyid (R.id.btnsoundpool); This.btnSoundPool.setOnClickListener (new View.onclicklistener () {@Overridepublic &NBSp;void onclick (view v) {soundpool.play (x, 1, 1, 0, 0, 0),}});}}
Attention
Final int x = This.soundPool.load (This,r.raw.hacker, 1);
You can see that the return is a soundid, and this soundid is used exactly when the Soundpool object invokes the playback method.
2. Using Mediaplay
package com.shao;import android.app.activity;import android.media.mediaplayer;import android.media.soundpool;import android.os.bundle;import android.view.view;import android.widget.button;public class Mainactivity extends activity {public button btnmediaplay;public mediaplayer mediaPlayer; @Overrideprotected void oncreate (bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);btnmediaplay = (Button) findviewbyid (R.id.btnmediaplay); Mediaplayer = mediaplayer.create (MainActivity.this, R.raw.hacker); This.btnMediaPlay.setOnClickListener (New view.onclicklistener () {@Overridepublic Void onclick (VIEW V) {try {mediaplayer.start ();} catch (throwable e) {e.printstacktrace ();} }});}}
There's nothing to note about this. Know just the following method, creating a MediaPlayer object can be
Mediaplayer.create (Mainactivity.this, R.raw.hacker);
And the call play method is not play, is start, this let me check for a long time.
Android Simple Play Audio