Set volume of audio attributes

After looking for a very long time to play notification sounds only through headphones (when plugged in) on a stream other than STREAM_MUSIC

, so that it can be interrupted and fully audible over any background music, Android finally came out with the AudioAttributes API. Using the following code, I can achieve exactly what I want for notifications, at least in API 21 or higher ( STREAM_MUSIC

is the best option I've found for lower versions):

AudioAttributes audioAttributes = new AudioAttributes.Builder()
    .setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
    .build();

      

Unfortunately, there is no way to adjust the audio volume in my app settings. Currently, I use AudioManager

the following, but it only allows you to adjust the volume flow, and none of the STREAM_ALARM

, STREAM_NOTIFICATION

, STREAM_RING

or STREAM_MUSIC

does not apply to any routing strategy used for sound processing

audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, originalVolume, 0);

      

Does anyone have any suggestion on how to set the volume to match the output AudioAttributes

? Be aware that the sound is actually played in BroadcastReceiver

, which is used for the actual notification, and the sound setting will only be specified in some settings Activity

.

+3


source to share


1 answer


Well it looks like I missed the critical table in the API documentation: https://source.android.com/devices/audio/attributes.html



Seems to STREAM_SYSTEM

be the equivalent of what I was trying to do with AudioAttributes

. Basically, for API code 21 and above, it is enough to use the code above, and using STREAM_SYSTEM

does everything necessary for AudioManager

APIs up to 21.

+3


source







All Articles