如何停止或释放MediaPlayer?

时间:2011-12-05 09:49:10

标签: android android-mediaplayer

我正在使用MediaPlayer播放Mp3文件,但问题是MediaPlayer在后退按钮事件的Click事件上没有停止。以下是我的代码。

Java文件: -

public class Menu_Screen_Activity extends Activity implements OnClickListener {

    Button mBtnPlay, mBtnCredits, mBtnHowto, mBtnOptions;
    MediaPlayer mp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menu_screen);
        System.out.println("onCreate Called");
        mp = new MediaPlayer();
        mp = MediaPlayer.create(this, R.raw.mainthememusic_menuscreen);
        mp.start();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == event.KEYCODE_BACK) {
            System.out.println("Back is called...");
            mp.stop();
            mp.release();
            mp = null;
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}

1 个答案:

答案 0 :(得分:1)

添加setVolumeControlStream(AudioManager.STREAM_MUSIC);

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menu_screen);
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        System.out.println("onCreate Called");
        mp = new MediaPlayer();
        mp = MediaPlayer.create(this, R.raw.mainthememusic_menuscreen);
        mp.start();
    }