Reputation: 13
I made an activity
that has an audio as a background music. When i add a skip button to move to another activity
the background music of my first activity was continuously playing. Here's my code, kindly check and post what should i add to my code. Thanks in advance!
public class pgone extends Activity {
protected boolean _active = true;
protected int _splashTime = 7000;
public void onAttachedToWindow() {
super.onAttachedToWindow();
Window window = getWindow();
window.setFormat(PixelFormat.RGBA_8888);
}
MediaPlayer audio;
MediaPlayer SLONE;
private long splashDelay = 6000;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pgone);
TimerTask task = new TimerTask()
{
public void run() {
Intent mainIntent = new Intent().setClass(pgone.this, pgtwo.class);
startActivity(mainIntent);
finish();
}
};
final Timer timer = new Timer();
timer.schedule(task, splashDelay);
audio = MediaPlayer.create(this,R.raw.storyaud);
audio.start();
SLONE = MediaPlayer.create(this,R.raw.sl1);
SLONE.start();
final MediaPlayer mp = MediaPlayer.create(this, R.raw.buttonbeep);
final Vibrator mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
Button skipButton = (Button)findViewById(R.id.skip);
skipButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent skipIntent = new Intent(pgone.this,choose.class);
startActivity(skipIntent);
mp.start();
mVibrator.vibrate(500);
finish();
timer.cancel();
timer.purge();
}
});
}
protected void exitByBackKey() {
AlertDialog alertbox = new AlertDialog.Builder(this)
.setMessage("Do you want to exit the game?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
})
.show();
}
}
Upvotes: 0
Views: 1763
Reputation: 2752
The easiest and most efficient way -
@Override
protected void onPause() {
super.onPause();
yoursMusicPlayerObject.release();
}
Exploit Activity life cycle's onPause phase when you jump to next activity .Just release the I/O resources under use which is yours MediaPlayer object here .
Upvotes: 0
Reputation: 22291
Please Write mp.stop()
mp.reset()
instead of mp.start()
on click event of skip button, and see below link for more information.
Media Player example of Playing Sounds
Simple Android Mp3 Media Player
Upvotes: 0
Reputation: 22537
You should stop the audio before moving to the next Activity. Try replacing mp.start() by mp.stop() here,
Button skipButton = (Button)findViewById(R.id.skip);
skipButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent skipIntent = new Intent(pgone.this,choose.class);
startActivity(skipIntent);
mp.stop();
mVibrator.vibrate(500);
finish();
timer.cancel();
timer.purge();
}
});
Upvotes: 1