Easy Tutorial
❮ Java Composite Pattern 2 Python Tower ❯

10.3 AudioManager (Audio Manager)

Category Android Basic Tutorial

Introduction:

>

In the first section of multimedia, we created a "Duang" example using SoundPool. When the pig clicked a button, it suddenly made a loud "Duang" sound, which scared me to death.

AudioManager (Audio Manager), a class located in the Android.Media package, provides operations related to volume control and ringtone modes! In this section, we will learn how to use this class. You can create a demo, a simple mute function. Before watching a movie, enter the demo and click mute.

Official API documentation: AudioManager


1. Obtain an AudioManager Object Instance

>

AudioManager audiomanage = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);


2. Detailed Method Explanation

Common Methods:

>

-adjustVolume (int direction, int flags): Controls the phone's volume, increasing or decreasing by one unit based on the first parameter. AudioManager.ADJUSTLOWER decreases by one unit; AudioManager.ADJUSTRAISE increases by one unit.

-adjustStreamVolume (int streamType, int direction, int flags): Similar to the above, but allows selection of the type of sound to adjust. 1) streamType parameter, specifies the type of sound: STREAM_ALARM: phone alarm, STREAM_MUSIC**: phone music, **STREAM_RING: phone ringtone, STREAM_SYSTEM**: phone system, **STREAM_DTMF: tone, STREAM_NOTIFICATION**: system notification, **STREAM_VOICE_CALL**: voice call. 2) The second parameter is the same as above, for increasing or decreasing the volume. 3) Optional flags, such as AudioManager.**FLAG_SHOW_UI**: show progress bar, AudioManager.**PLAY_SOUND: play sound.

-setStreamVolume (int streamType, int index, int flags): Directly sets the volume level.

-getMode (): Returns the current audio mode.

-setMode (): Sets the audio mode. Available modes are: MODENORMAL (normal), MODERINGTONE (ringtone), MODEINCALL (calling), MODEINCOMMUNICATION (communication).

-getRingerMode (): Returns the current ringtone mode.

-setRingerMode (int streamType): Sets the ringtone mode. Available modes are: RINGERMODENORMAL (normal), RINGERMODESILENT (silent), RINGERMODEVIBRATE (vibrate).

-getStreamVolume (int streamType): Gets the current volume of the phone, with a maximum of 7 and a minimum of 0. Setting it to 0 will automatically switch to vibrate mode.

-getStreamMaxVolume (int streamType): Gets the maximum volume level for a specific sound type.

-setStreamMute (int streamType, boolean state): Mutes a specific sound type.

-setSpeakerphoneOn (boolean on): Sets whether to turn on the loudspeaker.

-setMicrophoneMute (boolean on): Sets whether to mute the microphone.

-isMicrophoneMute (): Checks if the microphone is muted or on.

-isMusicActive (): Checks if any music is active.

-isWiredHeadsetOn (): Checks if a headset is plugged in.

Other Methods:

>

-abandonAudioFocus (AudioManager.OnAudioFocusChangeListener l): Abandons audio focus.

-adjustSuggestedStreamVolume (int, int suggestedStreamType, int flags): Adjusts the volume of the most relevant stream or the given fallback stream.

-getParameters (String keys): Sets a variable number of parameter values for the audio hardware.

-getVibrateSetting (int vibrateType): Returns whether the user's vibration setting is set for the vibration type.

-isBluetoothA2dpOn (): Checks if the A2DP Bluetooth headset audio routing is on or off.

-isBluetoothScoAvailableOffCall (): Indicates whether the current platform supports using SCO for off-call use cases.

-isBluetoothScoOn (): Checks if communication is using Bluetooth SCO.

-loadSoundEffects (): Loads sound effects.

