Jetpack compose - trying to get sound to play in viewmodel fun

Viewed 1097

I'm trying to play a sound outside of @Copmosable because of my application structure.

I have a validation routine which is in my viewmodel and based on the result I would like to trigger a sound but I cannot seem to get context working outside of @Composable

I get the following error in the MasterViewModel:

None of the following functions can be called with the arguments supplied.
create(Context!, Uri!) defined in android.media.MediaPlayer
create(Context!, Int) defined in android.media.MediaPlayer

Any pointers would be great thanks!!

package com.example.soundtest

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import com.example.soundtest.ui.theme.SoundTestTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            SoundTestTheme {
                // A surface container using the 'background' color from the theme
                Surface(color = MaterialTheme.colors.background) {
                    Greeting()
                }
            }
        }
    }
}

@Composable
fun Greeting(mastVM: MasterViewModel = MasterViewModel()) {
    Text("Play a sound...")
    mastVM.playSound()
    
}

and the MasterViewModel

package com.example.soundtest

import android.media.MediaPlayer

class MasterViewModel {

    fun playSound() {
        val mp: MediaPlayer = MediaPlayer.create(this, R.raw.correct)
    }
}

I have correct.mp3 save under res->raw-correct.mp3

MasterViewModel Error

1 Answers

I got it working!!!

I just include

@Composable
fun Greeting(mastVM: MasterViewModel = MasterViewModel()) {
    val context = LocalContext.current
    Text("Play a sound...")
    mastVM.playSound(context: context)
    
}

and then in the MasterViewModel like this

fun playSound(context: Context) {
        val mp: MediaPlayer = MediaPlayer.create(context, R.raw.correct)
    }
Related