Games that lack background music and sound effects are incomplete.
First, two variables are defined, one for playing background music and the other for playing sound effects.
Private music mmusic; private sound msound;
The playing sound in andengine must be declared in the oncreateengineoptions () method first.
Final engineoptions = new engineoptions (true, screenorientation. portrait_fixed, new ratioresolutionpolicy (camera_width, camera_height), camera); // declareProgramTo use the background music engineoptions. getaudiooptions (). setneedsmusic (true); // declare that the program uses the sound effects engineoptions. getaudiooptions (). setneedssound (true );
Load music and sound effects Resources in the oncreateresources () method
Musicfactory. setassetbasepath ("mfx/"); try {This. mmusic = musicfactory. createmusicfromasset (this. mengine. getmusicmanager (), this, "lx.mp3"); this. mmusic. setlooping (true);} catch (final ioexception e) {debug. E (E);} soundfactory. setassetbasepath ("mfx/"); try {This. msound = soundfactory. createsoundfromasset (this. mengine. getsoundmanager (), this, "click.ogg");} catch (final ioexception e) {debug. E (E );}
I used music and sound effects in the click event on the screen.
Scene. Merge (New ionscenetouchlistener () {@ overridepublic Boolean onscenetouchevent (scene pscene, touchevent pscenetouchevent) {If (pscenetouchevent. isactionup () {If (! Mainactivity. this. mmusic. isplaying () {mainactivity. this. msound. play (); mainactivity. this. mmusic. play ();} else {mainactivity. this. mmusic. pause () ;}}return false ;}});
All files in MP3 and Ogg formats are supported.