Use of Soundpool in Android

Source: Internet
Author: User

We know that MediaPlayer occupies a lot of resources, and can not support playing multiple audio at the same time, so we have a kind of called soundpool, such as our common key tone or mobile phone tone, as well as we in the development of the game will have a lot of sound effects, etc. Below is a description of her usage:

The steps are as follows:

1. Create a Soundpool object

The source code is as follows

/**     *SoundPool源码中的构造方法方法体     *     * @param maxStreams 最多可以容纳多少个音频     * @param streamType 指定的声音类型,通过AudioManager类提供的常量进行指定     * @param srcQuality 指定音频的质量,默认为0     * @return a SoundPool object, or null if creation failed     */    publicSoundPool(intintint srcQuality)
2. Load the audio you want to play:
/**     * @param context the application context     * @param resId the resource ID     * @param priority the priority of the sound. Currently has no effect. Use     *                 a value of 1 for future compatibility.     * @return a sound ID. This value can be used to play or unload the sound.     */publicintloadintint priority);
3. Play Audio
 /** * Play a sound from a sound ID.       * @param Soundid The audio returned by the Load method * @param Leftvolume The Left channel volume * @param Rightvolume the right channel volume  * @param priority, the greater the value, the higher the priority * @param loop loop: 0 is not loop, 1 is the loop * @param Rate Specified rate, normal bit 1, status 0.5, maximum bit 2 * @return Non-zero streamid If successful, zero if failed * /     Public Final int Play(intSoundid,floatLeftvolume,floatRightvolume,intPriorityintLoopfloatrate);
4. The case is as follows:

(1) Layout file:

<?xml version= "1.0" encoding= "Utf-8"?><linearlayout xmlns:android="Http://schemas.android.com/apk/res/android"  Android:layout_width="Fill_parent"android:layout_height="Fill_parent" android:orientation="Horizontal" >                <button  android:id  = "@+id/button1"  android:layout_width  = "wrap_content"  android:layout_height  = "wrap_content"  android:text  = wind ringtone" />     <button  android:id  = "@+id/button2"  android:layout_width  = "wrap_content"  android:layout_height  = "wrap_content"  android:text  =" cuckoo cry "/>     <button  android:id  = "@+id/button3"  android:layout_width  = "wrap_content"  android:layout_height  = "wrap_content"  android:text  =" door ringtone "/>     <buttonandroid:id="@+id/button4"android:layout_width="Wrap_ Content "android:layout_height=" Wrap_content "android:text=" Phone sound " />                                 </linearlayout>

(2) Mainactivity.java file

 PackageCom.mingrisoft;ImportJava.util.HashMap;Importandroid.app.Activity;ImportAndroid.media.AudioManager;ImportAndroid.media.SoundPool;ImportAndroid.os.Bundle;ImportAndroid.view.KeyEvent;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button; Public  class mainactivity extends Activity {    PrivateSoundpool Soundpool;//Declare a Soundpool object    //Use HASHMAP to manage various audio    PrivateHashmap<integer, integer> soundmap =NewHashmap<integer, integer> ();//Create a HashMap object    @Override     Public void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.main); Button chimes = (Button) Findviewbyid (R.id.button1);//Get the "Wind ringtone" buttonButton Enter = (Button) Findviewbyid (R.id.button2);//Get "cuckoo cry" buttonbutton notify = (Button) Findviewbyid (R.id.button3);//Get the "door ringtone" buttonButton Ringout = (button) Findviewbyid (R.ID.BUTTON4);//Get the "Phone Sound" buttonSoundpool =NewSoundpool (5, Audiomanager.stream_system,0);//Create a Soundpool object that can hold 5 audio streams        //The audio stream to be played is saved to the HashMap objectSoundmap.put (1, Soundpool.load ( This, R.raw.chimes,1)); Soundmap.put (2, Soundpool.load ( This, R.raw.enter,1)); Soundmap.put (3, Soundpool.load ( This, R.raw.notify,1)); Soundmap.put (4, Soundpool.load ( This, R.raw.ringout,1)); Soundmap.put (5, Soundpool.load ( This, R.raw.ding,1));//Add click event Listener for each buttonChimes.setonclicklistener (NewOnclicklistener () {@Override             Public void OnClick(View v) {Soundpool.play (Soundmap.get (1),1,1,0,0,1);//Play the specified audio}        }); Enter.setonclicklistener (NewOnclicklistener () {@Override             Public void OnClick(View v) {Soundpool.play (Soundmap.get (2),1,1,0,0,1);//Play the specified audio}        }); Notify.setonclicklistener (NewOnclicklistener () {@Override             Public void OnClick(View v) {Soundpool.play (Soundmap.get (3),1,1,0,0,1);//Play the specified audio}        }); Ringout.setonclicklistener (NewOnclicklistener () {@Override             Public void OnClick(View v) {Soundpool.play (Soundmap.get (4),1,1,0,0,1);//Play the specified audioSoundpool.play (Soundpool.load (mainactivity. This, R.raw.notify,1),1,1,0,0,1);    }        }); }//overriding event that the key is pressed    @Override     Public Boolean OnKeyDown(intKeyCode, KeyEvent event) {Soundpool.play (Soundmap.get (5),1,1,0,0,1);//Play key tone        return true; }}

In addition, there are several small ringtones in the raw file in the resource file, which are no longer displayed.

The source code is as follows:

Use of Soundpool in Android

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.