由于我的应用程序结构,我试图在@Copmosable之外播放声音。
我有一个验证例程,它在我的视图模型中,根据结果我想触发一个声音,但我似乎无法在@Composable之外获得上下文工作
我在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任何指点都会很好,谢谢!
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()
}和MasterViewModel
package com.example.soundtest
import android.media.MediaPlayer
class MasterViewModel {
fun playSound() {
val mp: MediaPlayer = MediaPlayer.create(this, R.raw.correct)
}
}我在res->raw-correct.mp3 -mp3下保存了原始文件
发布于 2021-08-09 10:03:42
我让它工作了!
我只是包含了
@Composable
fun Greeting(mastVM: MasterViewModel = MasterViewModel()) {
val context = LocalContext.current
Text("Play a sound...")
mastVM.playSound(context: context)
}然后在MasterViewModel中,如下所示
fun playSound(context: Context) {
val mp: MediaPlayer = MediaPlayer.create(context, R.raw.correct)
}https://stackoverflow.com/questions/68709122
复制相似问题