Android MediaPlayer Stop and Play
Asked Answered
L

6

32

I'm creating Android application contains 2 buttons, on click on each button play a mp3 file. The problem is when I play button1 it plays sound1, when I click button2 it plays sound2.

I check on each button the other player if it's working and I stop it and play the clicked one

But If I click on same button twice it's keep first audio playing in the background and play another one again

I tried to check isPlaying() and to stop it, but it doesn't work!

I want If I click on button1 it play sound1 and if clicked on it again it stop it and play it again from beginning.

My code:

package com.hamoosh.playaudio;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class PlayaudioActivity extends Activity {
/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button b= (Button) findViewById(R.id.button1);
        Button b2= (Button) findViewById(R.id.button2);
        final TextView t= (TextView) findViewById(R.id.textView1);

        final MediaPlayer mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far);
        final MediaPlayer mp1 = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet);

        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mp1.isPlaying()) {

                    mp1.stop();
                }

                mp.start();
            }

        });

        b2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mp.isPlaying()) {

                    mp.stop();
                }
                mp1.start();
            }
        });
    }
}

Hope if there any better code that can use multiple buttons as an array or something to not check each button and player every time.

Lanner answered 4/9, 2012 at 15:15 Comment(0)
L
65

You should use only one mediaplayer object

    public class PlayaudioActivity extends Activity {

        private MediaPlayer mp;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            Button b = (Button) findViewById(R.id.button1);
            Button b2 = (Button) findViewById(R.id.button2);
            final TextView t = (TextView) findViewById(R.id.textView1);

            b.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    stopPlaying();
                    mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far);
                    mp.start();
                }

            });

            b2.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    stopPlaying();
                    mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet);
                    mp.start();
                }
            });
        }

        private void stopPlaying() {
            if (mp != null) {
                mp.stop();
                mp.release();
                mp = null;
           }
        }
    }
Limemann answered 4/9, 2012 at 15:25 Comment(3)
@mario I went crazy looking for a way to implement media player in my app and although a lot of people were helping or at least trying to help me but no success. Your did the trick. The only issue I have now is where to put the code, where/how to check if sound stopped playing. Once the sound stops playing I want to display a button. I Upvoted your answer.Continuance
@SiKni8 You have to ask a new question, can't answer it hereLimemann
In case it helps anyone, you need to figure out a way to create a single instance of Media Player class in order to prevent overlapping of audio. I achieved this by creating the MediaPlayer object in the Application instance of my android app.Polyanthus
L
9

To stop the Media Player without the risk of an Illegal State Exception, you must do

  try {
        mp.reset();
        mp.prepare();
        mp.stop();
        mp.release();
        mp=null;
       }
  catch (Exception e)
         {
           e.printStackTrace();
         }

rather than just

try {
       mp.stop();
       mp.release();
       mp=null;
    } 
catch (Exception e) 
    {
      e.printStackTrace();
    }
Leatrice answered 8/8, 2016 at 22:45 Comment(2)
I've had exceptions with calling stop() first but replacing it with your code, it now throws an IllegalStateException on reset() and prepare() as well. I also had a check for isPlaying before calling those methods but I've now removed them and only check whether mp is null. Is there any other check for mp before calling these methods?Hagiocracy
It crashes on the first line: mp.reset() -> IllegalStateExceptionHerl
M
5

According to the MediaPlayer life cycle, which you can view in the Android API guide, I think that you have to call reset() instead of stop(), and after that prepare again the media player (use only one) to play the sound from the beginning. Take also into account that the sound may have finished. So I would also recommend to implement setOnCompletionListener() to make sure that if you try to play again the sound it doesn't fail.

Malady answered 4/9, 2012 at 15:26 Comment(0)
W
1

I may have not got your answer correct, but you can try this:

public void MusicController(View view) throws IOException{
    switch (view.getId()){
        case R.id.play: mplayer.start();break;
        case R.id.pause: mplayer.pause(); break;
        case R.id.stop:
            if(mplayer.isPlaying()) {
                mplayer.stop();
                mplayer.prepare(); 
            }
            break;

    }// where mplayer is defined in  onCreate method}

as there is just one thread handling all, so stop() makes it die so we have to again prepare it If your intent is to start it again when your press start button(it throws IO Exception) Or for better understanding of MediaPlayer you can refer to Android Media Player

Wolenik answered 26/3, 2020 at 12:10 Comment(0)
A
0

just in case someone comes to this question, I have the easier version.

public static MediaPlayer mp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button b = (Button) findViewById(R.id.button);
        Button b2 = (Button) findViewById(R.id.button2);


        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mp = MediaPlayer.create(MainActivity.this, R.raw.game);
                mp.start();
            }
        });

        b2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mp.stop();
               // mp.start();
            }
        });
    }
Airborne answered 31/3, 2017 at 17:48 Comment(1)
start and stop on same button possibleAmaranth
P
0

In Kotlin

1- Upper Class add a variable:

var mpo: MediaPlayer? = null

2- In onCreate or a Function

mpo = MediaPlayer.create(this, R.raw.m7)
            mpo!!.start()

3- Add Stop under a control, onClick or any order:

if (mpo != null) {
                mpo!!.stop()
                mpo!!.release()
                mpo = null
        }

Note that for each player, need a separate stop!

Palimpsest answered 11/2, 2023 at 20:17 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.