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.5.RadioButton (Radio Button) & Checkbox (Checkbox)
-2.3.6 ToggleButton and Switch
-2.3.7 ProgressBar (Progress 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.5 Simple Usage of ListView
-2.4.6 BaseAdapter Optimization ```
- 2.4.7 Focus Issues with ListView
- 2.4.8 Solving Checkbox Misalignment in ListView
- 2.4.9 Data Update Issues with ListView
- 2.5.0 Building a Reusable Custom BaseAdapter
- 2.5.1 Implementing Multiple Item Layouts in ListView
- 2.5.2 Basic Usage of GridView (Grid View)
- 2.5.3 Basic Usage of Spinner (Dropdown List)
- 2.5.4 Basic Usage of AutoCompleteTextView (Auto-complete Text Field)
- 2.5.5 Basic Usage of ExpandableListView (Collapsible List)
- 2.5.6 Basic Usage of ViewFlipper (Flip View)
- 2.5.7 Basic Usage of Toast (Popup Message)
- 2.5.8 Detailed Guide on Notification (Status Bar Notification)
- 2.5.9 Detailed Guide on AlertDialog (Dialog Box)
- 2.6.0 Basic Usage of Other Common Dialogs
- 2.6.1 Basic Usage of PopupWindow (Floating Box)
- 2.6.2 Menu (Menu)
- 2.6.3 Simple Usage of ViewPager
- 2.6.4 Simple Usage of DrawerLayout (Official Side Slider Menu)
- 3.1.1 Event Handling Mechanism Based on Listeners
- 3.2 Event Handling Mechanism Based on Callbacks
- 3.3 Analysis of Handler Message Passing Mechanism
- 3.4 TouchListener vs OnTouchEvent + Multi-touch
- 3.5 Listening to Content Changes in EditText
- 3.6 Responding to System Setting Changes (Configuration Class)
- 3.7 AsyncTask Asynchronous Tasks
- 3.8 Gestures (Gestures)
- 4.1.1 Introduction to Activity
- 4.1.2 Getting Started with Activity
- 4.1.3 Advanced Activity
- 4.2.1 Introduction to Service
- 4.2.2 Advanced Service
- 4.2.3 Expert Service
- 4.3.1 Basic BroadcastReceiver
- 4.3.2 Detailed BroadcastReceiver
- 4.4.1 Introduction to ContentProvider
- 4.4.2 Further Exploration of ContentProvider — Document Provider
- 4.5.1 Basic Usage of Intent
- 4.5.2 Passing Complex Data with Intent
- 5.1 Basic Overview of Fragment
- 5.2.1 Fragment Example Analysis — Bottom Navigation Bar Implementation (Method 1)
- 5.2.2 Fragment Example Analysis — Bottom Navigation Bar Implementation (Method 2)
- 5.2.3 Fragment Example Analysis — Bottom Navigation Bar Implementation (Method 3)
- 5.2.4 Fragment Example Analysis — Bottom Navigation Bar + ViewPager Page Sliding
- 5.2.5 Fragment Example Analysis — Simple Implementation of News (Shopping) App List Fragment
- 6.1 Data Storage and Access — File Storage and Reading
- 6.2 Data Storage and Access — SharedPreferences for Saving User Preferences
- 6.3.1 Data Storage and Access — Introduction to SQLite Database
- 6.3.2 Data Storage and Access — Further Exploration of SQLite Database
- 7.1.1 Android Network Programming and Learning HTTP Protocol
- 7.1.2 Learning Android HTTP Request and Response Headers
- 7.1.3 Android HTTP Request Method: HttpURLConnection
- 7.1.4 Android HTTP Request Method: HttpClient
- 7.2.1 Android XML Data Parsing
- 7.2.2 Android JSON Data Parsing
- 7.3.1 Android File Upload
- 7.3.2 Android File Download (1)
- 7.3.3 Android File Download (2)
- 7.4 Android Calling WebService
- 7.5.1 Basic Usage of WebView (Web View)
- 7.5.2 Basic Interaction Between WebView and JavaScript
- 7.5.3 Considerations for WebView in Android 4.4 and Later
- 7.5.4 WebView File Download
- 7.5.5 WebView Cache Issues
- 7.5.6 WebView Handling Error Codes from Web Pages
- 7.6.1 Network Basics for Socket Learning
- 7.6.2 Socket Communication Based on TCP Protocol (1)
- 7.6.3 Socket Communication Based on TCP Protocol (2)
- 7.6.4 Socket Communication Based on UDP Protocol
- 8.1.1 Summary of 13 Drawable Types in Android Part 1
- 8.1.2 Summary of 13 Drawable Types in Android Part 2
- 8.1.3 Summary of 13 Drawable Types in Android Part 3
- 8.2.1 Comprehensive Guide to Bitmap (Bitmap) Part 1
- 8.2.2 OOM Issues Caused by Bitmap
- 8.3.1 Detailed Explanation of Three Drawing Tools
- 8.3.2 Practical Examples of Drawing Classes
- 8.3.3 Paint API — MaskFilter (Mask)
- 8.3.4 Paint API — Xfermode and PorterDuff Detailed Explanation (Part One)
- 8.3.5 Paint API - Xfermode and PorterDuff Explained (Part 2)
- 8.3.6 Paint API - Xfermode and PorterDuff Explained (Part 3)
- 8.3.7 Paint API - Xfermode and PorterDuff Explained (Part 4)
- 8.3.8 Paint API - Xfermode and PorterDuff Explained (Part 5)
- 8.3.9 Paint API - ColorFilter (Color Filter) (1/3)
- 8.3.10 Paint API - ColorFilter (Color Filter) (2/3)
- 8.3.11 Paint API - ColorFilter (Color Filter) (3/3)
- 8.3.12 Paint API - PathEffect (Path Effect)
- 8.3.13 Paint API - Shader (Image Rendering)
- 8.3.14 Paint API - Enumerations/Constants and ShadowLayer Shadow Effect
- 8.3.15 Paint API - Typeface (Font Style)
- 8.3.16 Canvas API Explained (Part 1)
- 8.3.17 Canvas API Explained (Part 2) - Clipping Methods
- 8.3.18 Canvas API Explained (Part 3) - Matrix and drawBitmapMesh
- 8.4.1 Android Animation Collection - Frame Animation
- 8.4.2 Android Animation Collection - Tween Animation
- 8.4.3 Android Animation Collection - Property Animation - Introduction
- 8.4.4 Android Animation Collection - Property Animation - Further Insights
- 9.1 Using SoundPool to Play Sound Effects (Duang~)
- 9.2 MediaPlayer to Play Audio and Video
- 9.3 Using Camera to Take Photos
- 9.4 Using MediaRecord to Record Audio
- 10.1 TelephonyManager (Phone Manager)
- 10.2 SmsManager (SMS Manager)
- 10.3 AudioManager (Audio Manager)
- 10.4 Vibrator (Vibrator)
- 10.5 AlarmManager (Alarm Service)
- 10.6 PowerManager (Power Service)
- 10.7 WindowManager (Window Management Service)
- 10.8 LayoutInflater (Layout Service)
- 10.9 WallpaperManager (Wallpaper Manager)
- 10.10 Sensor Topic (1) - Introduction
- 10.11 Sensor Topic (2) - Orientation Sensor
- 10.12 Sensor Topic (3) - Accelerometer/Gyroscope Sensor
- 10.12 Sensor Topic (4) - Understanding Other Sensors
- 10.14 Android GPS Introduction
- 11.0 "2015 Latest Android Basic Tutorial" Concludes
- 12.1 Android Practice: DrySister App (Version 1) - Project Setup and Basic Implementation
- 12.2 DrySister App (Version 1) - Parsing Backend Data
- 12.3 DrySister App (Version 1) - Image Loading Optimization (Building an Image Cache Framework)
- 12.4 DrySister App (Version 1) - Adding Data Caching (Introducing SQLite)
- 12.5 DrySister App (Version 1) - Code Review, Adjustments, and Logging Class
- 12.6 DrySister App (Version 1) - Icon Creation, Obfuscation, Signing, APK Slimming, App Release
WeChat Subscription
English: