How does android implement SoundPool for playing sound effects in a short time?

Source: Internet
Author: User

Implementation Technology: android. media. SoundPool (manages and plays audio resources of applications and loads them directly to the memory ).

I. Basic Knowledge:

1. Create a SoundPool:

Let's take a look at the definition of the SoundPool function, as follows:

[Java]

Public SoundPool (

Int maxStream, // maximum number of streams simultaneously played

Int streamType, // stream type, which is generally STREAM_MUSIC

Int srcQuality // sampling rate conversion quality. No effect currently. Use 0 as the default value.

)

Public SoundPool (

Int maxStream, // maximum number of streams simultaneously played

Int streamType, // stream type, which is generally STREAM_MUSIC

Int srcQuality // sampling rate conversion quality. No effect currently. Use 0 as the default value.

) Eg.

SoundPool soundPool = new SoundPool (3, AudioManager. STREAM_MUSIC, 0 );

Creates a SoundPool that supports simultaneous playback of up to three streams and marks the type as music.

2. Load an audio file:

You can use either of the following methods:

[Java]

Int load (Context context, int resId, int priority) // load data from the APK Resource

Int load (FileDescriptor fd, long offset, long length, int priority) // load data from the FileDescriptor object

Int load (AssetFileDescriptor afd, int priority) // load data from the Asset object

Int load (String path, int priority) // load data from the complete file path

Int load (Context context, int resId, int priority) // load data from the APK Resource

Int load (FileDescriptor fd, long offset, long length, int priority) // load data from the FileDescriptor object

Int load (AssetFileDescriptor afd, int priority) // load data from the Asset object

Int load (String path, int priority) // load from the complete file path name. I currently use the first one, which is loaded from the APK Resource:

[Java]

Int load (

Context context, // the Context of the application, that is, the current Activity, which can be understood as who calls this method.

Int resId, // resource ID

Int priority // priority. Set this parameter to 1.

)

Int load (

Context context, // the Context of the application, that is, the current Activity, which can be understood as who calls this method.

Int resId, // resource ID

Int priority // priority. Set this parameter to 1.

)

3. Playback sound effects:

[Java]

Int play (

Int soundID, // the ID of the music to be played

Float leftVolume, // left audio volume

Float rightVolume, // right audio volume

Int priority, // priority, 0 is the lowest

Int loop, // number of cycles. 0 indicates no loop, and-1 indicates permanent loop.

Float rate // playback speed. The value ranges from 0.5 to 2.0, and 1 indicates the normal speed.

)

Int play (

Int soundID, // the ID of the music to be played

Float leftVolume, // left audio volume

Float rightVolume, // right audio volume

Int priority, // priority, 0 is the lowest

Int loop, // number of cycles. 0 indicates no loop, and-1 indicates permanent loop.

Float rate // playback speed. The value ranges from 0.5 to 2.0, and 1 indicates the normal speed.

)

4. Pause sound effects:

[Java]

Void pause (int streamID) // The parameter is the sound effect ID.

Void pause (int streamID) // The parameter is the sound effect ID.

Ii. Programming implementation:

1. Edit the interface (reslayoutmain. xml ):

[Java]

  

Android: orientation = "vertical"

Android: layout_width = "fill_parent"

Android: layout_height = "fill_parent"

>

  

Android: text = "Playing Sound 1"

Android: id = "@ + id/Button01"

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content">

  

  

Android: text = "playback sound 2"

Android: id = "@ + id/Button02"

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content">

  

  

Android: text = "Pause sound 1"

Android: id = "@ + id/Button1Pause"

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content">

  

  

Android: text = "Pause sound 2"

Android: id = "@ + id/Button2Pause"

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content">

  

  

  

Android: orientation = "vertical"

Android: layout_width = "fill_parent"

Android: layout_height = "fill_parent"

>

  

Android: text = "Playing Sound 1"

Android: id = "@ + id/Button01"

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content">

  

  

Android: text = "playback sound 2"

Android: id = "@ + id/Button02"

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content">

  

  

Android: text = "Pause sound 1"

Android: id = "@ + id/Button1Pause"

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content">

  

  

Android: text = "Pause sound 2"

Android: id = "@ + id/Button2Pause"

Android: layout_width = "fill_parent"

