In-game sound effects

Source: Internet
Author: User

1. Instant sound in the game:

In the game, the instant sound effects are short, repeatable, and can be played simultaneously, depending on the situation. Because the MediaPlayer available in Android consumes a lot of system resources and is buffered during playback, there is a greater delay, so using MediaPlayer does not enable instant audio playback. The Soundpool class, which is specifically provided in Android, is primarily used to manage and play the sound resources in the application, where it is necessary to first load the sound resources into memory, and then play them in the desired instant sound, with little delay. "Since the Soundpool design was designed to play instant sound in the game without delay, the actual development should only speak of a sound resource with a length of less than 7s in the Soundpool, or it might fail to load or take up too much memory"

Soundpool class:

Public Soundpool (int maxsreams, int streamtype, int srcquality): Create Soundpool object: maxstreams[This parameter sets the maximum number of simultaneous sound effects to play simultaneously] streamtype[This parameter to set the audio type, in the game is usually set to stream_music]srcquality[this parameter to set the quality of audio files, there is no specific role, set to 0 (default)]

public int Load (context context, int resId, int. priority): Shelves AH audio file: context[This parameter is the context of the application]resid[This parameter is the id]priority of the sound resource to be loaded [Priority]

Public final int Play (int soundid, float leftvolume, float rightvolume, int. priority, int loop, float rate): Play sound: soundid[ This parameter is the sound effect to play id]leftvolume[to control the left channel volume]rightvolume[to control the right channel volume]priority[The parameter is priority, 0 is the lowest]loop[the parameter is the number of loops of the sound, 0 is not loop, 1 is forever loop] rate[This parameter is the playback rate of the sound, which is at 0.5~2.0f,1.0f normal speed]

Public final void Pause (int streamid): Pause Sound Playback: streamid[The ID of the sound you want to pause]

