Introduction to this section:

In the first section on multimedia, we used SoundPool to write a "Duang" example. After the little pig clicked a button, a loud "Duang" sound suddenly came out, and it was so loud that it scared the baby to death, fortunately it wasn't during working hours. If the manager knew I was secretly writing blog posts during working hours, I'd be in big trouble~ Well, speaking of volume, I have to introduce the API Android provides for (volume control):

AudioManager (Audio Manager). This class is located in the Android.Media package and provides operations related to volume control and ringtone mode! In this section, we'll learn how to use this thing. You can write a Demo, a simple mute. Every time before watching a little movie, first enter the Demo and click mute, then, just kidding~ Well, without further ado, let's begin this section!

Official API documentation:AudioManager


1. Obtain an AudioManager object instance

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


2. Detailed explanation of related methods

Common methods:

  • adjustVolume(int direction, int flags): Controls the phone volume, increasing or decreasing by one unit, judged according to the first parameterAudioManager.ADJUST_LOWER, can decrease by one unit;AudioManager.ADJUST_RAISE, can increase by one unit
  • adjustStreamVolume(int streamType, int direction, int flags): Same as above, but you can choose the sound type to adjust. 1) The streamType parameter specifies the sound type. There are the following sound types:STREAM_ALARM: phone alarmSTREAM_MUSIC: phone music
    STREAM_RING: phone ringtoneSTREAM_SYSTEAM: phone system
    STREAM_DTMF: toneSTREAM_NOTIFICATION: system notification
    STREAM_VOICE_CALL: voice call 2) The second parameter is the same as the one above, to increase or decrease the volume. 3) Optional flags, for example AudioManager.FLAG_SHOW_UI, displays the progress bar, AudioManager.PLAY_SOUND: plays a sound
  • setStreamVolume(int streamType, int index, intflags): Directly set the volume level
  • getMode( ): Returns the current audio mode
  • setMode( ): Sets the sound mode There are the following modes:MODE_NORMAL(normal),MODE_RINGTONE(ringtone),MODE_IN_CALL(in call),MODE_IN_COMMUNICATION(communication)
  • getRingerMode( ): Returns the current ringtone mode
  • setRingerMode(int streamType): Sets the ringtone mode There are the following modes: For exampleRINGER_MODE_NORMAL(normal),RINGER_MODE_SILENT(mute),RINGER_MODE_VIBRATE(vibrate)
  • getStreamVolume(int streamType): Gets the current volume of the phone, with a maximum value of 7 and a minimum value of 0. When set to 0, it automatically switches to vibrate mode
  • getStreamMaxVolume(int streamType): Gets the maximum volume value for a certain sound type of the phone
  • setStreamMute(int streamType, boolean state): Sets a certain sound type of the phone to mute
  • setSpeakerphoneOn(boolean on): Sets whether to turn on the loudspeaker
  • setMicrophoneMute(boolean on): Sets whether to mute the microphone
  • isMicrophoneMute( ): Determines whether the microphone is muted or turned on
  • isMusicActive( ): Determines whether there is any music in an active state
  • isWiredHeadsetOn( ): Determines whether headphones are inserted

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 to the vibrate type
  • isBluetoothA2dpOn( ): Checks whether the A2DP Bluetooth headset audio route is on or off
  • isBluetoothScoAvailableOffCall( ): Indicates whether the current platform supports the off-call use case using SCO
  • isBluetoothScoOn( ): Checks whether communication uses Bluetooth SCO
  • loadSoundEffects( ): Loads a sound effect
  • playSoundEffect(int effectType, float volume): Plays a sound effect
  • egisterMediaButtonEventReceiver(ComponentName eventReceiver): Registers a component as the unique receiver for the MEDIA_BUTTON intent
  • requestAudioFocus(AudioManager.OnAudioFocusChangeListener l, int streamType, int durationHint) Requests audio focus
  • setBluetoothScoOn(boolean on): Requires the use of a Bluetooth SCO headset for communication
  • startBluetoothSco/stopBluetoothSco()( ): Starts/stops the Bluetooth SCO audio connection
  • unloadSoundEffects( ): Unloads sound effects

3. Usage examples

Hehe, there are quite a lot of properties, and some even involve things like Bluetooth. Here we will only explain the most common methods!

If we encounter some special or unfamiliar ones, we can look up the documentation!

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

By the way, first create a raw folder under res, and drop an MP3 resource file into it!

Running effect screenshot:

Code implementation:

Layout codeactivity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="播放" />

    <Button
        android:id="@+id/btn_stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:enabled="false"
        android:text="停止" />

    <Button
        android:id="@+id/btn_higher"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="调高音量" />

    <Button
        android:id="@+id/btn_lower"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="调低音量" />

    <Button
        android:id="@+id/btn_quite"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="静音" />

</LinearLayout> 

MainActivity.java:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btn_start;
    private Button btn_stop;
    private Button btn_higher;
    private Button btn_lower;
    private Button btn_quite;
    private MediaPlayer mePlayer;
    private AudioManager aManager;
    //定义一个标志用来标示是否点击了静音按钮
    private int flag = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获得系统的音频对象
        aManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
        //初始化mediaplayer对象,这里播放的是raw文件中的mp3资源
        mePlayer = MediaPlayer.create(MainActivity.this, R.raw.countingstars);
        //设置循环播放:
        mePlayer.setLooping(true);
        bindViews();
    }

    private void bindViews() {
        btn_start = (Button) findViewById(R.id.btn_start);
        btn_stop = (Button) findViewById(R.id.btn_stop);
        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:
                // 指定调节音乐的音频,增大音量,而且显示音量图形示意
                aManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                        AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
                break;
            case R.id.btn_lower:
                // 指定调节音乐的音频,降低音量,只有声音,不显示图形条
                aManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                        AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);
                break;
            case R.id.btn_quite:
                // 指定调节音乐的音频,根据isChecked确定是否需要静音
                flag *= -1;
                if (flag == -1) {
                    aManager.setStreamMute(AudioManager.STREAM_MUSIC, true);   //API 23过期- -
//                    aManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_MUTE,
//                            AudioManager.FLAG_SHOW_UI);   //23以后的版本用这个
                    btn_quite.setText("取消静音");
                } else {
                    aManager.setStreamMute(AudioManager.STREAM_MUSIC, false);//API 23过期- -
//                    aManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_UNMUTE,
//                            AudioManager.FLAG_SHOW_UI);  //23以后的版本用这个
                    aManager.setMicrophoneMute(false);
                    btn_quite.setText("静音");
                }
                break;
        }
    }
}

The code is still very simple. In addition, the method for setting mutesetStreamMute() was deprecated in API 23. You can use another method, adjustStreamVolume(int, int, int), and then set the third parameter:

ADJUST_MUTEorADJUST_UNMUTE!

Oh, and also:

IfadjustStreamVolumethe third parameter of () is set to vibration (Vibrator), then you need to add this permission in AndroidManifest.xml!

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

<h2>4. Code example download</h2> <p><a href="../download/AudioManagerDemo.zip.html">AudioManagerDemo.zip</a></p> <hr />

Summary of this section:

Okay, in this section we demonstrated a simple usage of AudioManager for adjusting volume. I, the author, don't use this class very often. If I learn any new skills in the future, I'll add them~ Hehe, have you finished writing the mute Demo? Do it based on actual needs~

In addition, the blog may not be updated very frequently this week. I have to replace the company's WebSocket library this week, which is a headache~ Okay, that's all for now, thank you~