Search code examples
javaandroidandroid-studiosoundpool

How do I Update My SoundPool Constructor to Use SoundPool.Builder?


My old SoundPool construction went as follows:

mySoundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);

I am just playing small mp3 sounds.

This has now been deprecated, so we now use SoundPool.Builder.

I have looked around and all I can find is something on the lines:

AudioAttributes attributes = new AudioAttributes.Builder()
    .setUsage(AudioAttributes.USAGE_MEDIA)
    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
    .build();
mySoundPool = new SoundPool.Builder()
    .setAudioAttributes(attributes)
    .setMaxStreams(3)
    .build();

But,

  1. I cannot see the new equivalent of AudioManager.STREAM_MUSIC in the new version. Where does this go?
  2. What AudioAttribute do I need in .setUsage(AudioAttributes.USAGE_MEDIA)?
  3. My Android Studio does not like the existence of the line `.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)'. Why is that?

Can anyone help me on what I need to do to update my code with new-equivalence of my old code?


Solution

  • The old SoundPool constructor was deprecated in favor of using SoundPool.Builder to build the SoundPool object. The old constructor had three parameters: maxStreams, streamType, and srcQuality.

    • The maxStreams parameter can still be set with the Builder. (And if you don't set it, it defaults to 1.)

    • The streamType parameter is replaced by AudioAttributes, which is more descriptive than streamType. (See the different stream type constants starting here.) With AudioAttributes you can specify the usage (why you are playing the sound), the content type (what you are playing), and flags (how to play it).

    • The srcQuality parameter was supposedly there to set the sample-rate converter quality. However, it was never implemented and setting it had no effect.

    SoundPool.Builder is better than the old constructor because maxStreams does not need to be explicitly set, AudioAttributes contains more information than streamType, and the useless srcQuality parameter was eliminated. Hope this video can help you out buddy!