So I'm following Big Nerd Ranch's Android Programming book and I have an audio file playing through MediaPLayer. I also have a button that both plays and pauses the audio. If you press the play button to play the audio the text on the button changes to "pause". The problems is after the audio ends the button still says "pause" so the user has to press the button twice to play the audio again. How would I get the button to change its text to "play right after the audio ends"
Here's my code minus the layout xml for the buttons
Fragment class:
public class HelloMoonFragment extends Fragment {
private Button mPlayButton;
private Button mStopButton;
private AudioPlayer mPlayer = new AudioPlayer();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_hello_moon, parent, false);
mPlayButton = (Button)v.findViewById(R.id.hellomoon_playButton);
mPlayButton.setText("Play");
mPlayButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
if(mPlayButton.getText().equals("Play")) {
mPlayButton.setText("Pause");
mPlayer.play(getActivity());
}
else if(mPlayButton.getText().equals("Pause")){
mPlayButton.setText("Play");
mPlayer.pause();
}
}
});
mStopButton = (Button)v.findViewById(R.id.hellomoon_stopButton);
mStopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mPlayer.stop();
mPlayButton.setText("Play");
}
});
return v;
}
@Override
public void onDestroy() {
super.onDestroy();
mPlayer.stop();
}
}
MediaPlayer class:
package com.bignerdranch.android.hellomoon;
import android.content.Context;
import android.media.MediaPlayer;
public class AudioPlayer {
private MediaPlayer mPlayer;
private boolean mCompleted = false;
public void stop() {
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
public void play(Context c) {
if(mPlayer == null) {
mPlayer = MediaPlayer.create(c, R.raw.one_small_step);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
stop();
mCompleted = true;
}
});
}
mPlayer.start();
}
public void pause() {
if(mPlayer != null) mPlayer.pause();
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…