Basic Android tutorial-10.3 AudioManager (audio manager)

Source: Internet
Author: User

Basic Android tutorial-10.3 AudioManager (audio manager)
Basic Android tutorial-10.3 AudioManager (audio manager)

Tags (separated by spaces): basic Android tutorial

This section introduces:

In the first section of multimedia, we wrote a Duang example using SoundPool. After clicking a button, pig suddenly issued a "Duang"
At that time, my voice was so loud that I was scared to death. Fortunately, I did not go to work, but secretly wrote a blog to the manager during work hours.
Will die ~ Well, okay. When it comes to the sound size, we need to introduce the APIs that Android provides for us (Volume Control:
AudioManager)This class is located under the Android. Media package and provides volume control and ringtone mode operations!
In this section, we will learn how to use this stuff. You can write a Demo, a simple mute, every time before watching a movie, first
In the Demo, click the mute button, and then, just say it ~ Well, let's not talk much about it. Let's start this section!
Official API documentation: 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 ):
Controls the volume of the mobile phone, increases or decreases by one unit, and determines based on the first parameter.
AudioManager. ADJUST_LOWER, Which can be up to one unit;
AudioManager. ADJUST_RAISE, Which can be up to one unit AdjustStreamVolume(Int streamType, int direction, int flags ):
The same as above, but you can select the adjusted sound type.
1) The streamType parameter specifies the sound type, which has the following types:
STREAM_ALARM: Mobile phone alert STREAM_MUSIC: Mobile music
STREAM_RING: Ringtone STREAM_SYSTEAM: Mobile Phone System
STREAM_DTMF: Tone STREAM_NOTIFICATION: System prompt
STREAM_VOICE_CALL: Voice phone
2) The second parameter is the same as the one above.
3) Optional flag spaces, such as AudioManager. FLAG_SHOW_UI, Displays the progress bar, AudioManager. PLAY_SOUND: Playing Sound SetStreamVolume(Int streamType, int index, intflags): directly set the volume. GetMode(): Returns the current audio mode. SetMode(): Set the sound mode.
There are the following modes:
MODE_NORMAL(Normal ), MODE_RINGTONE(Ringtones ),
MODE_IN_CALL(CALL ), MODE_IN_COMMUNICATION(Call) GetRingerMode(): Returns the current ringtone mode. SetRingerMode(Int streamType): Set the ringtone mode.
There are the following modes:
For example RINGER_MODE_NORMAL(Normal ), RINGER_MODE_SILENT(Mute ), RINGER_MODE_VIBRATE(Vibration) GetStreamVolume(Int streamType ):
Obtains the current volume of the mobile phone. The maximum value is 7 and the minimum value is 0. When it is set to 0, it is automatically adjusted to the vibrate mode. GetStreamMaxVolume(Int streamType): obtains the maximum volume of a mobile phone sound type. SetStreamMute(Int streamType, boolean state): Set the voice type of the phone to mute. SetSpeakerphoneOn(Boolean on): Set whether to enable the loudspeaker. SetMicrophoneMute(Boolean on): sets whether to mute the microphone. IsMicrophoneMute(): Determines whether the microphone is muted or Enabled IsMusicActive(): Determines whether music is active. IsWiredHeadsetOn(): Determine whether the headset is inserted

Other methods:

AbandonAudioFocus(AudioManager. OnAudioFocusChangeListenerl): discard audio focus AdjustSuggestedStreamVolume(Int, int suggestedStreamType intflags ):
Adjust the volume of the most relevant stream, or specify the rollback stream. GetParameters(String keys): Set a varavisible value for the audio hardware. GetVibrateSetting(Int vibrateType): returns whether the user's vibration is set to the vibration type. Isw.tha2dpon(): Check whether the A2DP Bluetooth headset audio route is enabled or disabled. IsBluetoothScoAvailableOffCall(): Shows whether the current platform supports using SCO to close call cases. Isw.thscoon(): Check whether the communication uses the Bluetooth SCO LoadSoundEffects(): Load the sound effect PlaySoundEffect(Int volume tType, float volume): Playing Sound Effects EgisterMediaButtonEventReceiver(ComponentName eventReceiver ):
Register a unique receiver with MEDIA_BUTTON intent RequestAudioFocus(AudioManager. OnAudioFocusChangeListener l, int streamType, int durationHint)
Request audio focus Setjavasthscoon(Boolean on): requires communication using Bluetooth SCO headphones Startbluw.thsco/stopw.thsco ()(): Start/stop the Bluetooth SCO audio connection UnloadSoundEffects(): Uninstall sound effects
3. Example

Hey, there are a lot of attributes, and some also involve Bluetooth. Here we will only explain some of the most common methods!
We have encountered some special things we have never seen before. Let's look at the document again!
Simple Example: Use Mediaplayer to play music and use AudioManager to adjust the volume and mute!
By the way, create a raw folder under res and drop an MP3 resource file in it!

Run:

Code Implementation:

Layout codeActivity_main.xml:


  
   
   
   
   
    

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; // define a flag to indicate whether the mute button is clicked. private int flag = 1; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // obtain the audio object aManager = (AudioManager) getSystemService (Service. AUDIO_SERVICE); // initialize the mediaplayer object. Here, the mp3 resource mePlayer = MediaPlayer in the raw file is played. create (MainActivity. this, R. raw. countingstars); // set loop playback: 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); listener (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 to adjust the audio of the music, increase the volume, and display the volume chart to indicate aManager. adjustStreamVolume (AudioManager. STREAM_MUSIC, AudioManager. ADJUST_RAISE, AudioManager. FLAG_SHOW_UI); break; case R. id. btn_lower: // specify to adjust the audio of the music and reduce the volume. Only the sound is displayed, and the figure bar aManager is not displayed. adjustStreamVolume (AudioManager. STREAM_MUSIC, AudioManager. ADJUST_LOWER, AudioManager. FLAG_PLAY_SOUND); break; case R. id. btn_quite: // specify the audio for music adjustment. Determine whether to mute the flag * =-1 based on isChecked; if (flag =-1) {aManager. setStreamMute (AudioManager. STREAM_MUSIC, true); // API 23 expired--// aManager. adjustStreamVolume (AudioManager. STREAM_MUSIC, AudioManager. ADJUST_MUTE, // AudioManager. FLAG_SHOW_UI); // use this btn_quite.setText (cancel mute) for Versions later than 23;} else {aManager. setStreamMute (AudioManager. STREAM_MUSIC, false); // API 23 expired--// aManager. adjustStreamVolume (AudioManager. STREAM_MUSIC, AudioManager. ADJUST_UNMUTE, // AudioManager. FLAG_SHOW_UI); // use this aManager for Versions later than 23. setMicrophoneMute (false); btn_quite.setText (mute);} break ;}}}

The code is still very simple. In addition, you can set the mute method.SetStreamMute() Expired in API 23,
You can use another method adjustStreamVolume (int, int, int), and set the third property:
ADJUST_MUTEOrADJUST_UNMUTE!
By the way, there are:
IfAdjustStreamVolumeThe third parameter of () You set Vibrator ),
You need to add this permission in AndroidManifest. xml!
<Uses-permission android: name = "android. permission. VIBRATE"/>

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.