-2

// Necessary libraries are imported.

public class MainActivity extends AppCompatActivity {
    MediaPlayer mPlayer;

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

    public void playAudio(View view) {
        mPlayer.create(this, R.raw.hahah);
        mPlayer.start();
    }

    public void pauseAudio(View view) {
        mPlayer.pause();
    }

}

This is my MainActivity. The app crashes as soon as I press play or pause button. This app works when I remove both the buttons and allow it to start playing automatically in onCreate method.

MJM
  • 5,088
  • 4
  • 24
  • 50
Abhay V Ashokan
  • 112
  • 2
  • 7

3 Answers3

3

You forgot

MediaPlayer mPlayer =new MediaPlayer();  

in onCreate method

Urvish Jani
  • 98
  • 1
  • 3
0

You must initialize class before using it. Object is not created for the mplayer.

Initialize it in the onCreate() method

MediaPlayer mPlayer =new MediaPlayer(); 
AskNilesh
  • 63,753
  • 16
  • 113
  • 150
Magudesh
  • 389
  • 4
  • 13
0

Well, whenever you define a variable but don't assign value to it, it will crash the app. Here you are creating a MediaPlayer but not assigning it. You should add this code in your onCreate() method:

MediaPlayer mMediaPlayer = new MediaPlayer();

This will create a new instance of the MediaPlayer object and you can reuse the functions of that class.

Gourav
  • 2,560
  • 5
  • 25
  • 40