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();
}