【发布时间】:2019-07-03 10:34:26
【问题描述】:
我有一个 SoundPool,我想在不同的片段中播放。所以我在一个单例中加载它。我必须使用什么上下文?
object PingSoundPool {
fun loadpings(note: Int) {
val context = Application()
val mAttributes = AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_GAME)
.build()
val mSoundPool = SoundPool.Builder()
.setMaxStreams(9)
.setAudioAttributes(mAttributes)
.build()
val cping = mSoundPool.load(context, R.raw.cping, 1)
val dbping = mSoundPool.load(context, R.raw.dbping, 1)
[...]
if (note == 0) {}
if(note == 1)
mSoundPool.play(cping, 1f, 1f, 1, -1, 1f)
if(note == 2)
mSoundPool.play(dbping, 1f, 1f, 1, -1, 1f)
[...]
}
}
如果我这样使用它,像这样PingSoundPool.loadPings(0) 将它加载到我的活动的 onCreate 中并在带有PingSoundPool.loadPings(1) 的 onClickListener 中访问它应该可以工作,不是吗?
在运行时,我得到一个像这样的 NullPointerExeption:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.soulfetch2/com.example.soulfetch2.FullscreenActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'android.content.res.Resources android.content.Context.getResources()'
on a null object reference
异常指出val cping = mSoundPool.load(context, R.raw.cping, 1)这一行
R.raw。文件存在,但无法以某种方式访问。我想我可能使用了错误的上下文。或者我以错误的方式实现了正确的上下文。
无论如何,非常感谢您的帮助。
编辑:
原来的问题已经解决,但还是有问题:每次尝试播放声音时,代码都会重新加载 SoundPool。有没有人知道如何单独加载它,以便PingSoundPool(this).loadPings(Int) 的调用只是播放声音而不是重新加载所有内容?
另一件事:当我从 Activity 执行 PingSoundPool(this).loadPings(Int) 时,一切正常。然而,从一个片段中,我得到一个 TypeMismatch“必需:上下文,找到:MainFragment”。我可以使用PingSoundPool(this.requireContext()).loadPings(2) 或PingSoundPool(this.context!!).loadPings(2) 解决它,但这似乎不是最好的做法。有什么建议吗?
这是我现在使用的类而不是对象:
class PingSoundPool(context: Context) {
val mAttributes = AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_GAME)
.build()
val mSoundPool = SoundPool.Builder()
.setMaxStreams(9)
.setAudioAttributes(mAttributes)
.build()
val cping = mSoundPool.load(context, R.raw.cping, 1)
val dbping = mSoundPool.load(context, R.raw.dbping, 1)
fun loadPings(note: Int) {
if(note == 1)
mSoundPool.play(cping, 1f, 1f, 1, -1, 1f)
if(note == 2)
mSoundPool.play(dbping, 1f, 1f, 1, -1, 1f)
[...]
}
}
【问题讨论】:
标签: android kotlin singleton android-context soundpool