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();
}
}
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();
}
});
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
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 .
Related
I'm making a quiz app in which there is a sound game.But i find that sound keeps playing even when app is closed. Two time I'm using mediaplayer.
1.while clicking on image button.
2.on changing question.
Question is changed every 15 sec and after killing app sound is getting played every 15 seconds.
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.start();
}
});
btnA.setOnClickListener(this);
btnB.setOnClickListener(this);
btnC.setOnClickListener(this);
btnD.setOnClickListener(this);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
}
#Override
protected void onResume()
{
super.onResume();
questionPlay = db.getMorseQuestionMode(mode);
totalQuestion = questionPlay.size();
mCountDown = new CountDownTimer(TIMEOUT, INTERVAL) {
#Override
public void onTick(long millisUntilFinished) {
progressBar.setProgress(progressValue);
progressValue++;
}
#Override
public void onFinish() {
mCountDown.cancel();
showQuestion(++index);
}
};
showQuestion(index);
}
private void showQuestion(int index) {
if (index < totalQuestion) {
thisQuestion++;
txtQuestion.setText(String.format("%d/%d", thisQuestion, totalQuestion));
progressBar.setProgress(0);
progressValue = 0;
int QusId = this.getResources().getIdentifier(questionPlay.get(index).getQus().toString(), "raw", getPackageName());
btnA.setText(questionPlay.get(index).getAnswerA());
btnB.setText(questionPlay.get(index).getAnswerB());
btnC.setText(questionPlay.get(index).getAnswerC());
btnD.setText(questionPlay.get(index).getAnswerD());
mCountDown.start();
mediaPlayer= MediaPlayer.create(this,QusId);
mediaPlayer.start();
} else {
Intent intent = new Intent(this, Done.class);
Bundle dataSend = new Bundle();
dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL", totalQuestion);
dataSend.putInt("CORRECT", correctAnswer);
intent.putExtras(dataSend);
startActivity(intent);
finish();
}
}
#Override
public void onClick(View v) {
mCountDown.cancel();
if (index < totalQuestion) {
Button clickedButton = (Button) v;
if (clickedButton.getText().equals(questionPlay.get(index).getCorrectAnswer())) {
score += 10; // increase score
correctAnswer++; //increase correct answer
showQuestion(++index);
} else {
vibrator.vibrate(50);
showQuestion(++index); // If choose right , just go to next question
}
txtScore.setText(String.format("%d", score));
}
}
//CLicking back Button
public void onBackPressed() {
showExitAlertBox();
}
public void showExitAlertBox() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setMessage("You want to quit the play?");
//Yes Quit then go to category page
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int button) {
Intent intent = new Intent(getApplicationContext(), CategorySecond.class);
startActivity(intent);
}
});
//no Quit stay on same page
alertDialog.setNegativeButton("NO", null);
alertDialog.show();
mediaPlayer.stop();
}
}
Error Showing us below
W/MediaPlayer-JNI: MediaPlayer finalized without being released
Cancel your timer and stop mediaplayer if playing in onStop
#Override
public void onStop() {
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
if(mCountDown != null)
mCountDown.cancel();
super.onStop();
}
handle on destroy
#Override
public void onDestroy() {
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
if(mCountDown != null)
mCountDown.cancel();
}
You have not released the mediaplayer properly.
Use
protected void onStop(){
mediaPlayer.release();
mediaPlayer = null;
}
call this method where ever required.
i have 2 activities. and 2 different background music plays on both. when i press a button on the first activity it will go to this activity and the changing of music goes smoothly but i want to stop background music when back button is pressed. i tried this but it force closes. is there any other way to do this?
public class Categories extends Activity{
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.categories);
mp = MediaPlayer.create(Categories.this, R.raw.looney);
mp.setLooping(true);
mp.start();
Button cartoonButton = (Button) findViewById(R.id.cartoon);
cartoonButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent launchCartoon = new Intent(Categories.this, Cartoon.class);
startActivity(launchCartoon);
}
});
Button superButton = (Button) findViewById(R.id.hero);
superButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
Intent launchSuperheroes = new Intent(Categories.this, SuperHeroes.class);
startActivity(launchSuperheroes);
}
});
Button singerButton = (Button) findViewById(R.id.singer);
singerButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent launchSinger = new Intent(Categories.this, Singer.class);
startActivity(launchSinger);
}
});
Button famousButton = (Button) findViewById(R.id.famous);
famousButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent launchFamous = new Intent(Categories.this, Famous.class);
startActivity(launchFamous);
}
});
}
#Override
protected void onResume() {
super.onResume();
mp.start();
}
#Override
protected void onPause() {
super.onPause();
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}
You can try this code:
#Override
public void onBackPressed() {
if (player.isPlaying()) {
player.stop();
}
player.release();
super.onBackPressed();
}
Hope this help you :)
i am making a quiz game that has a background music.i saw a very helpful source code using service and background music here http://marakana.com/forums/android/examples/60.html but my problem is i want to add another sound on my EasyOne.class in my correct answer button. what will i add or edit to make it work. my point is. everytime i click the a button of my easyone.class it will play a sound and if i want to turn off all my music even the corrrect button and the background music it will turn off if ill go to my settings.class and click the OFF button. hope you can help me.really appriciate it.
here is my code for my service
public class MusicService extends Service {
private static final String TAG = "";
MediaPlayer player;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "ON", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
player = MediaPlayer.create(this, R.raw.bsound);
player.setLooping(false);
}
#Override
public void onDestroy() {
Toast.makeText(this, "OFF", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "ON", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player.start();
}
}
and here is my for my settings
public class Settings extends Activity implements OnClickListener {
private static final String TAG = "";
Button on, off, back;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
back = (Button) findViewById(R.id.btn_backk);
on = (Button) findViewById(R.id.btn_on);
off = (Button) findViewById(R.id.btn_off);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Back",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),MainMenu.class);
startActivity(intent);
}
});
on.setOnClickListener(this);
off.setOnClickListener(this);
}
public void onClick(View src) {
switch (src.getId()) {
case R.id.btn_on:
Log.d(TAG, "onClick: starting srvice");
startService(new Intent(this, MusicService.class));
break;
case R.id.btn_off:
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, MusicService.class));
break;
}
}
}
my EasyOne.class - (class of my level 1 easy mode)
public class EasyOne extends Activity {
ImageButton a, b, c;
Intent intent ;
CountDownTimer cdt;
TextView timer;
MediaPlayer clap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.easyone);
a = (ImageButton) findViewById(R.id.ib_a);
b = (ImageButton) findViewById(R.id.ib_b);
c = (ImageButton) findViewById(R.id.ib_c);
timer = (TextView) findViewById(R.id.tv_timer);
cdt = new CountDownTimer(5000,1000) {
#Override
public void onTick(long millisUntilFinished) {
timer.setText("seconds remaining: " + millisUntilFinished / 1000);
}
#Override
public void onFinish() {
timer.setText("TIMES UP!");
intent = new Intent(getApplicationContext(),TimesUp.class);
startActivity(intent);
}
};
intent = new Intent(getApplicationContext(),ChoiceTwo.class);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(intent);
//i want to add a sound here that will play if they click this button and can turn it OFF on the setting.class OFF button
cdt.cancel();
Intent intent = new Intent(getApplicationContext(),ChoiceTwo.class);
startActivity(intent);
}
});
cdt.start();
}
}
In the main activity of your code (where the game actually starts), put:
startService(new Intent(MusicService.class))
This will start your music playing as soon as the game starts
I'm having a bit of a trouble,, here's the gen. idea,, I have created an app a simple game-like application.. however the problem is when I try to click the button in the title screen it doesn't play the click sound.. can anyone please help me.. here's the code for my sound
public class Effects extends Activity implements MediaPlayer.OnCompletionListener {
Button mPlay;
MediaPlayer mPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPlay = (Button)findViewById(R.id.btnStart);
mPlay.setOnClickListener(playListener);
setContentView(R.layout.activity_main);
}
#Override
public void onDestroy() {
super.onDestroy();
if(mPlayer != null) {
mPlayer.release();
}
}
private View.OnClickListener playListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mPlayer == null) {
try {
mPlayer = MediaPlayer.create(Effects.this, R.raw.button11);
mPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
} else {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
}
};
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
}
}
and here's my code for the main java that I want the sound to be played when I clicked this button
public class Main extends Activity implements OnClickListener
{
Button about;
Button Quit;
Button start;
protected void onCreate(Bundle onSavedInstanceState) {
super.onCreate(onSavedInstanceState);
setContentView(R.layout.activity_main);
about = (Button)findViewById(R.id.btnAbout);
about.setOnClickListener(this);
Quit = (Button)findViewById(R.id.btnQuit);
Quit.setOnClickListener(this);
start = (Button)findViewById(R.id.btnStart);
start.setOnClickListener(this);
}
public void onClick(View argo)
{
if(argo.getId()==R.id.btnAbout)
{
Intent i = new Intent(this,About.class);
this.startActivity(i);
}
if(argo.getId()==R.id.btnQuit)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
if(argo.getId()==R.id.btnStart)
{
Intent start = new Intent(this,Howto.class);
this.startActivity(start);
Intent svc=new Intent(this,Effects.class);
startService(svc);
}
}
}
Use SoundPool to play your sounds: http://developer.android.com/reference/android/media/SoundPool.html you should init sounds in your onCreate() and then play them back in onClick()
And instead of doing thousands of pointless if(argo.getId()==R.id.btnQuit) (you should at least use else) get familiar with switch/case syntax)
I am trying to stop a media player and get out of my activity class whenever the stop option of the process dialog is pressed,but by using the below code i am able to getting out of my activity class but unable to stop the media player sound ,and it is running continuously till the thread stop..
Please help me on this matter
Thanx in advance..
public class Test_Service extends Activity {
private MediaPlayer mp;
private Thread welcomeThread;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mp = MediaPlayer.create(Test_Service.this,R.raw.alarm1);
welcomeThread=new Thread() {
int wait = 0;
#Override
public void run() {
try {
super.run();
while (wait <30000) {
mp.start();
sleep(3000);
wait +=3000;
}
} catch (Exception e) {
System.out.println("EXc=" + e);
} finally {
}
}
};
new AlertDialog.Builder(Test_Service.this)
.setTitle("Alarm is running")
.setPositiveButton("Stop",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mp.stop();
welcomeThread.stop();
Test_Service.this.finish();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mp.stop();
Test_Service.this.finish();
}
})
.create().show();
welcomeThread.start();
}
}
First of all, you should use a Handler with it's postDelayed() method to delay the start.
Furthermore you can set the following OnDismissListener on your AlertDialog and stop the player there to avoid code repetition.
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
mp.release();
handler.removeCallbacks(startingRunnable);
finish();
}
});
MediaPlayer.release() will stop your MediaPlayer and release it. If you want to reuse this MediaPlayer you will have to create a new one after calling release().