MediaPlayer and threading cleanup before onBackPressed - android

I have a mediaplayer in my activity and with the mediaplayer I have a seekbar that I am updating via a thread handler. The way I run the thread handler is like so:
Runnable run = new Runnable() {
#Override
public void run() {
seekUpdation();
}
};
public void seekUpdation() {
if(mp.isPlaying()){
this.seekbar.setProgress(mp.getCurrentPosition());
this.seekHandler.postDelayed(run, 2);
}
}
I call this whenever the user hits the play button and then the seekbar keeps getting updated while the mediaplayer is in playing. SO this works great, but when I hit the Back button when the mediaplayer is playing I then get an illegalstateexception because I am doing the following:
#Override
public void onBackPressed(){
super.onBackPressed();
if (mr != null)
mr.release();
if (mp != null){
mp.pause();
mp.stop();
mp.release();
}
}
See I figured by pausing the mediaplayer this would trigger the thread to stop, but it hasn't worked. Does anyone have any other suggestions?

Related

Android Media player onClick issue

I'm using MediaPlayer for playing sounds onClick. Until the sound is finished the click event is not play the sound again. How can it play the sound again on click, when the sound is currently playing?
final MediaPlayer mistake = MediaPlayer.create(getActivity(), R.raw.mistake);
tv_mistake.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mistake.start();
}
});
You must create a new MediaPlayer object to play the sound again like so.
tv_mistake.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mistake != null) {
mistake.release();
mistake = MediaPlayer.create(getActivity(), R.raw.mistake);
}
mistake.start();
}
});
You can read more about MediaPlayer in the following links.
Also a quite similar question
MediaPlayer, MediaPlayer Tutorial, MediaPlayer Tutorial From Google
Most of the errors in MediaPlayer comes due to improper handling of different states of its object.
You should release MediaPlayer object after completing playback or before calling start() again.
It is also recommended that once a MediaPlayer object is no longer being used, call release() immediately so that resources used by the internal player engine associated with the MediaPlayer object can be released immediately.
Create a MediaPlayer object as:
Mediaplayer mediaPlayer = null;
And call playMistakeSound() on button click:
tv_mistake.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playMistakeSound()
}
});
Implement playMistakeSound() as:
void playMistakeSound() {
try {
// releases MediaPlayer object before calling create() again while previous is still playing
if (mediaPlayer != null){
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}
mediaPlayer = MediaPlayer.create(getActivity() /*Context*/, R.raw.mistake);
// this will release MediaPlayer as soon as it completes
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if (mp != null) {
mp.reset();
mp.release();
mediaPlayer = null;
}
}
});
mediaPlayer.start();
} catch (Exception e) {
// log exception and handle
e.printStackTrace();
}
}

Android How to delete MediaPlayer perfectly

I am trying to develop a simple test project that plays sound when I tap the button and stop automatically after a few minutes after playing the sound.
Here is a code snippet:
Code for playing:
if (mPlayer != null) mPlayer = null;
mPlayer = MediaPlayer.create(this, R.raw.shush_v2);
mPlayer.setLooping(true);
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
Code for stopping:
if(mPlayer != null && mPlayer.isPlaying()) {
mPlayer.stop();
mPlayer.reset();
mPlayer.release();
mPlayer = null;
}
But sometimes I can still hear two sounds playing after I've stopped the sound.
Have so ever seen this behaviour before?
You should clear your media player.
//example usage of clearing media player when its over.
ourSong.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
clearMediaPlayer(mp);
}
});
//You can use this to stop media player.
private void clearMediaPlayer(MediaPlayer mp){
if(mp!=null){
mp.stop();
mp.release();// this will clear memory
mp = null;
}
}
public class PlayerApp extends Activity {
Button btnStart;
MediaPlayer mediaPlayer = null;
// Use the handler to stop the Player, after specific time
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player_app);
btnStart = (Button)findViewById(R.id.btnStart);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
// Initialize Player and start it.
// Call the Handler same time.
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.test);
mediaPlayer.start();
startHandler();
}
});
}
private void startHandler()
{
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// if Player is not null, then Stop it and Reset Null.
if(mediaPlayer!=null)
{
mediaPlayer.stop();
mediaPlayer = null;
}
}
}, 2500);
}
}

