Playing Sound in Android

Source: Internet
Author: User
Tags sendmsg

In the Android system, there are two ways to play sound, one is through MediaPlayer, and the other is through SoundPool. The former is mainly used to play music for a long period of time, while the latter is used to play sound effects for a short period of time, such as the key tone. Its advantage is that the resource usage is small and multiple sound clips can be loaded at the same time, then select play as needed. The following two methods are described respectively:

1. MediaPlayer

MediaPlayer can be created in either of the following ways:

MediaPlayer mp = new MediaPlayer()
To create a MediaPlayer object in this way, you must use the following statement after creating the object:
mp.setDataSource("filePath");mp.prepare();
Then, call the start () method. Note that you need to use this method to set the path for playing the music, which is not convenient for general applications and cannot be directly packaged into the apk.
Method 2:
mp = MediaPlayer.create(this, R.raw.music);
To create a MediaPlayer object in this way, you don't need to set datasource () and prepare (). Just start.

When you need to stop playing music, use the following method:

if(mp.isPlaying()){mp.stop();}mp.reset();
It should be noted that you must ensure that the mp is playing before stopping, because if the playing has been stopped, stopping again will cause an error because the MediaPlayer has a strict lifecycle, if you call an incorrect method during an incorrect period, an error is always reported.

2. SoundPool

SoundPool is particularly useful when playing sound effects. Why? Because it can load more sound fragments at a time. The following describes the basic usage:

// Create SoundPool sp = new SoundPool (10, StreamType. MUSIC, 5); // load soundPoolMap = new HashMap
 
  
(); SoundPoolMap. put (0, soundPool. load (context, R. raw. sound1, 1); // play the soundPool. play (soundPoolMap. get (0), 1, 1, 0, 0, 1 );
 
The specific meanings of parameters in each function are not important. We will not introduce them here. You can check them yourself. If you do this directly in the main thread, it is very likely that an error (Sample X Not Ready) will be reported. Why?

Originally, SoundPool. the load () function returns immediately. That is to say, this function will return no matter whether it is loaded or not. However, it is very likely that the sound has not been loaded yet. What should I do? In fact, after the load is complete, the system will send a broadcast before playing the video. Because this is a time-consuming operation, it is best to create a new thread for implementation. The following is my Implementation Scheme:

Handler handler; static SoundPool soundPool; static HashMap
 
  
SoundPoolMap; String TAG = "wtianok"; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); if (savedInstanceState = null) {getSupportFragmentManager (). beginTransaction (). add (R. id. container, new PlaceholderFragment ()). commit ();} soundPool = new SoundPool (10, AudioManager. STREAM_MUSIC, 5); soundPoolMap = new HashMap
  
   
(); // Load soundPoolnew LoadSoundPoolThread (). run (this); handler = new Handler () {public void handleMessage (android. OS. message msg) {if (msg. what = MessageType. SOUND_POOL_READY.ordinal () {Log. d (TAG, "finish load message received ed"); // do somethind }}} private class LoadSoundPoolThread extends Thread {public void run (Context context) {Log. d (TAG, "start to load soundpool"); soundPool. setOnLoadCompleteListener (new MyOnLoadCompleteListener (); soundPool. load (context, R. raw. sound1, 1); soundPool. load (context, R. raw. sound2, 1); soundPool. load (context, R. raw. sound3, 1); soundPool. load (context, R. raw. sound4, 1); soundPool. load (context, R. raw. sound5, 1); soundPool. load (context, R. raw. sound6, 1); soundPool. load (context, R. raw. sound7, 1);} private class MyOnLoadCompleteListener implementsOnLoadCompleteListener {int count = 1; @ Overridepublic void onLoadComplete (SoundPool soundPool, int sampleId, int status) {// note the parameter Log here. d (TAG, "load" + count + "sound"); soundPoolMap. put (count, sampleId); if (count = 7) {Log. d (TAG, "finish load soundpool"); MainActivity. soundPool = soundPool; sendMsg (MessageType. SOUND_POOL_READY); count = 1;} count ++ ;}} private void sendMsg (MessageType micTestStartRecord) {Message message Message = Message. obtain (); message. what = micTestStartRecord. ordinal (); handler. sendMessage (message );}
  
 

Note that after loading is completed, I use the following sentence:
MainActivity.soundPool = soundPool;
If this sentence is Not added, the Sample X Not Ready error will still be reported when I play the main thread. If I call play after receiving the broadcast, there is no problem. It is found that in the onLoadComplete () function that receives the broadcast, the local parameter soundPool of the function is actually called, rather than the global soundPool, but from the code point of view, if the global soundPool is called during load, why can't the global soundPool be used for playing? I still haven't figured it out yet, but the project still has to be continued. I have to add the above sentence and assign a value to the global soundPool. It turns out that this can be done.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.