Android: layout_height = "wrap_content">

  

  

LinearLayout defines a linear layout of vertical (vertical direction.

In this layout, fill in four button controls, including the text, id, layout_width, and layout_height parameters.

The interface layout is as follows:

2. code editing (srcwyfzclMyActivity. java ):

[Java]

Package wyf. zcl;

Import java. util. HashMap; // introduce related packages

Import android. app. Activity;

Import android. media. AudioManager;

Import android. media. SoundPool;

Import android. OS. Bundle;

Import android. view. View;

Import android. widget. Button;

Import android. widget. Toast;

Public class MyActivity extends Activity {

/** Called when the activity is first created .*/

SoundPool sp; // gets a sound pool reference

HashMap spMap; // get a map reference

Button b1; // specifies the audio playback control Button.

Button b1Pause; // specifies the pause control Button.

Button b2; // audio playback control Button

Button b2Pause; // specifies the pause control Button.

@ Override

Public void onCreate (Bundle savedInstanceState ){

Super. onCreate (savedInstanceState );

SetContentView (R. layout. main );

InitSoundPool (); // initialize the sound pool

B1 = (Button) findViewById (R. id. Button01); // audio playback control Button instantiation

B2 = (Button) findViewById (R. id. Button02); // audio playback control Button instantiation

B1Pause = (Button) findViewById (R. id. Button1Pause );

B2Pause = (Button) findViewById (R. id. Button2Pause );

B1.setOnClickListener (new View. OnClickListener (){

@ Override

Public void onClick (View v ){

PlaySound (); // play the first sound effect, loop through it

Toast. makeText (MyActivity. this, "Playing Sound 1", Toast. LENGTH_SHORT). show ();

}});

B1Pause. setOnClickListener (new View. OnClickListener (){

@ Override

Public void onClick (View v ){

Sp. pause (spMap. get (1 ));

Toast. makeText (MyActivity. this, "Pause sound 1", Toast. LENGTH_SHORT). show ();

}});

B2.setOnClickListener (new View. OnClickListener (){

@ Override

Public void onClick (View v ){

PlaySound (); // play the second sound, loop it over

Toast. makeText (MyActivity. this, "Playing Sound 2", Toast. LENGTH_SHORT). show ();

}});

B2Pause. setOnClickListener (new View. OnClickListener (){

@ Override

Public void onClick (View v ){

Sp. pause (spMap. get (2 ));

Toast. makeText (MyActivity. this, "Pause sound 2", Toast. LENGTH_SHORT). show ();

}});

}

Public void initSoundPool () {// initialize the sound pool

Sp = new SoundPool (

5, // maxStreams parameter, which is used to set the number of sound effects that can be played at the same time

AudioManager. STREAM_MUSIC, // streamType parameter. This parameter sets the audio type, which is usually set to STREAM_MUSIC in games.

0 // srcQuality parameter, which sets the quality of the audio file. Currently, no effect is available. Set it to 0 as the default value.

);

SpMap = new HashMap ();

SpMap. put (1, sp. load (this, R. raw. attack02, 1 ));

SpMap. put (2, sp. load (this, R. raw. attack14, 1 ));

}

Public void playSound (int sound, int number) {// playback sound. The parameter sound is the id of the playback sound, and the parameter number is the number of playback sound effects.

AudioManager am = (AudioManager) this. getSystemService (this. AUDIO_SERVICE); // instantiate the AudioManager object

Float audioMaxVolumn = am. getStreamMaxVolume (AudioManager. STREAM_MUSIC); // returns the maximum volume of the current AudioManager object.

Float audioCurrentVolumn = am. getStreamVolume (AudioManager. STREAM_MUSIC); // return the volume of the current AudioManager object.

Float volumnRatio = audioCurrentVolumn/audioMaxVolumn;

Sp. play (

SpMap. get (sound), // the id of the music to be played

VolumnRatio, // left audio volume

VolumnRatio, // right-channel volume

1, // priority, 0 is the lowest

Number, // number of cycles. 0 indicates no loops, and-1 indicates no permanent loops.

1 // playback speed. The value ranges from 0.5 to 2.0. 1 indicates the normal speed.

);

}

}

Package wyf. zcl;

Import java. util. HashMap; // introduce related packages

Import android. app. Activity;

Import android. media. AudioManager;

Import android. media. SoundPool;

Import android. OS. Bundle;

Import android. view. View;

Import android. widget. Button;

Import android. widget. Toast;

Public class MyActivity extends Activity {

/** Called when the activity is first created .*/

SoundPool sp; // gets a sound pool reference

HashMap spMap; // get a map reference

Button b1; // specifies the audio playback control Button.

Button b1Pause; // specifies the pause control Button.

Button b2; // audio playback control Button

Button b2Pause; // specifies the pause control Button.

@ Override

Public void onCreate (Bundle savedInstanceState ){

Super. onCreate (savedInstanceState );

SetContentView (R. layout. main );

InitSoundPool (); // initialize the sound pool

B1 = (Button) findViewById (R. id. Button01); // audio playback control Button instantiation

B2 = (Button) findViewById (R. id. Button02); // audio playback control Button instantiation

B1Pause = (Button) findViewById (R. id. Button1Pause );

B2Pause = (Button) findViewById (R. id. Button2Pause );

B1.setOnClickListener (new View. OnClickListener (){

@ Override

Public void onClick (View v ){

PlaySound (); // play the first sound effect, loop through it

Toast. makeText (MyActivity. this, "Playing Sound 1", Toast. LENGTH_SHORT). show ();

}});

B1Pause. setOnClickListener (new View. OnClickListener (){

@ Override

Public void onClick (View v ){

Sp. pause (spMap. get (1 ));

Toast. makeText (MyActivity. this, "Pause sound 1", Toast. LENGTH_SHORT). show ();

}});

B2.setOnClickListener (new View. OnClickListener (){

@ Override

Public void onClick (View v ){

PlaySound (); // play the second sound, loop it over

Toast. makeText (MyActivity. this, "Playing Sound 2", Toast. LENGTH_SHORT). show ();

}});

B2Pause. setOnClickListener (new View. OnClickListener (){

@ Override

Public void onClick (View v ){

Sp. pause (spMap. get (2 ));

Toast. makeText (MyActivity. this, "Pause sound 2", Toast. LENGTH_SHORT). show ();

}});

}

Public void initSoundPool () {// initialize the sound pool

Sp = new SoundPool (

5, // maxStreams parameter, which is used to set the number of sound effects that can be played at the same time

AudioManager. STREAM_MUSIC, // streamType parameter. This parameter sets the audio type, which is usually set to STREAM_MUSIC in games.

0 // srcQuality parameter, which sets the quality of the audio file. Currently, no effect is available. Set it to 0 as the default value.

);

SpMap = new HashMap ();

SpMap. put (1, sp. load (this, R. raw. attack02, 1 ));

SpMap. put (2, sp. load (this, R. raw. attack14, 1 ));

}

Public void playSound (int sound, int number) {// playback sound. The parameter sound is the id of the playback sound, and the parameter number is the number of playback sound effects.

AudioManager am = (AudioManager) this. getSystemService (this. AUDIO_SERVICE); // instantiate the AudioManager object

Float audioMaxVolumn = am. getStreamMaxVolume (AudioManager. STREAM_MUSIC); // returns the maximum volume of the current AudioManager object.

Float audioCurrentVolumn = am. getStreamVolume (AudioManager. STREAM_MUSIC); // return the volume of the current AudioManager object.

Float volumnRatio = audioCurrentVolumn/audioMaxVolumn;

Sp. play (

SpMap. get (sound), // the id of the music to be played

VolumnRatio, // left audio volume

VolumnRatio, // right-channel volume

1, // priority, 0 is the lowest

Number, // number of cycles. 0 indicates no loops, and-1 indicates no permanent loops.

1 // playback speed. The value ranges from 0.5 to 2.0. 1 indicates the normal speed.

);

}

}

The first few imports are used to import related packages on which the program depends;

Then there is the Activity class, which is equivalent to registering the callback function of our interface. @ Override refers to the onCreate () function of the Activity. This method is called when MyActivity (that is, our window) is created.

The initSoundPool () function initializes the sound pool;

FindViewById instantiate the button control;

@ Override: the Key listening function setOnKeyListener ().

========================================================== ========================================================== ================

Eclipse display Line number: [Ctrl + F10] --> [Show Line Numbers]

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.