1

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.

Adel gamer
  • 23
  • 7

2 Answers2

3

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()
    }
}
scccrt
  • 56
  • 1
0

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()
    }
}
snachmsm
  • 17,866
  • 3
  • 32
  • 74