androidclasssoundpoolcompanion-object

SoundPool items randomly playing/not playing when triggered


I have some sounds in a SoundPool that I need to play. Sometimes when they should play, there's just a low pitched click sound instead of the sound that should play. Sometimes they play just fine.

Here's the code I use for the SoundPool:

open class PingSoundPool(context: Context) {

open var mAttributes = AudioAttributes.Builder()
    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
    .setUsage(AudioAttributes.USAGE_GAME)
    .build()

open var mSoundPool = SoundPool.Builder()
    .setMaxStreams(9)
    .setAudioAttributes(mAttributes)
    .build()

open var babping = mSoundPool.load(context, R.raw.ab830ping, 1)
open var aaping = mSoundPool.load(context, R.raw.a220ping, 1)
open var abbping = mSoundPool.load(context, R.raw.bb233ping, 1)
open var abping = mSoundPool.load(context, R.raw.b247ping, 1)
[and others]

open fun loadPings(note: Int) {
println(note.toString())
if (note == 0) {}
if(note == 1)
    mSoundPool.play(acping, 2.55f, 2.55f, 1, 0, 1f)
if(note == 2)
mSoundPool.play(adbping, 2.5f, 2.5f, 1, 0, 1f)
if(note == 3)
    mSoundPool.play(adping, 2.45f, 2.45f, 1, 0, 1f)
if(note == 4)
    mSoundPool.play(aebping, 2.4f, 2.4f, 1, 0, 1f)
[and so on]
}

Now I make this accessible within my activity:

companion object {
lateinit var pingSoundPool: PingSoundPool
}

And in onCreate I do pingSoundPool = PingSoundPool(this)

Like this, I should be able to play any of these sounds with FullscreenActivity.pingSoundPool.loadPings(note: Int) - as stated above, this sometimes works, sometimes it doesn't, even for repetitions of the same sound.

One observation is that println(note.toString()) prints the Int corresponding to the note that should be played, regardless of whether the note can actually be heard. However, every time the note is actually played, that number is followed by W/AudioTrack: AUDIO_OUTPUT_FLAG_FAST denied by client; transfer 4, track 44100 Hz, output 48000 Hz - All these come up in Android Studio's logcat.

This happens in the emulator as well as on real devices.

Any ideas?


Solution

  • The solution is this: the volume only accepts values from 0.0f to 1.0f. I tried setting them all to 1.0f and now it works fine.

    if(note == 4) mSoundPool.play(aebping, 2.4f, 2.4f, 1, 0, 1f) // wrong
    if(note == 4) mSoundPool.play(aebping, 1.0f, 1.0f, 1, 0, 1f) // right