简体   繁体   中英

Android Studio: Start and Stop audio using mediaPlayer

How to start and stop playing the music using the same button. The code below will play the song multiple times (overlaping) if I click it repeatedly.

And another problem is where to insert starTimer and StopTimer function so the starTimer will active is the sound is not playing and stopTimer will active if the sound is playing.

Updated Code:

   public void playFile(View v) {
    if (mediaPlayer == null)
        mediaPlayer = new MediaPlayer();

    try {

        mediaPlayer.setDataSource(question.getAudio());

        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(@NotNull MediaPlayer mp) {
                mediaPlayer.start();
            }
        });
        mediaPlayer.prepareAsync();

    }catch (IOException e) {
        e.printStackTrace();
        stopSelf();
    }

    if (mediaPlayer.isPlaying()) {
        //pause music
        mediaPlayer.pause();
    } else {
        //play music
        mediaPlayer.start();
    }
}

Xml file:

<Button
    android:id="@+id/audQuestion"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Play"
    android:onClick="playFile"
    android:layout_centerInParent="true"/>

and for the startTimer stopTimer function

public void starTimer() {
    timer = new Timer(Constant.TIME_PER_QUESTION, Constant.COUNT_DOWN_TIMER);
    timer.start();
}

public void stopTimer() {
    if (timer != null)
        timer.cancel();
}

better you make one boolean values on button click then handling easily

isClick is false means if will execute other going else.else spot you make mediaplayer stop and timer stop function

boolean isClick=false;
public void playFile(View v){
    MediaPlayer mediaPlayer = new MediaPlayer(); if(!isClick){

    isClick=true;
        try {

            mediaPlayer.setDataSource(question.getAudio());

            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                     if( mediaPlayer.isPlaying() ) {
                     mediaPlayer.stop();}  mp.start();
                     starTimer();
                 }
             });
            mediaPlayer.prepareAsync();

        }catch (IOException e){
            e.printStackTrace();
            stopSelf();
        }

    }else{ 
        if( mediaPlayer.isPlaying() ) {
            mediaPlayer.stop();
            stopTimer();
        }
     isClick=false;
    }
}

To stop the music/sound using media player create a boolean value isPlaying . make it true when the music is playing

declare isPlaying as global variable like

private boolean isPlaying = false;
@Override
public void onPrepared(MediaPlayer mp) {
    mp.start();
    isPlaying = true;
}

now you can create a method which will check the value of isPlaying and play or pause the music, call this method onClick() of button

private playPauseMusic(){
    if (!isPlaying) {
        //play music
        isPlaying = true;
        mediaPlayer.start();
    } else {
        //pause music
        isPlaying = false;
        mediaPlayer.pause();
    }
}

hope this will help!

The code below will play the song multipletimes (overlaying) if i click it repeatedly.

Because your are instantiating the media player object each time you hit the button, to solve this, make your medica player object a class field, not a method local field & check first if the object is not null before instantiating it

MediaPlayer mediaPlayer;

public void playFile(View v) { 
    if (mediaPlayer == null)
        mediaPlayer = new MediaPlayer();

    // The reset of the code
    ...

And no need to have a variable to check if the media is playing as you can check that directly from mediaplayer object

if (mediaPlayer.isPlaying()) {
    mediaPlayer.pause();
} else if () {
    mediaPlayer.start();
}

So change your code to

MediaPlayer mediaPlayer;

public void playFile(View v) {
    if (mediaPlayer == null)
        mediaPlayer = new MediaPlayer();

    try {

        mediaPlayer.setDataSource(question.getAudio());

        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(@NotNull MediaPlayer mp) {
                mediaPlayer.start();
            }
        });
        mediaPlayer.prepareAsync();

    }catch (IOException e) {
        e.printStackTrace();
        stopSelf();
    }

    if (mediaPlayer.isPlaying()) {
        //pause music
        mediaPlayer.pause();
    } else if () {
        //play music
        mediaPlayer.start();
    }
}

For timer issue, it's not that clear, how do you implement your timer?

Please define below code at Global:

private Button play_pause;
MediaPlayer mediaPlayer; 

Now in onCreate Method:

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

        mediaPlayer = new MediaPlayer();
        play_pause = findViewById(R.id.play_pause);
    }

Play pause button:

play_pause.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mediaPlayer != null) {
                        if (mediaPlayer.isPlaying()) {
                            mediaPlayer.pause();
                        } else {
                            mediaPlayer.getDuration();
                            mediaPlayer.start();
                        }
                    } 
                }
            });

When Audio is ready to play:

private void readyToPlay(Uri uri) {
        try {
            if (mediaPlayer != null) {
                mediaPlayer.setOnCompletionListener(this);
                mediaPlayer.setDataSource(activity, uri);//Write your location here
                mediaPlayer.prepare();
                mediaPlayer.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Audio is complete then auto stop:

@Override
    public void onCompletion(MediaPlayer mp) {
        if (mediaPlayer != null) {
            mp.stop();
            mp.release();
        }
    }

Don't forgot to add this line:

implements MediaPlayer.OnCompletionListener

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM