【发布时间】:2021-08-09 08:38:04
【问题描述】:
由于我的应用程序结构,我正在尝试在 @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
【问题讨论】:
标签: kotlin android-mediaplayer android-jetpack