Play Music
MediaPlayer mediaPlayer = new MediaPlayer ();
If (mediaPlayer. isPlaying ()){
MediaPlayer. reset (); // reset to initial state
}
MediaPlayer. setDataSource ("/mnt/sdcard/god.mp3 ");
MediaPlayer. prepare ();
MediaPlayer. start (); // starts or resumes playback.
MediaPlayer. pause (); // pause playback
MediaPlayer. start (); // resumes playback.
MediaPlayer. stop (); // stop playing
MediaPlayer. release (); // release resources
MediaPlayer. setOnCompletionListener (new MediaPlayer. OnCompletionListener () {// broadcast completion event
@ Override public void onCompletion (MediaPlayer arg0 ){
MediaPlayer. release ();
}
});
MediaPlayer. setOnErrorListener (new MediaPlayer. OnErrorListener () {// error handling event
@ Override public boolean onError (MediaPlayer player, int arg1, int arg2 ){
MediaPlayer. release ();
Return false;
}
});
DEMO code for playing music: DemoActivity. java:
Package cn.itcast.mp3; import java. io. file; import android. app. activity; import android. media. mediaPlayer; import android. media. mediaPlayer. onCompletionListener; import android. media. mediaPlayer. onPreparedListener; import android. OS. bundle; import android. OS. handler; import android. OS. systemClock; import android. telephony. phoneStateListener; import android. telephony. telephonyManager; import android. view. view; Import android. view. view. onClickListener; import android. widget. button; import android. widget. chronometer; import android. widget. chronometer. onChronometerTickListener; import android. widget. editText; import android. widget. seekBar; import android. widget. seekBar. onSeekBarChangeListener; import android. widget. toast; public class DemoActivity extends Activity implements OnClickListener, OnChronometerTickListen Er, second {private EditText et_path; private Chronometer et_time; private SeekBar sb; private Button bt_play, bt_pause, bt_replay, bt_stop; private MediaPlayer mediaPlayer; private TelephonyManager manager;/*** subtime: click the interval from "resume" to "pause" and beginTime: Return to the bash value during playback. falgTime: The value when you click "play" * pauseTime: value of "Suspend" */private long subtime = 0, beginTime = 0, falgTime = 0, pauseTime = 0; @ Overridepublic v Oid onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); manager = (TelephonyManager) this. getSystemService (TELEPHONY_SERVICE); manager. listen (new MyListener (), PhoneStateListener. LISTEN_CALL_STATE); sb = (SeekBar) this. findViewById (R. id. sb); et_path = (EditText) this. findViewById (R. id. et_path); et_time = (Chronometer) this. findViewById (R. id. et_time); bt _ Play = (Button) this. findViewById (R. id. play); bt_pause = (Button) this. findViewById (R. id. pause); bt_replay = (Button) this. findViewById (R. id. replay); bt_stop = (Button) this. findViewById (R. id. stop); sb. setEnabled (false); sb. setOnSeekBarChangeListener (this); bt_play.setOnClickListener (this); listener (this); bt_replay.setOnClickListener (this); bt_stop.setOnClickListener (this); et_time.setO NChronometerTickListener (this);} Handler handler = new Handler (); Runnable updateThread = new Runnable () {public void run () {// obtain the current playing position of the Song and set it to the value of the playing progress bar if (mediaPlayer! = Null) {sb. setProgress (mediaPlayer. getCurrentPosition (); // start the thread handler every time with a delay of 100 milliseconds. postDelayed (updateThread, 100) ;}}; public void onClick (View v) {String path; try {switch (v. getId () {case R. id. play: falgTime = SystemClock. elapsedRealtime (); path = et_path.getText (). toString (). trim (); play (path); pauseTime = 0; et_time.setBase (falgTime); et_time.start (); break; case R. id. pause: pause (); break; case R. id. repla Y: if (mediaPlayer! = Null & mediaPlayer. isPlaying () {mediaPlayer. seekTo (0); et_time.setBase (SystemClock. elapsedRealtime (); et_time.start ();} else {path = et_path.getText (). toString (). trim (); play (path); et_time.setBase (SystemClock. elapsedRealtime (); et_time.start ();} if ("continued broadcast ". equals (bt_pause.getText (). toString (). trim () {bt_pause.setText ("pause");} falgTime = SystemClock. elapsedRealtime (); subtime = 0; break; case R. id. stop: If (mediaPlayer! = Null & mediaPlayer. isPlaying () {mediaPlayer. stop (); mediaPlayer = null; et_time.setBase (SystemClock. elapsedRealtime (); et_time.start (); et_time.stop (); bt_play.setEnabled (true); bt_play.setClickable (true);} falgTime = 0; subtime = 0; sb. setProgress (0); sb. setEnabled (false); break;} catch (Exception e) {e. printStackTrace (); Toast. makeText (getApplicationContext (), "file playback exception", 0 ). show () ;}} private void pause () {// Determine whether the music is playing if (mediaPlayer! = Null & mediaPlayer. isPlaying () {// pause the mediaPlayer of the music player. pause (); bt_pause.setText ("continued broadcast"); sb. setEnabled (false); et_time.stop (); pauseTime = SystemClock. elapsedRealtime (); // System. out. println ("1 pauseTime" + pauseTime);} else if (mediaPlayer! = Null & "continued broadcast ". equals (bt_pause.getText (). toString () {subtime + = SystemClock. elapsedRealtime ()-pauseTime; // System. out. println ("2 subtime:" + subtime); mediaPlayer. start (); bt_pause.setText ("pause"); sb. setEnabled (true); beginTime = falgTime + subtime; // System. out. println ("3 beginTime" + beginTime); et_time.setBase (beginTime); et_time.start () ;}}/*** play the music file at the specified address. mp3. wav. amr ** @ param path */private v Oid play (String path) throws Exception {if ("". equals (path) {Toast. makeText (getApplicationContext (), "path cannot be blank", 0 ). show (); return;} File file = new File (path); if (file. exists () {mediaPlayer = new MediaPlayer (); mediaPlayer. setDataSource (path); // mediaPlayer. prepare (); // c/c ++ player engine initialization // synchronization method // asynchronous mediaPlayer. prepareAsync (); // register mediaPlayer for the player. setOnPreparedListener (new OnPreparedListener () {pu Blic void onPrepared (MediaPlayer mp) {// TODO Auto-generated method stubmediaPlayer. start (); bt_play.setEnabled (false); bt_play.setClickable (false); sb. setMax (mediaPlayer. getDuration (); handler. post (updateThread); sb. setEnabled (true) ;}}); // register the listener event mediaPlayer after playing. setOnCompletionListener (new OnCompletionListener () {public void onCompletion (MediaPlayer mp) {mediaPlayer. release (); mediaPlayer = null; bt_p Lay. setEnabled (true); bt_play.setClickable (true); et_time.setBase (SystemClock. elapsedRealtime (); et_time.start (); et_time.stop (); sb. setProgress (0) ;}}) ;}else {Toast. makeText (getApplicationContext (), "file does not exist", 0 ). show (); return ;}} private class MyListener extends PhoneStateListener {@ Overridepublic void onCallStateChanged (int state, String incomingNumber) {super. onCallStateChanged (state, incomingNumber ); Switch (state) {case TelephonyManager. CALL_STATE_RINGING: // pause (); break; case TelephonyManager. CALL_STATE_IDLE: // play the pause (); break ;}}public void onChronometerTick (Chronometer chronometer) {} public void onProgressChanged (SeekBar seekBar, int progress, boolean fromUser) {// method stub automatically generated by TODO if (fromUser = true & mediaPlayer! = Null) {mediaPlayer. seekTo (progress); falgTime = SystemClock. elapsedRealtime (); beginTime = falgTime-sb. getProgress (); Progress (beginTime); et_time.start () ;}} public void onStartTrackingTouch (SeekBar seekBar) {// method stub automatically generated by TODO} public void onStopTrackingTouch (SeekBar seekBar) {// method stub automatically generated by TODO }}
Main. xml:
Play audio using SoundPool: In Android development, we often use MediaPlayer to play audio files. However, MediaPlayer has some shortcomings, such: high resource usage, long latency, and simultaneous playback of multiple audios are not supported. These disadvantages determine that MediaPlayer is not ideal in some scenarios, for example, in game development with relatively high time precision.
In game development, we often need to play some game sound effects (such as bullet explosion and object impact). These sound effects are characterized by short promotion, intensive, and low latency. In this scenario, we can use SoundPool instead of MediaPlayer to play these sound effects.
SoundPool (android. media. SoundPool) is called the sound pool. It is mainly used to play short sound clips and supports loading from program resources or file systems. Compared with MediaPlayer, SoundPool has the advantage of low CPU usage and low response latency. In addition, SoundPool also allows you to set parameters such as sound quality, volume, and playback ratio, and allows you to manage multiple audio streams by ID.
As we know, SoundPool has some Design Bugs. Some bugs have not been fixed since the firmware version 1.0. We should be careful when using them. I believe Google will fix these problems in the future, but we 'd better list them as follows:
1. SoundPool can only apply for a maximum of 1 MB of memory space, which means that we can only use some very short sound clips instead of playing songs or playing background music.
2. SoundPool provides pause and stop methods, but it is recommended that you do not use these methods easily, because sometimes they may cause your program to terminate inexplicably. We recommend that you do as much test work as possible when using these two methods. Some friends report that they do not stop playing the sound immediately, but stop playing the data in the buffer zone, it may take a second to play.
3. SoundPool efficiency issues. In fact, SoundPool efficiency is good in these playing classes, but some friends test it in G1 with a latency of about ms, which may affect the user experience. Maybe this does not care about SoundPool itself, because the latency in Droid with better performance is acceptable.
SoundPool has these defects at present, but it also has an irreplaceable advantage. Based on these, we recommend that you use SoundPool in the following scenarios: 1. audio Effect in the application (key tone, message, etc.) 2. intensive and transient sounds in the game (such as the simultaneous explosion of multiple ships)
Development steps:
1> Add a sound file to the res/raw directory of the project.
2> Create a SoundPool object, call SoundPool. load () to load the sound effect, and call SoundPool. play () to play the specified sound effect file.
Public class AudioActivity extends Activity {
Private SoundPool pool;
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
// The maximum number of audio streams in the specified sound pool is 10 and the sound quality is 5.
Pool = new SoundPool (10, AudioManager. STREAM_SYSTEM, 5 );
Final int sourceid = pool. load (this, R. raw. pj, 0); // load the audio stream and return the id in the pool
Button button = (Button) this. findViewById (R. id. button );
Button. setOnClickListener (new View. OnClickListener (){
Public void onClick (View v ){
// Play the audio. The second parameter is the left-channel volume. The third parameter is the right-channel volume. The fourth parameter is the priority. The fifth parameter is the number of cycles, and the value 0 is not the cycle, -1 loop. The sixth parameter is the speed. The lowest rate of 0.5 is. The highest speed is, which indicates the normal speed.
Pool. play (sourceid, 1, 1, 0,-1, 1 );
}
});
}
}
DEMO code for playing sound effects using SoundPool: DemoActivity. java:
Package cn. itcast. soundpool; import android. app. activity; import android. media. audioManager; import android. media. soundPool; import android. OS. bundle; import android. view. view; public class DemoActivity extends Activity {int soundid; SoundPool pool; @ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); pool = new SoundPool (5, AudioManager. STREAM_MUSIC, 0); // The code of this statement is an Asynchronous Operation soundid = pool. load (this, R. raw. ring, 1); // it takes some time} public void shoot (View view) {// It does not play back because the above asynchronous sound loading operation has not completed the pool. play (soundid, 1.0f, 1.0f, 0, 0, 1.0f); // taking tom }}