Android multimedia SoundPool
I have learned before that MediaPlayer is used to play mobile phone music, but many of the prompts on mobile phones are not played using MediaPlayer, such as text message ringtones and notification ringtones, use SoundPool in android to play small audio files;
The following describes how to use SoundPool.
[1] set a button on the UI for playback.
[2] Get SoundPool
View the API and find that there are two ways to obtain the SoundPool based on different versions.
Used before version 21
SoundPool pool = new SoundPool (int maxStreams, int streamType, int srcQuality)
Versions later than 21: generate with Builder
[3] Call the load method to load audio
[4] call the play Method
Public final int play (int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate)
Parameter Introduction
Parameters
SoundID a soundID returned by the load () function
LeftVolume left volume value (range = 0.0 to 1.0) left channel
RightVolume right volume value (range = 0.0 to 1.0) right channel
Priority stream priority (0 = lowest priority) priority
Loop mode (0 = no loop,-1 = loop forever) loop or not
Rate playback rate (1.0 = normal playback, range 0.5 to 2.0)
Notes
If you have no sound, it takes time to load the audio. Do not put load and play together.
Below is the source code
Public class MainActivity extends Activity {private Button mButton; private SoundPool pool = null; private int id; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); mButton = (Button) findViewById (R. id. button_sound); // It must be placed outside because loading audio takes time, otherwise there will be no sound id = initSound (); mButton. setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {playSound () ;}}) ;}private void playSound () {// public final int play (int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate) // Parameters // soundID a soundID returned by the load () function // leftVolume left volume value (range = 0.0 to 1.0) left channel // rightVolume right volume value (range = 0.0 to 1.0) right channel // priority stream priority (0 = lowest priority) priority // loop mode (0 = no loop,-1 = loop forever) loop or not // rate playback rate (1.0 = normal playback, range 0.5 to 2.0) the returned speed pool. play (id, 1, 1, 0,-1, 1);} public int initSound () {if (Build. VERSION. SDK_INT> 21) {SoundPool. builder builder = new SoundPool. builder (); builder. setMaxStreams (2); AudioAttributes. builder builder1 = new AudioAttributes. builder (); builder1.setLegacyStreamType (AudioManager. STREAM_MUSIC); builder. setAudioAttributes (builder1.build (); pool = builder. build ();} else {// use SoundPool (int maxStreams, int streamType, int srcQuality) pool = new SoundPool (2, AudioManager. STREAM_MUSIC, 0);} return pool. load (getApplicationContext (), R. raw. outgoing, 1 );}}