I manage to add background music to my apps, but when i close it, it doesn't stop. When I click on HOME, or BACK button, it still plays music. Does anyone knows how to solve that problem?
MediaPlayer bsound;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
MediaPlayer bsound = MediaPlayer.create(this, R.raw.sample);
bsound.setLooping(true); // Set looping
bsound.setVolume(100,100);
bsound.start();
TextView txt = (TextView) findViewById(R.id.textView1);
Typeface font = Typeface.createFromAsset(this.getAssets(), "Schalk.ttf");
txt.setTypeface(font);
TextView txt1 = (TextView) findViewById(R.id.button1);
Typeface font1 = Typeface.createFromAsset(this.getAssets(), "Schalk.ttf");
txt1.setTypeface(font1);
}
public void list(View view) {
Intent intent = new Intent(this, Menus.class);
startActivity(intent);
}
@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, menu);
return true;
}
Try to pause and resume MediaPlayer:
MediaPlayer bsound;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
bsound = MediaPlayer.create(this, R.raw.sample);
bsound.setLooping(true); // Set looping
bsound.setVolume(100, 100);
bsound.start();
TextView txt = (TextView) findViewById(R.id.textView1);
Typeface font = Typeface.createFromAsset(this.getAssets(), "Schalk.ttf");
txt.setTypeface(font);
TextView txt1 = (TextView) findViewById(R.id.button1);
Typeface font1 = Typeface.createFromAsset(this.getAssets(), "Schalk.ttf");
txt1.setTypeface(font1);
}
@Override
protected void onPause() {
if (bsound.isPlaying()) {
bsound.pause();
}
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
bsound.start();
}
And yes, you didn't initialize that MediaPlayer bsound field. Change this line:
MediaPlayer bsound = MediaPlayer.create(this, R.raw.sample);
to this:
bsound = MediaPlayer.create(this, R.raw.sample);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With