开发者

Android MediaPlayer State Changes

开发者 https://www.devze.com 2023-03-13 21:47 出处:网络
I hope this isn\'t a dumb question, as I am rather new to Android, but I\'m having trouble handling the state changes with MediaPlayer. The mediaplayer works fine while on the screen, and it continues

I hope this isn't a dumb question, as I am rather new to Android, but I'm having trouble handling the state changes with MediaPlayer. The mediaplayer works fine while on the screen, and it continues to play the sound while the screen isn't visible, but when I return to the activity and try to stop the mediaplayer, it won't stop. I don't see anyway to get a streamID from mp, which I could save and restore on onPause and onResume. There 开发者_StackOverflow中文版must be something simple I'm missing. Here's some snippets of what I have so far:

    public class Noise extends Activity {
       public MediaPlayer mp;

     public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layour.main);

        Button startButton = (Button)findViewById(R.id.startButton);
        Button stopButton = (Button)findViewById(R.id.stopButton);

        mp = MediaPlayer.create(this, R.raw.noise);

        startButton.setOnClickListener(new OnClickListener(){
             @Override
             public void onClick(View v){
                 playSoundLoop();
                 }
               });

        stopButton.setOnClickListener(new OnClickListener(){
             @Override
             public void onClick(View v){
                 stopSound();
                 }
               });
       }

    public void playSoundLoop(){
         mp.setLooping(true);
         mp.start();
     }

    public void stopSound(){
         mp.pause();
         //Had originally tried mp.stop, mp.reset, mp.prepare, but that didn't work any better
     }

}


I don't think you're deallocating the original MediaPlayer instance. So, when you leave the activity and return, onCreate() is called again, and you end up with two instances until memory pressure causes the old one to get released.

The simple solution is release it when your activity leaves the foreground, eg:

@Override
    onPause() {
    mp.release();
    super.onPause();
}

However, if you want your music to continue playing in the background, you need to move the MediaPlayer reference somewhere outside the Activity lifecycle - probably into a service.

0

精彩评论

暂无评论...
验证码 换一张
取 消