Setting the Volume Controls

If you possess an Android device, you will have noticed that when you press the volume up and down buttons, you control different volume settings depending on what application you are currently in. In a call you control the volume of the incoming voice stream. In the YouTube application you control the volume of the video's audio. On the home screen you control the volume of the ringer.

Android has different audio streams for different purposes. When we play back audio in our game, we use classes that output sound effects and music to a specific stream called the music stream. Before we think about playing back sound effects or music, though, we have to first make sure that the volume buttons will control the correct audio stream. For this we use another method of the Context interface:

context.setVolumeControlStream(AudioManager.STREAM_MUSIC);

As always, the Context implementation of our choice will be our activity. After this call, the volume buttons will control the music stream, to which we'll later output our sound effects and music. We need to call this method only once in our activity life cycle. The Activity.onCreate() method is the best place to do this.

Writing an example that only contains a single line of code is a bit of overkill. I'll thus refrain from doing that at this point. Just remember to use this method in all the activities that output sound.

YouTube Tactics

YouTube Tactics

Report Reveals 50 Easy-To-Implement YouTube Tactics For Better Videos, More Video Views and Traffic To Your Website.

Get My Free Ebook


Post a comment