user3879626 user3879626 - 1 month ago 5
Android Question

Play song in android using android studio

Button playButton = (Button)findViewById(R.id.playButton);
playButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)`enter code here`
{
MediaPlayer mMediaPlayer;

mMediaPlayer = new MediaPlayer();
mMediaPlayer = MediaPlayer.create(this, R.raw.shenkin);
mMediaPlayer.start();
}


});


I am getting error on "this" as parameter to MediaPlayer.create
What should I do to fix it ?

Answer

In that scope, this refers to new View.OnClickListener(), but you want it to refer to your activity, or pass any other context. In that case, you should do:

mMediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.shenkin); 
//Or whichever the name of the activity is

or something like

mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shenkin); 
Comments