How to set Android background music playing only one time

I am creating a game, I want to play a background music for one activity only(For main menu of game), my code shown below, The problem is that the music plays more than one time, I want to play the same music also when activity Resumes.
public class Menu extends Activity {
MediaPlayer mp
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
mp = MediaPlayer.create(Menu.this, R.raw.adalante);
if(!mp.isPlaying()) {
mp.start();
}
public void play(View ButtonClicked) {
mp.stop();
mp.release();
//mp = MediaPlayer.create(Menu.this, R.raw.l);
//mp.start();
goToActivity(Game.class);
}
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
//coins
coin.setText(data.getString("coin"));
mp = MediaPlayer.create(Menu.this, R.raw.adalante);
if(!mp.isPlaying()) {
mp.start();
}
//mps.release();
}
In your onResume don't initialise MediaPlayer again and again. It creates new instance every time when you come to onResume. So add a check in onResume like this :
#Override
protected void onResume() {
super.onResume();
if (mp==null)
mp=MediaPlayer.create(MainActivity.this,R.raw.adalante);
if (!mp.isPlaying())
mp.start();
}
and additionally add this for prevention to play when activity goes to onPause
#Override
protected void onPause() {
super.onPause();
mp.pause();
}

How to stop audio from playing when back button is pressed?

Hi all here is my code:
final ImageView imageView = (ImageView) findViewById(R.id.Image7);
imageView.setImageResource(mFullSizeIds[position]);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(Audio.this,mAudio[position]);
mp.start();
}
});
Now this code works fine to play the audio when the user taps the image, however when I want to exit this activity and go to a different activity, the audio track is still playing, even when I press the home key the audio is still playing. How can I prevent this from happening?
Is there a way to stop the track from playing when the user taps the image again or presses the back/home button?
Add
#Override
public void onBackPressed ()
{
if (mp != null)
mp.stop();
super.onBackPressed();
}
and
#Override
public void onPause ()
{
if (mp != null)
{
mp.pause();
mp.stop();
}
super.onPause();
}
Create an onStop in the activity and make mp a class variable although I always create/prefer media player helper class for this sort of stuff. Then call mp.stop()/pause on onStop.
private MediaPlayer mp = null;
#Override
public void onStop() {
super.onStop();
if (mp != null) {
mp.stop();
}
}
then you just create it with removing the MediaPlayer before mp:
mp = MediaPlayer.create(Audio.this,mAudio[position]);
Override the onBackPressed method, and stop your MediaPlayer object, which is mp.

Releasing consumed memory after using MediaPlayer

I'm developing an application containing 100s of sound effects.
after playing some of the sounds the application force closes. I understood that the problem would be consuming all the available space of the memory. I tried using Release() method but after this method is called I'm not able to play the sound again.
I also tried using onDestroy() method to set the object of the mediaplayer to null but since these kind of objects must be final I can't do this.
What is your suggestion?
Here is my code:
final MediaPlayer mp1 = MediaPlayer.create(MainActivity.this, R.raw.a1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (i[0] == false)
{
mp1.start();
Toast.makeText(getBaseContext(), "horn", Toast.LENGTH_SHORT).show();
b1.setBackgroundResource(R.drawable.stop_button);
i[0] = true;
}
else
{
mp1.pause();
mp1.seekTo(0);
b1.setBackgroundResource(R.drawable.horn);
i[0] = false;
}
}
});
mp1.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
b1.setBackgroundResource(R.drawable.horn);
}
});
Have you tried something like this?
You can call release() in OnDestroy() method.
#Override
public void onDestroy(){
super.onDestroy();
mp.release();
}

Categories

Resources