Search code examples
javaandroidandroid-layoutsoundpool

SoundPool Android not playing


Now the problem is, when I rotate the cellphone, the music starts again, how can I prevent that?

Actually I want to start the app in landscape view, and lock it that way.

here is the code:

package elfinha.app;

/**
 * Created by quest on 01/06/14.
 */

import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

   package testapps.emilyssong;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;


public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    MediaPlayer dontcallme = MediaPlayer.create(this, R.raw.dontcallmedarling);
    dontcallme.start();
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

Solution

  • @Override
       protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
         MediaPlayer dontcallme = MediaPlayer.create(this, R.raw.dontcallmedarling);
         dontcallme.start();
    }
    

    Your main problem is that the MediaPlayer is getting recreated when the device rotates. Locking it will fix that, but it's really just a bandaid because you don't understand the problem. If the music only plays once on open, you could set a variable that turns true on play and then won't play on rotation unless it false again.
    Up top.....

    boolean isPlaying=false;
    

    In the onCreate...

    if(!isPlaying){ 
         MediaPlayer dontcallme = MediaPlayer.create(this, R.raw.dontcallmedarling);
         dontcallme.start();
         isPlaying=true;}
    

    Then you could easily set up a listener to turn if false again once it's done or leaving.