Adel gamer
Adel gamer

Reputation: 23

Unresolved reference: Context in android MediaPlayer (kotlin)

I created this function to make the button do a sound when i click it, the sound file is mp3 located in raw/button_click.mp3 directory .

fun play_sound(which_one:Int) {
    if(which_one == 1){
        val mediaPlayer:MediaPlayer? = MediaPlayer.create(Context,R.raw.button_click)
        mediaPlayer?.start()
}
}

But i get the following error when i run it Unresolved reference: Context

How should I edit my code to solve this problem?

By the way just ignore the if statement for now it always turns true for this stage of development.

Upvotes: 1

Views: 1593

Answers (2)

scccrt
scccrt

Reputation: 56

Unresolved reference: Context

You receive the following error because you are using the Class instead of your variable name as parameter.

fun play_sound(which_one:Int) {
    if(which_one == 1) {
        val mediaPlayer:MediaPlayer? = MediaPlayer.create(Context,R.raw.button_click)
        mediaPlayer?.start()
    }
}

There are also different kind of Contexts in Android.

You have your Application, Activity, and Fragment Context, which is also tied to different lifecycles depending on what Context you used.

If this function is a member of your Activity.

fun play_sound(which_one:Int) {
    if(which_one == 1) {
        val mediaPlayer:MediaPlayer? = MediaPlayer.create(this@YourActivityHere,R.raw.button_click)
        mediaPlayer?.start()
    }
}

Fragment

fun play_sound(which_one:Int) {
    if(which_one == 1) {
        val mediaPlayer:MediaPlayer? = MediaPlayer.create(requireContext(),R.raw.button_click)
        mediaPlayer?.start()
    }
}

Upvotes: 3

snachmsm
snachmsm

Reputation: 19233

pass proper active Context to this method

fun play_sound(ctx:Context, which_one:Int) {
    if(which_one == 1){
        val mediaPlayer:MediaPlayer? = MediaPlayer.create(ctx, R.raw.button_click)
        mediaPlayer?.start()
    }
}

Upvotes: 0

Related Questions