Soundpool
A sound playing auxiliary class, from the name can be seen, it has the ability to "pool", it first loads the sound file into memory to support multiple playback of the sound file.
Characteristics
- Soundpool for short sound files
- Soundpool is suitable for playing "sounds that need to be played multiple times", such as in some commonly used please log in, please click on something
- Consumes less resources compared to MediaPlayer
- Supports simultaneous playback of multiple sounds
How to use
Create an instance
New Soundpool (1, audiomanager.stream_alarm, 0);
Soundpoolmap = new Hashmap<integer, integer> (); Here I create a hash table to record the ID of the loaded sound, in general we will define a constant as the key to retrieve the sound
Loading sound files
Soundpoolmap.put (KEY_SOUND_A1, Msoundpool.load (This, r.raw.a1, 1)); Soundpoolmap.put (KEY_SOUND_A2, Msoundpool.load (This, r.raw.a2, 1));//Note that the hash table here is recorded
play a sound file
Note that the specific ID is removed from the hash table here.
register a listener and get a message when the sound is loaded
Msoundpool.setonloadcompletelistener (new Soundpool.onloadcompletelistener () { @Override publicvoidintint status) { alert ("" + SampleID); } });
Finally, the code for the complete class, the sample code can be downloaded on my github: Https://github.com/vir56k/demo/tree/master/SoundPoolDemo
PackageDemo.vir56k.soundpooldemo;ImportAndroid.media.AudioManager;ImportAndroid.media.SoundPool;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.util.Log;ImportAndroid.view.View;ImportJava.util.HashMap; Public classMainactivityextendsappcompatactivity { Public Static Final intKEY_SOUND_A1 = 1; Public Static Final intKEY_SOUND_A2 = 1; Soundpool Msoundpool; PrivateHashmap<integer, integer>Soundpoolmap; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Msoundpool=NewSoundpool (1, audiomanager.stream_alarm, 0); Msoundpool.setonloadcompletelistener (NewSoundpool.onloadcompletelistener () {@Override Public voidOnloadcomplete (Soundpool Soundpool,intSampleID,intstatus) {Alert (" " +SampleID); } }); Soundpoolmap=NewHashmap<integer, integer>(); Soundpoolmap.put (KEY_SOUND_A1, Msoundpool.load ( This, R.RAW.A1, 1)); Soundpoolmap.put (KEY_SOUND_A2, Msoundpool.load ( This, R.RAW.A2, 1)); } Private voidalert (String s) {log.i ("Alert:", S + ""); } Public voidOnclickview (view view) {if(View.getid () = =R.id.button) {msoundpool.play (Soundpoolmap.get (KEY_SOUND_A1),1, 1, 0, 0, 1); } if(View.getid () = =r.id.button2) {msoundpool.play (Soundpoolmap.get (KEY_SOUND_A2),1, 1, 0, 0, 1); } }}
Android Development (44) using Soundpool to play the beep