Public final void Stop (int streamid): Stop playing sound: streamid[the ID of the sound you want to stop playing

Instance:

Method of initializing the sound pool public       void initialsnd ()       {               //Initialize 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 to 1th into HM in Hm.put (1,sp.load (this,r.raw.ff,1));} Sound play public void playSound (int sound,int loop)      {               //Get Audiomanager reference Audiomanager am= (Audiomanager) This.getsystemservice (context.audio_service);               Gets the current system volume float v1=am.getstreamvolume (audiomanager.stream_music);               Gets the system's maximum volume float v2=am.getstreammaxvolume (audiomanager.stream_music);                Calculated to get the playback volume float v=v1/v2;                Call Soundpool's Play method to play the file Currentid=sp.play (Hm.get (sound), v,v,1,loop,1.0f);}

2. Background music playback:

In the game, the background music can use a section of music less than 7s to set the Soundpool loop to 1, but in practice, background sound is not particularly sensitive to delay, so longer sounds can be played using MediaPlayer.

2.1MediaPlayer declaration period: The MediaPlayer lifecycle consists of 10 states, each of which can invoke the appropriate method 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 an idle state. In this state, call getduration and other methods, the reset method into the idle state will trigger Onerrorlistener.onerror, while mediaplayer the object into the error state, of course, the new method does not.

<2>end state: Through the Release method can enter the end state, as long as the MediaPlayer object is no longer used, it should be released through the release method as soon as possible to release the use of hardware and software resources, some of these resources are mutually exclusive. If MediaPlayer enters the end state, it will no longer be in any other state.

<3>initialized state: MediaPlayer calls the Setdatasource method into the initialized state, indicating that the file to be played is now equipped.

<4>prepared state: After initialization, it is also necessary to call the prepare or Prepareasync method for preparation, one of which is synchronous and asynchronous. Only enter the prepared state, only to indicate that MediaPlayer so far has been working normally, music files can be played.

<5>preparing state: Mainly with the Prepareasync asynchronous preparation method, if the asynchronous ready to complete, will trigger onpreparedlistener.onprepared, and then enter the prepared state.

<6>started state: After MediaPlayer is ready to complete, the started state is entered by calling the Start method. The so-called started state, which is the state in playback, can be used in development to test whether MediaPlayer is in started state using the IsPlaying method.

<7>paused Status: Started call paused method can pause playback to enter the paused state. The Seekto method can be called when the state is paused, when the state of this mediaplayer is unchanged.

<8>stop Status: Started status and paused state can call the Stop method and enter the stop state, if the stop state of the MediaPlayer to play back, You need to return to the previous prepared state by calling the Prepareasync or prepare method to start again.

<9>playbackcompleted Status: The file is played properly, and the loop is not set to enter the state, and will trigger the Oncompletion method in the Oncompletionlistener interface. You can call the Start method to play the file again from the beginning, or you can call the Stop method to stop playback, or call the Seekto method to reposition the playback position.

<10>error state: For some reason MediaPlayer error occurs, the Onerrorlistener.onerror callback method is triggered, and MediaPlayer will enter the error state. Capturing and handling these errors in a timely manner frees up related hardware and software resources, and can also improve the user experience. If MediaPlayer enters the error state, it can be restored by calling the Reset method, allowing MediaPlayer to return to the idle state again.

2.2MediaPlayer class:

First you need to call the Activity object's Getsystemservice (Context.audio_service) method to get the Audiomanager object. Then call the relevant methods in the MediaPlayer class for volume control.

public void Adjustvolume (int direction, int flags): Call this method to adjust the volume size. The parameter direction is the direction of the adjustment, adjust_lower decrease the volume, adjust_raise increase the volume, adjust_same keep the volume unchanged; The parameter flags is the flag, usually set to 0.

public int getstreammaxvolume (int streamtype): Gets the system maximum volume.

public int getstreamvolume (int streamtype): Gets the current volume of the system.

void Android.media.AudioManager.setStreamVolume (int streamtype, int index, INT flags): Call this method to set the volume size, The parameter streamtype is the type of sound, index is the indexed value of the audio to be set, the parameter flags is marked, and is usually set to Audiomanager.flag_play_sound.

 PackageCom.mycompany.myapp;Importandroid.app.*;Importandroid.os.*;Importandroid.view.*;Importandroid.widget.*;ImportAndroid.media.*;Importandroid.content.*;Importandroid.view.view.*; Public classMainactivityextendsactivity{MediaPlayer MP;    Audiomanager am; Private intMaxvolume; Private intCurvolume; Private intStpvolume; /**Called when the activity is first created.*/@Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.main); MP=NewMediaPlayer (); Try{Mp.setdatasource ("Sdcard/kgmusic/download/one t-the Magic Key.mp3");        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 (NewOnclicklistener () { Public voidOnClick (View v) {mp.start (); Toast.maketext (Getbasecontext (),"Start playing", Toast.length_long). Show ();        }        }); Bpause.setonclicklistener (NewOnclicklistener () { Public voidOnClick (View v) {mp.pause (); Toast.maketext (Getbasecontext (),"Pause Playback", Toast.length_long). Show ();        }        }); Bstop.setonclicklistener (NewOnclicklistener () { Public voidOnClick (View v) {mp.stop (); Toast.maketext (Getbasecontext (),"Stop playing", Toast.length_long). Show ();        }        }); Bincrease.setonclicklistener (NewOnclicklistener () { Public voidOnClick (View v) {Curvolume=Am.getstreamvolume (Audiomanager.stream_music); inttmpvolume=curvolume+Stpvolume;                Am.setstreamvolume (Audiomanager.stream_music,curvolume,audiomanager.flag_play_sound); Toast.maketext (Getbasecontext (),"Volume Increase", Toast.length_long). Show ();        }        }); Breduce.setonclicklistener (NewOnclicklistener () { Public voidOnClick (View v) {Curvolume=Am.getstreamvolume (Audiomanager.stream_music); inttmpvolume=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);    }        }); }}

In-game sound effects

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.