How to stop mediaplayer when i click to leave the app? - java

I have started a sound in onCreate method meaning when I open the app the music starts playing. Then I have a button to stop the music and it's ok. But if I start the app then leave the app the music stills playing so I want to stop the music too when I click the back button to leave the app.
I have this code:
onCreate:
final MediaPlayer mp = MediaPlayer.create(this, R.raw.seconds);
mp.start();
Then onDestroy:
#Override
public void onDestroy()
{
// Don't forget to shutdown!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
mp.stop;
}
But in mp.stop; i have mp in red so isn't working.
If i try to put MediaPlayer mp outside onCreate then the mp.start; and mp.stop; mp turn blues and don't work too.
Any advice?

public class ExampleActivity extends Activity {
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//other codes
mp = MediaPlayer.create(this, R.raw.seconds);
mp.prepare();
mp.start();
}
protected void onDestroy() {
//other codes
mp.stop();
}
}
try to use like above..

You can play song using this function
public void playSong()
{
try
{
mp.reset();
mp.prepare();
mp.start();
}
catch (IllegalStateException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Then on destroy just release the player
#Override
public void onDestroy(){
super.onDestroy();
mp.release();
}

try this
private MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
///
mp = MediaPlayer.create(this, R.raw.seconds);
}
#Override
protected void onStop() {
if(mp.isPlaying()){
mp.stop();
}
super.onStop();
}

put following code in Activity's onStop() method so that when your activity goes in backstack or you leave the app, the music will be stopped.
#Override
protected void onStop()
{
if(mp != null && mp.isPlaying())
{
mp.stop();
mp.release();
mp = null;
}
super.onStop();
}

public class SampleMediaPlayer extends Activity {
private MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample_media_player); //your layout resource
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
mediaPlayer.release();
mediaPlayer = null;
}
}

Related

Need a sound to play every second if a button is toggled

I have a toggle button and i need the 'mp' sound to play every second if that button is toggled.The code below is what i tried and it does play the sound every second but the button stops responding so i can't turn it off.
ToggleButton btn = findViewById(R.id.button);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.beat);
btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
while (isChecked) {
mp.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thank you in advance.
Never use Thread.sleep(1000) it is the terrible thing you can do to the app. Your app is not
responsding because you are putting Main thread of app to sleep.
I have created this class for you for desmonstration. you can tweak is further to your needs.
private Handler soundHandler = new Handler();
private int delay = 1000;
private Runnable soundRunnable;
private MediaPlayer mediaPlayer;
private boolean isToggleChecked;
#Override protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ToggleButton toggleButton = findViewById(R.id.button);
mediaPlayer = MediaPlayer.create(this, R.raw.beat);
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked){
isToggleChecked = isChecked;
if(isChecked){
playSound();
}else {
stopSound();
}
}
});
}
#Override protected void onResume(){
super.onResume();
if(isToggleChecked){
playSound();
}
}
// this will make sure sound stops when app stops or goes in background
#Override
protected void onPause() {
soundHandler.removeCallbacks(soundRunnable);
super.onPause();
}
private void playSound(){
soundHandler.postDelayed(new Runnable() {
public void run() {
soundRunnable = this;
if(mediaPlayer != null) {
mediaPlayer.start();
}
soundHandler.postDelayed(soundRunnable, delay);
}
}, delay);
}
private void stopSound(){
if(mediaPlayer != null){
if(mediaPlayer.isPlaying()){
mediaPlayer.stop();
soundHandler.removeCallbacks(soundRunnable);
}
}
}
I found an answer to another question and modified it to fit my needs and now it works perfectly.Here is the solution/code.
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer = null;
int delayMillis;
Handler handler;
Runnable runnable;
private boolean isToggleChecked;
private ToggleButton toggleButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toggleButton = findViewById(R.id.button);
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
mediaPlayer.start();
}
};
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
isToggleChecked = true;
toggleMediaPlayer();
}
else {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer=null;
handler.removeCallbacks(runnable);
isToggleChecked = false;
}
}
});
}
#Override
public void onResume() {
super.onResume();
if (isToggleChecked) {
toggleButton.setChecked(true);
}
else {
toggleButton.setChecked(false);
}
}
private void toggleMediaPlayer(){
if(mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer=null;
handler.removeCallbacks(runnable);
}else{
mediaPlayer = MediaPlayer.create(this, R.raw.beat);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
delayMillis = 1000;
handler.postDelayed(runnable,delayMillis);
}
});
}
}
}

How to stop playing sounds on button click to start another sound file?