-playSoundEffect ((int effectType, float volume): Plays a sound effect.

-registerMediaButtonEventReceiver (ComponentName eventReceiver): Registers a component as the sole receiver for MEDIA_BUTTON intents.

-requestAudioFocus (AudioManager.OnAudioFocusChangeListener l, int streamType, int durationHint): Requests audio focus.

-setBluetoothScoOn (boolean on): Requests communication using Bluetooth SCO headphones.

-startBluetoothSco/stopBluetoothSco(): Starts/stops Bluetooth SCO audio connection.

-unloadSoundEffects (): Unloads sound effects.


3. Usage Example

>

Hehe, there are quite a few properties, some of which involve Bluetooth and other features. Here, we will only explain the most common methods!

If you encounter any special or unfamiliar ones, refer to the documentation!

Simple example: Use MediaPlayer to play music, and adjust the volume and mute using AudioManager!

First, create a raw folder under res and drop an MP3 resource file into it!

Running Effect:

btn_higher = (Button) findViewById(R.id.btn_higher);
btn_lower = (Button) findViewById(R.id.btn_lower);
btn_quite = (Button) findViewById(R.id.btn_quite);

btn_start.setOnClickListener(this);
btn_stop.setOnClickListener(this);
btn_higher.setOnClickListener(this);
btn_lower.setOnClickListener(this);
btn_quite.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btn_start:
            btn_stop.setEnabled(true);
            mePlayer.start();
            btn_start.setEnabled(false);
            break;
        case R.id.btn_stop:
            btn_start.setEnabled(true);
            mePlayer.pause();
            btn_stop.setEnabled(false);
            break;
        case R.id.btn_higher:
            // Specify the audio stream to adjust, increase the volume, and display the volume graphic
            aManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                    AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
            break;
        case R.id.btn_lower:
            // Specify the audio stream to adjust, decrease the volume, only sound, no graphic bar
            aManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                    AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);
            break;
        case R.id.btn_quite:
            // Specify the audio stream to adjust, determine if mute is needed based on isChecked
            flag *= -1;
            if (flag == -1) {
                aManager.setStreamMute(AudioManager.STREAM_MUSIC, true);   // API 23 deprecated
//                aManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_MUTE,
//                        AudioManager.FLAG_SHOW_UI);   // Use this for versions after 23
                btn_quite.setText("Unmute");
            } else {
                aManager.setStreamMute(AudioManager.STREAM_MUSIC, false);   // API 23 deprecated
//                aManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_UNMUTE,
//                        AudioManager.FLAG_SHOW_UI);   // Use this for versions after 23
                aManager.setMicrophoneMute(false);
                btn_quite.setText("Mute");
            }
            break;
    }
}
}

The code is quite simple. Additionally, the method setStreamMute() is deprecated in API 23. You can use another method adjustStreamVolume(int, int, int), and set the third attribute to:

ADJUSTMUTE or ADJUSTUNMUTE!

By the way:

If you set the third parameter of adjustStreamVolume() to vibrate (Vibrator), you need to add this permission in AndroidManifest.xml!

<uses-permission android:name="android.permission.VIBRATE"/>

Summary:

>

This section demonstrates a simple usage of AudioManager for adjusting volume, a class I don't often use. If I learn any new skills in the future, I'll add them here. Hehe, have you finished writing the mute demo? It should be based on actual needs.

Also, I may not update my blog frequently this week. I need to replace the WebSocket library at work, which is going to be a headache. That's all for now, thank you!

-1.0 Android Basic Beginner Tutorial

-1.0.1 2015 Latest Android Basic Beginner Tutorial Table of Contents

-1.1 Background and System Architecture Analysis

-1.2 Development Environment Setup

-1.2.1 Using Eclipse + ADT + SDK to Develop Android APP

-1.2.2 Using Android Studio to Develop Android APP

-1.3 Solving SDK Update Issues

-1.4 Genymotion Emulator Installation

-1.5.1 Git Tutorial for Basic Local Repository Operations

-1.5.2 Git: Setting Up a Remote Repository on GitHub

-1.6 How to Play with 9-Patch Images

-1.7 Interface Prototype Design

-1.8 Project Source Analysis (Various Files, Resource Access)

-1.9 Android Application Signing and Packaging

-1.11 Decompiling APK to Obtain Code & Resources

-2.1 Concepts of View and ViewGroup

-2.2.1 LinearLayout (Linear Layout)

-2.2.2 RelativeLayout (Relative Layout)

-2.2.3 TableLayout (Table Layout)

-2.2.4 FrameLayout (Frame Layout)

-2.2.5 GridLayout (Grid Layout)

-2.2.6 AbsoluteLayout (Absolute Layout)

-2.3.1 TextView (Text View) Detailed Explanation

-2.3.2 EditText (Input Box) Detailed Explanation

-2.3.3 Button and ImageButton

-2.3.4 ImageView (Image View)

-2.3.5.RadioButton (Radio Button) & Checkbox (Checkbox)

-2.3.6 ToggleButton and Switch

-2.3.7 ProgressBar (Progress Bar)

-2.3.8 SeekBar (Drag Bar)

-2.3.9 RatingBar (Star Rating Bar)

-2.4.1 ScrollView (Scroll Bar)

-2.4.2 Date & Time Components (Part 1)

-2.4.3 Date & Time Components (Part 2)

-2.4.4 Adapter Basics

-2.4.5 Simple Usage of ListView

-2.4.6 BaseAdapter Optimization ```

WeChat Subscription

English:

❮ Java Composite Pattern 2 Python Tower ❯