Hello! First time to ask a question here at stackoverflow. Exciting! Haha.
We're developing an Android game and we play some background music for our intro (we have an Intro Activity) but we want it to continue playing to the next Activity, and perhaps be able to stop or play the music again from anywhere within the application.
What we're doing at the moment is play the bgm using MediaPlayer at our Intro Activity. However, we stop the music as soon as the user leaves that Activity. Do we have to use something like Services for this? Or is MediaPlayer/SoundPool enough? If anyone knows the answer, we'd gladly appreciate your sharing it with us. Thanks!
Select the Play button then refer to the Attributes panel. Set the id to 'playButton' and the onClick attribute to 'playSound'. Note Android Studio may not recognise the playSound value yet but we will resolve this shortly.
Open your Android Studio and create a new project. Create a new folder named "raw" in your Android project's "res" folder and place your audio file inside the "raw" folder. You can see the audio is now successfully added into your Android Studio project by viewing the "raw" subfolder under "res" folder.
You can also create a service which play music using mediaplayer as below.
Intent svc=new Intent(this, BackgroundSoundService.class); startService(svc); //OR stopService(svc);
public class BackgroundSoundService extends Service { private static final String TAG = null; MediaPlayer player; public IBinder onBind(Intent arg0) { return null; } @Override public void onCreate() { super.onCreate(); player = MediaPlayer.create(this, R.raw.idil); player.setLooping(true); // Set looping player.setVolume(100,100); } public int onStartCommand(Intent intent, int flags, int startId) { player.start(); return 1; } public void onStart(Intent intent, int startId) { // TODO } public IBinder onUnBind(Intent arg0) { // TODO Auto-generated method stub return null; } public void onStop() { } public void onPause() { } @Override public void onDestroy() { player.stop(); player.release(); } @Override public void onLowMemory() { } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With