user3210655
user3210655

Reputation: 43

Android setStreamVolume not working reliably

Since Android Marshmallow, AudioManager.setStreamVolume not working reliably.

The Stream does not change its volume. Here is the syntax:

audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, AudioManager.FLAG_SHOW_UI);

The UI that is shown actually SHOWS the correct volume setting, but it reverts to the old volume without being changed. This used to work before Android v21 - 6.0

Any ideas?

Upvotes: 1

Views: 4176

Answers (1)

user496854
user496854

Reputation: 6830

There's something weird going on with the timing of the setStreamVolume() call on 6.0. You have to do it after the stream starts playing, otherwise it doesn't take effect until the stream stops playing, and then starts again. The tricky part is making sure that the stream is actually playing before you try to change the volume. Depending on your implementation, that may not be straightforward. If you showing any kind of a UI for playback (like a seekbar), you can add code to the thread that's updating that UI. I have it waiting for 250ms from the start of playback, and then set the volume. But if you don't have any UI (you just start playback, and never keep track of the progress), then you have to arbitrarily choose how long to wait to change the volume. But in this case, it would work differently on different devices because on slower ones there is a greater delay to process the stream and actually start playing it.

Upvotes: 5

Related Questions