The game sound effects are the music that appears when we play games, which is also a must-have part of every game. However, if the background music you make the game feels interrupted, we can use the getCurrentPosition() method to judge the offset of the sound playback. Actually, this is also very simple. As long as we set (initialize sound) and (load sound effect resources) in the code, everything else is similar to the code of the music player, such as starting and stopping. Let's not say much, let's take a look at how the sound effects are implemented in the code:
1. Sound volume
int streamVolume;
//Define SoundPool object private SoundPool soundPool;//Define the HASH table private HashMap soundPoolMap;/*Parameters: null * Returns: None. * Description: Initialize the sound system * Notes: none. ******************************************************************
2. Initialize soundPool
public void initSounds() { //Initialize the soundPool object. The first parameter is how many sound streams are allowed to play at the same time. The second parameter is the sound type and the third parameter is the quality of the sound. soundPool = new SoundPool(100, AudioManager.STREAM_MUSIC, 100);//Initialize the HASH table soundPoolMap = new HashMap();//Get the sound equipment and device volume AudioManager mgr = (AudioManager)(Context.AUDIO_SERVICE);streamVolume = (AudioManager.STREAM_MUSIC); } /*************************************************************************** * Function: loadSfx(); * Parameters: null * Returns: None. * Description: Loading sound effects resources * Notes: none. ******************************************************************
3. Loading
public void loadSfx(int raw, int ID) { //Load the sound effects in the resource to the specified ID (it will be appropriate to play when playing) (ID, (context, raw, ID));} /****************************************************************************** * Function: play(); * Parameters: sound: The ID of the sound effect to be played, loop: the number of loops * Returns: None. * Description: Play sound * Notes: none. ****************************************************************** public void play(int sound, int uLoop) { ((sound), streamVolume, streamVolume, 1, uLoop, 1f); }