set Audio Attributes in SoundPool.Builder class for API 21

Pranit Bankar picture Pranit Bankar · Jan 29, 2015 · Viewed 17.7k times · Source

I am following an Android Programming video lecture series which was designed in the pre-API 21 times. Hence it tells me to create a SoundPool variable in the following manner.

SoundPool sp = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
//SoundPool(int maxStreams, int streamType, int srcQuality)

However, I want to use this SoundPool for API 21 as well. So, I am doing this:

if((android.os.Build.VERSION.SDK_INT) == 21){
    sp21 = new SoundPool.Builder();
    sp21.setMaxStreams(5);
    sp = sp21.build();
}
else{
    sp = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
}

sp21 is a variable of Builder type for API 21 and sp is of SoundPool type.

This works very well with my AVD having API 21 and real device having API 19. (Haven't tried with a real device with API 21 but I think it will work well). Now, I want to set the streamType to USAGE_MEDIA in the if-block before sp = sp21.build();. So I type:

sp21.setAudioAttributes(AudioAttributes.USAGE_MEDIA);

But the Lint marks it in red and says:

The method setAudioAttributes(AudioAttributes) in the type SoundPool.Builder is not applicable for the arguments (int)

I know that even if I do not set it to USAGE_MEDIA it will be set to the same by default. But I am asking for future reference if I have to set it to something else like : USAGE_ALARM.

How should I proceed ?

Please Help!

I have referred to Audio Attributes, SoundPool, SoundPool.builder and AudioManager.

Answer

rmdroid picture rmdroid · Jan 29, 2015

An AudioAttributes instance is built through its builder, AudioAttributes.Builder.

You can use it in the following way.

sp21.setAudioAttributes(new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build());

Ref:https://developer.android.com/reference/android/media/AudioAttributes.html