I have two buttons and two songs. If I click the first button, the first sound plays. But if I click the second button while the first sound is playing the second sound starts playing too.
How can I stop other sounds?
My code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer johnCenaPlayer = MediaPlayer.create(this, R.raw.john_cena);
Button johnCenaButton = (Button) findViewById(R.id.john_cena_button);
johnCenaButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
johnCenaPlayer.start();
}
});
final MediaPlayer haGayPlayer = MediaPlayer.create(this, R.id.ha_gay_button);
Button haGayButton = (Button) findViewById(R.id.ha_gay_button);
haGayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
haGayPlayer.start();
}
});
}
Stop the other MediaPlayer in clickListener using stop() method.
public void onClick(View view) {
ha_gay.stop()
john_cena.start();
}
If you have many audio files use a single MediaPlayer and change the sources dynamically.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer mediaPlayer = new MediaPlayer();
Button john_cena_button = (Button) findViewById(R.id.john_cena_button);
john_cena_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stopAndPlay(R.raw.john_cena, mediaPlayer);
}
});
Button ha_gay_button = (Button) findViewById(R.id.ha_gay_button);
ha_gay_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stopAndPlay(R.raw.ha_gay, mediaPlayer);
}
});
}
// This resets the mediaPlayer and starts the given audio
private void stopAndPlay(int rawId, MediaPlayer mediaPlayer) {
mediaPlayer.reset();
AssetFileDescriptor afd = this.getResources().openRawResourceFd(rawId);
try {
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
}
Try this one. Do it same for the other.
final MediaPlayer john_cena = MediaPlayer.create(this, R.raw.john_cena);
Button john_cena_button = (Button) findViewById(R.id.john_cena_button);
john_cena_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (he_gay.isPlaying()){
he_gay.stop();
}
else if (john_cena.isPlaying()){
john_cena.seekTo(0);
} else{
john_cena.start();
}
}
});

Android Studio MediaPlayer stops working after a while, why?

Hey I created a Soundboard with 200 Sounds but when I click a lot on the buttons the MediaPlayer stops working although I clean up the MediaPlayer.
Here is the code with only 2 Sounds:
public class MainActivity extends AppCompatActivity{
public MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//plays sound
public void sound1(View view){
cleanUpMediaPlayer();
mp = MediaPlayer.create(this, R.raw.sound1);
mp.start();
}
public void sound2(View view){
cleanUpMediaPlayer();
mp = MediaPlayer.create(this, R.raw.sound2);
mp.start();
}
public void cleanUpMediaPlayer(){
if(mp != null) {
if(mp.isPlaying()) {
try {
mp.reset();
mp.prepare();
mp.stop();
mp.release();
mp = null;
} catch (Exception e){
e.printStackTrace();
}
}
}
}
}
What is wrong with this Code? And why does my MediaPlayer stops working after approximately 80 clicks.

How to play, stop and pause working on media player instance in android ?

I want to develop media player type of application which has two button one for play and pause and one for stop. I take two image buttons in my layout file and reference it in Java file and code like this which I put here, but when I click on stop button audio is getting stopped but then I want replay audio file; but I cant play with play button.
my Java code below
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_aarti_fragment, container, false);
btnplay=(ImageButton)v.findViewById(R.id.btnplay);
btnstop=(ImageButton)v.findViewById(R.id.btnstop);
seekbar=(SeekBar)v.findViewById(R.id.seekbar);
mp = MediaPlayer.create(getActivity(), R.raw.arti);
btnstop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
btnplay.setImageResource(R.drawable.ic_action_play);
Toast.makeText(getActivity(), "Stop",Toast.LENGTH_LONG).show();
}
});
btnplay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying())
{
mp.pause();
btnplay.setImageResource(R.drawable.ic_action_play);
Toast.makeText(getActivity(), "Pause",Toast.LENGTH_SHORT).show();
}
else
{ btnplay.setImageResource(R.drawable.ic_action_pause);
mp.start();
Toast.makeText(getActivity(), "Play",Toast.LENGTH_SHORT).show();
}
}
});
return v;
}
Use This:
private BackgroundSound mBackgroundSound;
private MediaPlayer player;
public class BackgroundSound extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
player = MediaPlayer.create(HomePage.this, R.raw.background);
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float actualVolume = (float) audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
player.setLooping(true); // Set looping
player.setVolume(volume, volume);
player.start();
return null;
}
}
For Playing:
mBackgroundSound = new BackgroundSound();
mBackgroundSound.execute();
For Stop:
mBackgroundSound.cancel(true);
if (player != null) {
player.stop();
player.release();
}
For Pause:
if (player != null) {
player.pause();
}
Try this it will help you....
//Click Listener on Image Button with play and Pause method
PLAY.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Play-Pause();
}
});
//Play Pause method...........
public void Play-Pause(){
if (mediaPlayer.isPlaying()) {
PLAY.setImageResource(R.drawable.pause);
mediaPlayer.pause();
} else {
PLAY.setImageResource(R.drawable.play);
mediaPlayer.start();
}
}
Once a media player is stopped, you need to call prepare on it again to get it to a state where you can call start(). Look at the state diagram here http://developer.android.com/reference/android/media/MediaPlayer.html#pause%28%29
Check this code, its better and simple solution !
public class MainActivity extends AppCompatActivity {
MediaPlayer mp;
Switch sw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = MediaPlayer.create(this,R.raw.nokia);
sw = findViewById(R.id.sw);
sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mp.setLooping(true);
}
});
}
public void play(View v){
mp.start();
}
public void pause(View v){
if(mp.isPlaying())
mp.pause();
}
public void stop(View v){
if(mp.isPlaying()) {
boolean loop=mp.isLooping();
mp.stop();
mp = MediaPlayer.create(this, R.raw.nokia);
mp.setLooping(loop);
}
}
}

