Skip to content Skip to sidebar Skip to footer

Android: Change Button Text After Mediaplayer Audio Ends

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 p

Solution 1:

If you use the MediaPlayer class directly on the activity, then you can use its OnCompletionListener to detect if the media stops playing. inside this OnCompletionListener you can switch your button's text from "Pause" to "Play" like so:

mPlayer.setOnCompletionListener(newMediaPlayer.OnCompletionListener() {
    publicvoidonCompletion(MediaPlayer mp) {
        mPlayButton.setText("Play");
    }
});

I integrated your AudioPlayer to the fragment so that it would look like:

publicclassHelloMoonFragmentextendsFragment {

    privateButton mPlayButton;
    privateButton mStopButton;

    privateMediaPlayer mPlayer;
    privateboolean mCompleted =  false;

    @OverridepublicViewonCreateView(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(newView.OnClickListener(){
            publicvoidonClick(View v) {

                if(mPlayer == null) {
                    mPlayer = MediaPlayer.create(c, R.raw.one_small_step);
                    mPlayer.setOnCompletionListener(newMediaPlayer.OnCompletionListener() {
                        publicvoidonCompletion(MediaPlayer mp) {
                            stopMediaPlayer();
                            mPlayButton.setText("Play");
                        }
                    });
                }

                if(mPlayButton.getText().equals("Play")) {
                    mPlayButton.setText("Pause");
                    mPlayer.start();
                }
                elseif(mPlayButton.getText().equals("Pause")){
                    mPlayButton.setText("Play");
                    mPlayer.pause();
                }
            }
        });

        mStopButton = (Button)v.findViewById(R.id.hellomoon_stopButton);
        mStopButton.setOnClickListener(newView.OnClickListener() {
           publicvoidonClick(View v) {
                stopMediaPlayer();
                mPlayButton.setText("Play");
           }
        });

        return v;
    }

    @OverridepublicvoidonDestroy() {
        stopMediaPlayer();
        super.onDestroy();
    }


    publicvoidstopMediaPlayer() {
        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
    }
}

Post a Comment for "Android: Change Button Text After Mediaplayer Audio Ends"