Skip to content Skip to sidebar Skip to footer

How To Play Audio Continuously While Orientation Changes In Android?

I'm new to Android and I have to create MediaPlayer for playing the audio music. When start my activity song starts playing. But when I change the orientation on my emulator screen

Solution 1:

Simplest Answer for this question.

@OverrideprotectedvoidonSaveInstanceState(Bundle outState) 
{
    outState.putInt("possition", mpbg.getCurrentPosition());
    mpbg.pause();
    super.onSaveInstanceState(outState);
}

@OverrideprotectedvoidonRestoreInstanceState(Bundle savedInstanceState) 
{
    int pos = savedInstanceState.getInt("possition");
    mpbg.seekTo(pos);
    super.onRestoreInstanceState(savedInstanceState);
}

Solution 2:

When we declare mediaplayer as a static variable then only one instance of mp will exist. Suppose our Activity orientation changes now, Everything will be recreated on orientation change but Mp variable will not be recreated because of static property. In this way we just make a condition

if(mp!=null && !mp.isPlaying()){ 
    mp = MediaPlayer.create(getApplicationContext(), R.raw.subhanallah);
    playMusic(); 
} 

in our onCreate() method, this will check whether music is already playing or not, if its playing then if condition will not allow application to start music player again. and if Music is not playing then if condition will allow the application to restart the music.


Here is your update code:

publicclassAudio_ActivityextendsActivity {


staticMediaPlayer mp = null;


    publicvoidonCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        if(isLaunched)
        {
            setContentView(R.layout.audio);
        }

        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        length = settings.getInt("TheOffset", 0);
        init();
        prefs = PreferenceManager.getDefaultSharedPreferences(this);
        if(mp == null) 
        {
            initializeMP();
        }
        if(!mp.isPlaying())
        {
             playMusic();
        }

        mp.setOnCompletionListener(newOnCompletionListener() 
        {

            @OverridepublicvoidonCompletion(MediaPlayer arg0) 
            {
                // TODO Auto-generated method stub

            }
        });


    }

    privatevoidplayMusic() 
    {
        httpGetAsynchTask httpGetAsyncTask = newhttpGetAsynchTask();
        httpGetAsyncTask.execute();
    }

    publicvoidinitializeMP()
    {
          mp = MediaPlayer.create(getApplicationContext(), R.raw.subhanallah);

    }

    classhttpGetAsynchTaskextendsAsyncTask<String,Integer, Void>
    {

        protectedvoidonPreExdcute()
        {

        }

        @OverrideprotectedVoiddoInBackground(String... arg0)
        {
            // TODO Auto-generated method stub

            final SharedPreferences.Editor prefsEdit = prefs.edit();

            Log.e("Song is playing", "in  Mediya Player ");

            if(mp == null)
            {
                initializeMP()
            }
            mp.setLooping(false);
            mp.start();
            int millisecond=mp.getDuration();
            Log.e("Song is playing", "in  Mediya Player " + millisecond);

            prefsEdit.putBoolean("mediaplaying", true);
            prefsEdit.commit();
            //btnChapter.setEnabled(false);returnnull;

        }

        protectedvoidonPostExecute(Void result)
        {
            super.onPostExecute(result);
            btnChapter.setEnabled(false);
        }

    }

    @OverridepublicvoidonConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        Configuration config=getResources().getConfiguration();
        if(config.orientation == Configuration.ORIENTATION_PORTRAIT)
        {
            setContentView(R.layout.audio);
        }
        elseif(config.orientation == Configuration.ORIENTATION_LANDSCAPE)
        {
            setContentView(R.layout.audio);
        }
    }

    @OverridepublicvoidonPause() {
        super.onPause();


        SharedPreferences.Editor prefsEdit = prefs.edit();
        boolean isPlaying = prefs.getBoolean("mediaplaying", false);
        if (isPlaying)
        {
            if(mp!=null)
            {
                 mp.pause();
            }
            int position = mp.getCurrentPosition();
            Log.e("Current ", "Position -> " + position);
            prefsEdit.putInt("mediaPosition", position);
            prefsEdit.commit();
        }
    }

    @OverrideprotectedvoidonResume() {

        super.onResume();
        if(mp == null)
        {
            initializeMP();
        }
        mp.start();

        boolean isPlaying = prefs.getBoolean("mediaplaying", false);
        if (isPlaying) {
            int position = prefs.getInt("mediaPosition", 0);
            mp.seekTo(position);
            // mp.start();


        }
    } 

}

Solution 3:

For tasks like this you should use a Service since it won't be re-initialized when the orientation changes.

Solution 4:

publicvoidonSaveInstanceState(Bundle savedInstanceState) {

    super.onSaveInstanceState(savedInstanceState);

    savedInstanceState.putInt("Position", mediaPlayer.getCurrentPosition());
    savedInstanceState.putBoolean("isplaying", mediaPlayer.isPlaying());

     if (mediaPlayer.isPlaying())
          mediaPlayer.pause();

}


@OverridepublicvoidonRestoreInstanceState(Bundle savedInstanceState) {

    super.onRestoreInstanceState(savedInstanceState);

    position = savedInstanceState.getInt("Position");
    mediaPlayer.seekTo(position);
     if (savedInstanceState.getBoolean("isplaying"))
         mediaPlayer.start();



}

Solution 5:

So I wrestled with this for quite a time, but I finally figured it out. What you want to do is make your Mediaplayer a static member variable of the class, similar to the top answer here. However, the pitfall you want to avoid is using the "convenient" create() method. This actually creates a new instance of the mediaplayer every time it is called, even if it is static. What you want to do instead is something like this:

staticMediaPlayerm=newMediaPlayer();

Now wherever in your code you want to create the player, do something like this:

m.reset();

try{
        m.setDataSource(getApplicationContext(),Uri.parse("android.resource://com.example.app/" + R.raw.soundId));
        m.prepare();

}catch(java.io.IOException e){ }

m.seekTo(pos);
m.start();

The point of this is that create(), while convenient, is really only nice when you are not changing orientation ever, because it will keep creating new instances and quickly use up memory. Creating one static member and re-using it each time onCreate() is called is much cleaner and simpler. Reset() puts the player in the correct state for it to be re-used.

Post a Comment for "How To Play Audio Continuously While Orientation Changes In Android?"