In-game sound effects, in-game sound effects
1. Real-time sound effects in the game:
In the game, the real-time sound effects played based on the situation are relatively short, can be repeated, or can be played at the same time. The MediaPlayer provided by Android occupies a large amount of system resources, and it also performs buffering during playback, resulting in high latency. Therefore, MediaPlayer cannot be used for instant sound playback. The SoundPool class provided by Android is mainly used to manage and play sound resources in applications. To use this class, you must first load the sound resources to the memory, then play the video where real-time sound effects are needed. There is almost no latency. [Because the SoundPool was designed to play real-time sound effects in the game without delay, in actual development, we should put only sound resources with a length less than 7 s into soundPool, otherwise, loading may fail or the memory usage is too large]
SoundPool class:
Public SoundPool (int maxSreams, int streamType, int srcQuality): Create a SoundPool object: maxStreams [this parameter is used to set the maximum number of sound effects to play simultaneously] streamType [this parameter sets the audio type, in the game, it is usually set to STREAM_MUSIC] srcQuality [this parameter sets the quality of the audio file, which has no specific effect yet. It is set to 0 (default)]
Public int load (Context context, int resId, int priority): rack audio file: context [this parameter is the application context] resId [this parameter is the ID of the Audio Resource to be loaded] priority [priority]
Public final int play (int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate): play Sound effect: soundID [this parameter is the audio ID to be played] leftVolume [used to control the left-channel volume] rightVolume [used to control the right-channel volume] priority [this parameter is a priority, 0 is the lowest] loop [this parameter is the number of audio loops, 0 is not a loop,-1 is a permanent loop] rate [this parameter is the playback speed of the sound, the value is 0.5 ~ 2.0f and 1.0f are normal speeds]
Public final void pause (int streamID): pause sound playback: streamID [ID of the sound to be paused]
Public final void stop (int streamID): stop Playing Sound: streamID [ID of the sound to be stopped]
Instance:
// Method for initializing the sound pool public void initialsnd () {// initialize the SoundPool object sp = new SoundPool (4, AudioManager. STREAM_MUSIC, 0); // initialize hashMaphm = new HashMap <Integer, Integer> (); // load the audio file ff, and set the sound number to 1 and put it in hm. put (1, sp. load (this, R. raw. ff, 1);} // play the public void playSound (int sound, int loop) {// obtain AudioManager reference AudioManager am = (AudioManager) this. getSystemService (Context. AUDIO_SERVICE); // obtain the current system volume float v1 = am. getStreamVolume (AudioManager. STREAM_MUSIC); // obtain the maximum volume of the system float v2 = am. getStreamMaxVolume (AudioManager. STREAM_MUSIC); // obtain the stream playback volume float v = v1/v2; // call the play method of SoundPool to play the file currentId = sp. play (hm. get (sound), v, v, 1, loop, 1.0f );}
2. Background music playback:
In the game, you can set the loop of SoundPool to-1 using a music segment of no greater than 7 s. However, in actual development, background sound effects are not particularly sensitive to latency, therefore, you can use MediaPlayer for playback of long sound effects.
2.1MediaPlayer claim period: the life cycle of a MediaPlayer includes 10 States. In each state, you can call corresponding methods to manage or play audio/video files.
<1> Idle State: When a MediaPlayer object is created using the new method or its reset method is called, The MediaPlayer object is in the idle state. Call getDuration and other methods in this state. If the reset method enters the idle state, OnErrorListener. onError is triggered, and the MediaPlayer object enters the Error state. Of course, the new method does not.
<2> End state: You can enter the End state through the release method. As long as the MediaPlayer object is no longer in use, it should be released through the release method as soon as possible, to release the occupied software and hardware resources, some of which are mutually exclusive. If the MediaPlayer enters the End state, it will not be in any other State.
<3> Initialized status: When MediaPlayer calls the setDataSource method, it enters the Initialized status, indicating that the file to be played is ready.
<4> Prepared status: After initialization, you must call the prepare or prepareAsync method for preparation. either of these two methods is synchronous or asynchronous. Only when the video enters the Prepared status indicates that MediaPlayer has been operating normally so far and can play music files.
<5> Preparing status: It mainly works with the prepareAsync asynchronous preparation method. If the asynchronous preparation is complete, OnPreparedListener. onPrepared is triggered, and then enters the Prepared status.
<6> Started status: After the MediaPlayer preparation is complete, it enters the Started status by calling the start method. The so-called Started status, that is, the playing status. In development, you can use the isPlaying method to test whether the MediaPlayer is in the Started status.
<7> Paused status: You can call the paused method in Started state to pause the playback and enter the Paused state. You can call the seekTo method when pausing a Media Player. The status of the Media Player remains unchanged.
<8> Stop status: You can call the stop method in either the Started or Paused status and enter the Stop status. If you want to play a stopped MediaPlayer, you must call the prepareAsync or prepare method to return to the previous Prepared status and start again.
<9> PlaybackCompleted status: The PlaybackCompleted status is displayed if the file is normal and loop playback is not set. The OnCompletion method in the OnCompletionListener interface is triggered. In this case, you can call the start method to play back the file from the beginning, or call the stop method to stop the playback, or call the seekTo method to locate the playback position.
<10> Error status: If a MediaPlayer Error occurs for some reason, the OnErrorListener. onError callback method is triggered, and the MediaPlayer enters the Error status. Timely capturing and properly handling of these errors can release related software and hardware resources and improve user experience. If the MediaPlayer enters the Error status, you can call the reset method to restore the status so that the MediaPlayer returns the Idle status again.
2.2MediaPlayer class:
First, you must call the getSystemService (Context. AUDIO_SERVICE) method of the Activity object to obtain the AudioManager object. Then, call the related method in the MediaPlayer class to control the volume.
Public void adjustVolume (int direction, int flags): You can call this method to adjust the volume. The direction parameter is the direction of adjustment. ADJUST_LOWER reduces the volume, ADJUST_RAISE increases the volume, and ADJUST_SAME keeps the volume unchanged. The flags parameter is set to 0.
Public int getStreamMaxVolume (int streamtype): gets the maximum volume of the system.
Public int getStreamVolume (int StreamType): gets the current volume of the system.
Void android. media. audioManager. setStreamVolume (int streamType, int index, int flags): You can call this method to set the volume. The streamType parameter is the sound type, and the index parameter is the index value of the audio to be set, the flags parameter is set to AudioManager. FLAG_PLAY_SOUND.
Package com. mycompany. myapp; import android. app. *; import android. OS. *; import android. view. *; import android. widget. *; import android. media. *; import android. content. *; import android. view. view. *; public class MainActivity extends Activity {MediaPlayer mp; AudioManager am; private int maxvolume; private int curvolume; private int stpvolume;/** Called when the activity is first created. * // @ Override publi C void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); mp = new MediaPlayer (); try {mp. setDataSource ("sdcard/kgmusic/download/One T-The Magic keypoints"); mp. prepare ();} catch (Exception e) {e. printStackTrace ();} am = (AudioManager) this. getSystemService (Context. AUDIO_SERVICE); maxvolume = am. getStreamMaxVolume (AudioManager. STREAM_MUSIC); stpvolume = Maxvolume/6; Button bstart = (Button) this. findViewById (R. id. playbtn); Button bpause = (Button) this. findViewById (R. id. pausebtn); Button bstop = (Button) this. findViewById (R. id. stopbtn); Button bincrease = (Button) this. findViewById (R. id. increasevolumebtn); Button breduce = (Button) this. findViewById (R. id. reducevolumebtn); bstart. setOnClickListener (new OnClickListener () {public void onClick (View v) {mp. start (); Toast. makeText (getBaseContext (), "Start playing", Toast. LENGTH_LONG ). show () ;}}); bpause. setOnClickListener (new OnClickListener () {public void onClick (View v) {mp. pause (); Toast. makeText (getBaseContext (), "pause playback", Toast. LENGTH_LONG ). show () ;}}); bstop. setOnClickListener (new OnClickListener () {public void onClick (View v) {mp. stop (); Toast. makeText (getBaseContext (), "Stop playing", Toast. LENGTH_LONG ). show () ;}}); binc Rease. setOnClickListener (new OnClickListener () {public void onClick (View v) {curvolume = am. getStreamVolume (AudioManager. STREAM_MUSIC); int tmpvolume = curvolume + stpvolume; am. setStreamVolume (AudioManager. STREAM_MUSIC, curvolume, AudioManager. FLAG_PLAY_SOUND); Toast. makeText (getBaseContext (), "increase volume", Toast. LENGTH_LONG ). show () ;}}); breduce. setOnClickListener (new OnClickListener () {public void onClick (Vie W v) {curvolume = am. getStreamVolume (AudioManager. STREAM_MUSIC); int tmpvolume = curvolume-stpvolume; curvolume = tmpvolume> 0? Tmpvolume: 0; am. setStreamVolume (AudioManager. STREAM_MUSIC, curvolume, AudioManager. FLAG_PLAY_SOUND); Toast. makeText (getBaseContext (), "volume reduction", Toast. LENGTH_LONG );}});}}