Shishir.bobby
Shishir.bobby

Reputation: 10984

How to play audio in splash screen in android

How to play an audio during splash screen. Guidance needed.

Upvotes: 1

Views: 9667

Answers (2)

Curtain
Curtain

Reputation: 1972

My way to do this (no external sound needed, since I put my soundfile in my resources-folder):

In onCreate:

mp = MediaPlayer.create(getBaseContext(), R.raw.sound); /*Gets your 
soundfile from res/raw/sound.ogg */
mp.start(); //Starts your sound

//Continue with your run/thread-code here

Remember to have the sound in .ogg-format; it's fully supported in Android.

An important thing below about handling the sound when the Splash Screen activity is stopped:

There are two general ways to manage the Splash Screen (and the sound inside it) when it's stopped:

  1. Destroy the whole activity:

    protected void onStop() {
      super.onStop();
    
      ur.removeCallbacks(myRunnable); /*If the application is stopped;
    remove the callback, so the next time the 
    application starts it shows the Splash Screen again, and also, so the
    thread-code,
    don't continue after the application has stopped */
    
      finish();
      onDestroy();
    }
    
  2. Or you can just stop the sound in onStop:

     protected void onStop() {
    super.onStop();
    if(mp.isPlaying()){ //Must check if it's playing, otherwise it may be a NPE
        mp.pause(); //Pauses the sound
        ur.removeCallbacks(myRunnable);
        }
    }
    

If you choose the second alternative you also have to start your Callback and MediaPlayer in the onStart-method.

I prefer the first alternative.

Upvotes: 7

Charles
Charles

Reputation: 2661

You can play audio files using the MediaPlayer class.

Example

MediaPlayer player = new MediaPlayer();
player.setDataSource("/sdcard/audiotrack.mp3");
player.prepare();
player.start();

Upvotes: 2

Related Questions