AudioManager(audio manager)


Introduction to this section:

In the first section of multimedia, we used SoundPool to write an example of Duang. After the piggy clicks a button, it suddenly emits "Duang" One sound, and the sound was so loud that it scared the baby to death1.jpg. Fortunately, it was not during working hours. During working hours, I secretly wrote a blog to let the manager know. It will kill you~ Well, okay, when it comes to the sound volume, we have to introduce the API (volume control) provided by Android for us:

AudioManager(audio manager) Yes, this class is located under the Android.Media package and provides volume control and ringtone mode related operations! In this section, we will learn how to use this stuff. You can write a demo, a simple mute. Before watching a short movie, first Enter Demo and click mute, then 2.gif, just talk~ Well, without further ado, let’s start this section!

Official API document: AudioManager


1. Obtain the AudioManager object instance

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


2. Detailed explanation of related methods

Common methods:

  • adjustVolume(int direction, int flags): Control the volume of the mobile phone, turn it up or down by one unit, judge based on the first parameter AudioManager.ADJUST_LOWER, it can be adjusted down by one unit; AudioManager.ADJUST_RAISE, it can be adjusted up by one unit
  • adjustStreamVolume(int streamType, int direction, int flags): Same as above, but you can choose to adjust the sound type 1) The streamType parameter specifies the sound type. There are the following sound types: STREAM_ALARM: mobile phone alarm STREAM_MUSIC: mobile phone music
    STREAM_RING: phone Ringtone STREAM_SYSTEAM: Cell phone system
    STREAM_DTMF: Tone STREAM_NOTIFICATION: System prompt
    STREAM_VOICE_CALL: Voice call 2) The second parameter is the same as the one above, to increase or decrease the volume. 3) Optional flag bits, such as AudioManager.FLAG_SHOW_UI, display progress bar, AudioManager.PLAY_SOUND: play sound
  • setStreamVolume(int streamType, int index, intflags): Set the volume directly
  • getMode( ): Return the current audio mode
  • setMode( ): Set sound mode There are the following modes: MODE_NORMAL(normal), MODE_RINGTONE(ring tone), MODE_IN_CALL(phone call), MODE_IN_COMMUNICATION(call )
  • getRingerMode( ): Return the current ringtone mode
  • setRingerMode(int streamType): Set the ringtone mode There are several modes: Such as RINGER_MODE_NORMAL (normal), RINGER_MODE_SILENT (silent), RINGER_MODE_VIBRATE (vibration)
  • getStreamVolume(int streamType) : Get the current volume of the mobile phone. The maximum value is 7 and the minimum value is 0. When set to 0, it will automatically adjust to vibration mode
  • getStreamMaxVolume(int streamType): Get a certain volume of the mobile phone The maximum volume value of a sound type
  • setStreamMute(int streamType,boolean state): Set a certain sound type on the phone to mute
  • setSpeakerphoneOn (boolean on): Set whether to turn on the loudspeaker
  • setMicrophoneMute(boolean on): Set whether to mute the microphone
  • isMicrophoneMute(): Determine whether the microphone is muted or open
  • isMusicActive(): Determine whether music is active
  • isWiredHeadsetOn(): Determine whether it is inserted Headphones

Other methods:

  • abandonAudioFocus(AudioManager.OnAudioFocusChangeListenerl):Abandon audio focus
  • adjustSuggestedStreamVolume(int,int suggestedStreamType intflags): Adjust the volume of the most relevant stream, or the given fallback stream
  • getParameters(String keys): Set a varaible number of parameter values ​​for the audio hardware
  • getVibrateSetting(int vibrateType): Returns whether the user's vibration is set to vibration type
  • isBluetoothA2dpOn(): Checks whether the A2DP Bluetooth headset audio routing is on or off
  • isBluetoothScoAvailableOffCall(): Displays whether the current platform supports the use of SCO off call case
  • isBluetoothScoOn(): Checks whether the communication uses Bluetooth SCO
  • loadSoundEffects():Load sound effects
  • playSoundEffect((int effectType, float volume):Play sound effects
  • egisterMediaButtonEventReceiver(ComponentName eventReceiver): Register the only receiver of a component's MEDIA_BUTTON intent
  • requestAudioFocus(AudioManager.OnAudioFocusChangeListener l,int streamType,int durationHint) Request audio focus
  • setBluetoothScoOn(boolean on): Request the use of Bluetooth SCO headsets for communication
  • startBluetoothSco/stopBluetoothSco()(): Start /Stop Bluetooth SCO audio connection
  • unloadSoundEffects(): Unload sound effects

3. Usage example

Hey, there are quite a lot of attributes, some of which involve things like Bluetooth. Here we only explain some of the most common methods!

When we encounter some special ones that we haven’t seen before, let’s check the documentation again!

Simple example: Use Mediaplayer to play music, and adjust the volume and mute through AudioManager!

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

Running renderings:

3.gif

##Code implementation:

Layout Code

activity_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, and there is also a method to set mute

setStreamMute () is expired in API version 23, You can use another method adjustStreamVolume(int, int, int), and then set the third property:

ADJUST_MUTE or ADJUST_UNMUTE!

By the way, there is also:

If you set the vibration (Vibrator) in the third parameter of

adjustStreamVolume(), You need to add this permission in AndroidManifest.xml!

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


4. Code sample download

AudioManagerDemo.zip


Summary of this section:

Okay, this section shows you a simple usage of AudioManager to adjust the volume. This class is not commonly used by the author. Come on, if there are any new skills you can get in the future, please add them~ Hehe, have you finished writing the mute demo? It needs to be combined with actual needs~4.gif

In addition, the blog may not be updated too frequently this week. The company's WebSocket library will be replaced this week, which will give me a headache~ Okay, that’s all, thank you~