Search code examples
androidadt

Trying to use the same button to play+pause music


I have recently tried to create a button that says "Play", and when this button is pressed, I wanted it to play the music then change the text to "Stop", but it throws an error and quits the app. Here is my code:

        mPlay.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if(ourMusic.isPlaying()){
                ourMusic.pause();
                mDisplay.setText("Play");
            }else{
                ourMusic = MediaPlayer.create(MainActivity.this, R.raw.killthenoise);
                ourMusic.start();
                mDisplay.setText("Stop");
            }
        }
    });

So if you press the button once it should play, press it again it should stop the music. There is no errors in the actual coding. Here is my logcat: http://pastie.org/7970711

I am new to this stuff, so I don't know too much of whats going on. Any help would be appreciated.


Solution

  • Use this instead:

        @Override
        public void onClick(View v) {
            if (ourMusic == null) {
                ourMusic = MediaPlayer.create(MainActivity.this, R.raw.killthenoise);
            }
    
            if(ourMusic.isPlaying()){
                ourMusic.pause();
                mDisplay.setText("Play");
            }else{
                ourMusic.start();
                mDisplay.setText("Stop");
            }
        }
    

    Basically don't:

    1. Recreate ourMusic everytime there is a click to play
    2. Try to use ourMusic when it isn't instantiated.