Play sound in Android

Source: Internet
Author: User
Tags sendmsg

In Android, there are two ways to play sound, one through MediaPlayer and the other through Soundpool. The former is mainly used for playing long-time music, while the latter is used to play a small segment of the sound effects, such as the key tone, the advantage is that the resource occupies a small, while being able to load multiple sound clips, and then choose to play as needed. These two approaches are described below:

1, MediaPlayer

There are two ways to create a MediaPlayer:

MediaPlayer MP = new MediaPlayer ()
To create a MediaPlayer object this way, you must use the following statement after the object is created:
Mp.setdatasource ("FilePath"); Mp.prepare ();
The start () method is then called. Note that using this method to set the playing music requires a path, which is not very convenient to use for general applications, and cannot be packaged directly into the APK.
Way two:
MP = Mediaplayer.create (this, r.raw.music);
Creating MediaPlayer objects in this way does not require setdatasource () and prepare (), and direct start () is fine.

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

if (mp.isplaying ()) {mp.stop ();} Mp.reset ();
It should be noted that before stop must confirm the MP is playing, because if it has stopped playing, again stop will throw an error, because MediaPlayer has a strict life cycle, in the wrong time to call the wrong method, is sure to error.

2, Soundpool

Soundpool is especially useful when playing sound, why? Because it can load more sound fragments at a time. Here's a basic way to use it first:

Create Soundpool sp = new Soundpool (Streamtype.music, 5);//Load Soundpoolmap = new Hashmap<integer, integer> (); Soundpoolmap.put (0, Soundpool.load (context, R.RAW.SOUND1, 1));//Play Soundpool.play (Soundpoolmap.get (0), 1, 1, 0, 0, 1);
The specific meaning of the parameters in each function is not the focus, here do not introduce, you go to check. What I would like to say is that if you do this directly in the main thread, you will probably get an error (Sample X isn't ready).

Originally, Soundpool.load () This function is returned immediately, that is, no matter if the load is not good, this function will return, but it is very likely that the sound has not been loaded into the end, what should be done? In fact, the system will send a broadcast after the load is completed before it can be played. And because it's a time-consuming operation, it's a good idea to create a new thread to implement. Here are my implementation scenarios:

Handler handler;static soundpool soundpool;static hashmap<integer, integer> 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 (Ten, Audiomanager.stream_music, 5); soundpoolmap = new Hashmap<integer, integer> ();// 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");//do somethind }}}}private class Loadsoundpoolthread extends Thread {public void Run (context context) {LOG.D (TAG, "start to load Soundpoo L "); 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 here the formal parameter log.d (TAG, "load" + Count + "sound"); Soundpoolma P.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.obtain (); message.what = Micteststartrecord.ordinal (); handler.sendmessage (message);}

It is important to note that after loading, I used the following sentence:
Mainactivity.soundpool = Soundpool;

If I do not add this, I will still report the sample X not-ready error when I play in the main thread, and it is no problem to call play after receiving the broadcast. Looking closely, it is found that in the Onloadcomplete () function of the receiving broadcast, the local parameter soundpool of the function is actually called, not the global Soundpool, but from the point of view of the code, the real global soundpool of the load is called, Then why not play with the global Soundpool? I still do not think, but the project still to continue, had to add the above sentence, the global Soundpool re-assignment, it turns out that this can be done.

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Today, I suddenly found out that the problem above is because I accidentally declared a local variable called Soundpool. So after changing the name, there is no need to use that sentence to assign a value.

Today also found that Soundpool can only load up to 7 segments of the voice, do not know if this is because I board the reason or Android itself is limited.

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.