how to resume my audio in Android?

I have to implemented application for creating audio with the status of pause and resume and when my app as an when start the audio is start and when I press the back button on the emulator the audio music is on pause state but When my activity comes back to the foreground from the stopped state my audio music is not resumed. Here is my code.
public class Audio_Activity extends Activity
{
private MediaPlayer mp;
Button btnStartStop ;
Button btnChapter ;
Button btnOne;
Button btnTwo;
Button btnThree;
Button btnFour;
Button btnFive;
int length;
ImageView imgVw;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.audio);
init();
mp=MediaPlayer.create(Audio_Activity.this,R.raw.ennamo_yadho);
Log.e("Song is playing","in Mediya Player ");
if(mp!=null)
{
mp.setLooping(false);
mp.start();
btnChapter.setEnabled(false);
System.out.println("B4 button Click!!!!");
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
mp.stop();
mp.release();
btnChapter.setEnabled(true);
System.out.println("Music is over and Button is enable !!!!!!");
}
});
btnStartStop.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
if(mp.isPlaying())
{
if(mp!=null)
{
mp.pause();
}
}
else
{
// Resume song
if(mp!=null)
{
mp.start();
}
}
}
});
btnOne.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
imgVw.setImageResource(R.raw.chocklate);
}
}
);
btnTwo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
imgVw.setImageResource(R.raw.creame);
}
});
btnThree.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
imgVw.setImageResource(R.raw.schocklate);
}
});
btnFour.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
imgVw.setImageResource(R.raw.pinapple);
}
});
btnFive.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
imgVw.setImageResource(R.raw.strobery);
}
});
}
#Override
protected void onResume()
{
super.onResume();
System.out.println("Activity is Resume !!!");
}
#Override
protected void onStart()
{
super.onStart();
System.out.println("Activity is Started !!!");
}
#Override
protected void onRestart() {
super.onRestart();
System.out.println("Activity is Re-Started !!!");
if(mp.isPlaying())
{
if(mp!=null)
{
length=mp.getCurrentPosition();
mp.seekTo(length);
mp.start();
}
}
}
#Override
protected void onPause() {
super.onPause();
System.out.println("Activity is Pause!!!");
}
#Override
protected void onStop() {
super.onStop();
System.out.println("Activity is Stop !!!");
}
#Override
protected void onDestroy() {
super.onDestroy();
System.out.println("Activity is Destroyed !!!");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{ //Back key pressed
//Things to Do
if(mp!= null)
{
if(mp.isPlaying())
{
mp.pause();
//mp=null;
}
}
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
You should use android MediaPlaybackService for background play,Pause, stop or just open the activity by clicking the Notification. when click on back button it will bind a PendingIntent to with the button click event or buttons on the notification bar for controlling audio playbacks.
Use this Gist Code for AudioPlayer, try o use MediaPlaybackService class or try to reverse engineer this owncloud code.
Your code is not correct. You should not bother backbutton etc, but activity life cycle. You should pause your audio in onPause() and resume in onResume(). So move code to onPause() and get rid of onKeyDown() and move code from your onRestart() to onResume(). And remove all methods you do not need, line onDestroy(), onStart() etc

Categories

Resources