An analysis of the Android Framework Audio Management Audiomanager (cont.)

Source: Internet
Author: User

Above two simple analysis, the framework of the Android System for volume adjustment of the part of the code, there may be some deeper things are not involved, because the first attempt to analyze, not everything can be fully understood and thorough understanding, So for the time being I can only understand and use the part of the analysis.

This article mainly wants to analyze the part content and usage of the audio competition mechanism in Audiomanager.

First of all, the reason for this competition mechanism, according to my understanding, because there are many types of audio in the Android system, and they remain independent of each other, and do not affect each other. such as music sound, key touch sound, ringing sound, call sound, Bluetooth call sound, error alarm sound and so on. There will be a sound type of response. As a result, they also have independent audio streams to control playback. In order to prevent these sounds will affect each other, the competition mechanism has been produced, this mechanism effectively control the playback of this part of the priority has been mutually exclusive, coexistence and other independent relationship, each audio stream will be played through this mechanism to obtain the broadcast license, so that it can be monitored status, easy to manage.

For this mechanism, the core content is the management of audio focus.

Part of the code is posted below

    /** * Used to indicate a gain of audio focus, or a request for audio focus, of unknown duration. * @see onaudiofocuschangelistener#onaudiofocuschange (int) * @see #requestAudioFocus (onaudiofocuschangelistener, int,    int) */public static final int audiofocus_gain = 1; /** * Used to indicate a temporary gain or request for audio focus, anticipated to last a short * amount of time.     Examples of temporary changes is the playback of driving directions, or an * event notification. * @see onaudiofocuschangelistener#onaudiofocuschange (int) * @see #requestAudioFocus (onaudiofocuschangelistener, int,    int) */public static final int audiofocus_gain_transient = 2;  /** * Used to indicate a temporary request for audio focus, anticipated to last a short * amount of time, and where It is acceptable for other audio applications to keep playing * after have lowered their output level (also Referre     D to as "ducking"). * Examples of TempoRary changes is the playback of driving directions where playback of music * in the background is acceptable. * @see onaudiofocuschangelistener#onaudiofocuschange (int) * @see #requestAudioFocus (onaudiofocuschangelistener, int,    int) */public static final int audiofocus_gain_transient_may_duck = 3;     /** * Used to indicate a loss of audio focus of unknown duration. * @see onaudiofocuschangelistener#onaudiofocuschange (int) */public static final int audiofocus_loss =-1 * audiofo    Cus_gain;     /** * Used to indicate a transient loss of audio focus.  * @see onaudiofocuschangelistener#onaudiofocuschange (int) */public static final int audiofocus_loss_transient = 1    * Audiofocus_gain_transient; /** * Used to indicate a transient loss of audio focus where the loser of the audio focus can * lower its output v  Olume if it wants to continue playing (also referred to as "ducking"), as * The new focus owner doesn ' t require others To IS Silent. * @see onaudiofocuschangelistener#onaudiofocuschange (int) */public static final int Audiofocus_loss_transient_can_ DUCK =-1 * audiofocus_gain_transient_may_duck;
The above code is also present in the Android\frameworks\base\media\java\android\media\audiomanager.java, and the partial definition is given first.

Audiofocus_gain-persistent focus, see the Notes section for a longer period of time to play audio, before the audio focus user needs to stop the sound.

Audiofocus_gain_transient--transient focus, used to play a very short time of audio, before the focus user needs to pause the sound.

Audiofocus_gain_transient_may_duck---transient focus, used to play short time audio, before the audio focus users need to lower their own volume.

Audiofocus_loss-Loses focus, indicating that the user of the persistent focus loses the audio focus.

Audiofocus_loss_transient-Loses focus, indicating that the user of the transient focus loses the audio focus.

Audiofocus_loss_transient_can_duck-Loses focus, indicating that the user of the focus of the transient focus, which lowers its own volume, loses the audio focus.

The above definitions are the parameters that need to be specified when the audio focus is requested, and then the request to continue parsing the audio focus.

    /** * A failed focus change request.    */public static final int audiofocus_request_failed = 0;     /** * A successful focus change request.    */public static final int audiofocus_request_granted = 1;     /** * Request Audio focus. * Send a request to obtain the audio focus * @param l The Listener-be notified of audio focus changes * @par Am Streamtype The main audio stream type affected by the focus request * @param durationhint use {@link #AUDIOFOCUS_G Ain_transient} to indicate this focus request * is temporary, and focus would be abandonned shortly.     Examples of Transient Requests is * for the playback of driving directions, or notifications sounds. * Use {@link #AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK} to indicate also that it's OK for * the previous focus own     Er to keep playing if it ducks it audio output. * Use {@link #AUDIOFOCUS_GAIN} for a focus request of unknown duration such * as The playback of a song or a video. * @return {@link #AUDIOFOCUS_REQUEST_FAILED} or {@link #AUDIOFOCUS_REQUEST_GRANTED} */public int REQUESTAUDIOFOCU        S (onaudiofocuschangelistener l, int streamtype, int durationhint) {int status = audiofocus_request_failed; if ((Durationhint < audiofocus_gain) | |        (Durationhint > Audiofocus_gain_transient_may_duck))            {LOG.E (TAG, "Invalid duration hint, audio focus request denied");        return status;        } registeraudiofocuslistener (L);        TODO protect request by permission check?        Iaudioservice service = GetService (); try {status = Service.requestaudiofocus (Streamtype, Durationhint, Micallback, MAUDIOFOCUSDI        Spatcher, Getidforaudiofocuslistener (L), mcontext.getpackagename ()/* Package name */);        }catch (RemoteException e) {log.e (TAG, "Can ' t call Requestaudiofocus () in Audioservice due to" +e); }        return status; }/** * @hide * Used internally by telephony package to request audio focus.     Would cause the focus request * to being associated with the ' voice communication ' identifier only used in Audioservice     * to identify.      * @param streamtype use stream_ring for focus requests when ringing, Voice_call for * The establishment of the call * @param durationhint The type of focus request. Audiofocus_gain_transient is recommended so * Media applications resume after a call */public void Requesta        Udiofocusforcall (int streamtype, int durationhint) {Iaudioservice service = GetService (); try {service.requestaudiofocus (Streamtype, durationhint, micallback, NULL, Audioservice.in_        voice_comm_focus_id, "System"/* dump-friendly Package name */); }catch (RemoteException e) {log.e (TAG, "Can ' t call Requestaudiofocusforcall () on Audioservice due to"+e);     }}/** * @hide * Used internally by telephony package to abandon audio focus, typically after a call or     * When ringing ends and the call are rejected or not answered.     * Should match one or more calls to {@link #requestAudioFocusForCall (int, int)}.        */public void Abandonaudiofocusforcall () {Iaudioservice service = GetService ();        try {service.abandonaudiofocus (null, audioservice.in_voice_comm_focus_id);        } catch (RemoteException e) {log.e (TAG, "Can ' t call Abandonaudiofocusforcall () on Audioservice due to" +e); }}/** * Abandon audio focus.     Causes the previous focus owner, if any, to receive focus.     * @param l the listener with which focus is requested. * @return {@link #AUDIOFOCUS_REQUEST_FAILED} or {@link #AUDIOFOCUS_REQUEST_GRANTED} */public int ABANDONAUDIOFOCU        S (onaudiofocuschangelistener l) {int status = audiofocus_request_failed; UnregisteraudiofoCuslistener (l);        Iaudioservice service = GetService (); try {status = Service.abandonaudiofocus (Maudiofocusdispatcher, Getidforaudiofocuslistener (l        ));        } catch (RemoteException e) {log.e (TAG, "Can ' t call Abandonaudiofocus () on Audioservice due to" +e);    } return status; }
The above code mainly posts a function of two actions to request and release the audio focus, for the request operation

Requestaudiofocus (onaudiofocuschangelistener l, int streamtype, int durationhint) has three parameters

The first parameter: a listener that needs to write an audio focus can be as follows

Onaudiofocuschangelistener Afchangelistener = new Onaudiofocuschangelistener () {public   void Onaudiofocuschange ( int Focuschange) {     if (Focuschange = = audiofocus_loss_transient        //Pause playback     } else if (Focuschange = = Au Diomanager.audiofocus_gain) {       //Resume playback     } else if (Focuschange = = Audiomanager.audiofocus_loss) {       Am.unregistermediabuttoneventreceiver (remotecontrolreceiver);       Am.abandonaudiofocus (Afchangelistener);       Stop playback     }}   ;
The second parameter: the type of audio stream that needs to be developed, such as the Stream_music,stream_ring,stream_system described in the first article, and so on.

The third parameter: This parameter is the first three audio focus types listed at the beginning of this article.

The request function returns audiofocus_request_granted if successful, and returns audiofocus_request_failed

The requested method can be consulted as follows:

Audiomanager am = Mcontext.getsystemservice (context.audio_service); ...     Request audio focus for playback    int result = Am.requestaudiofocus (Afchangelistener,    //Use the music stream.
   audiomanager.stream_music,    //Request permanent focus.    Audiomanager.audiofocus_gain);     if (result = = audiomanager.audiofocus_request_granted) {      am.unregistermediabuttoneventreceiver ( Remotecontrolreceiver);      Start playback.    
Back to success, you can start playing the audio stream we need to play. However, when playback is complete, you must call Abandonaudiofocus () to release the audio focus while you log off

Audiomanager.onaudiofocuschangelistener. This way, when the application releases the audio focus, the other interrupted applications are re-allowed to get the focus to continue playing. As below, you can

   Abandon Audio Focus when playback complete    
When the type of audio focus is described earlier, there are two types of audio focus for transient transients, one that pauses when the focus is lost, and the other is to decrease the playback volume itself when the focus is lost. The purpose of both is to determine whether two audio streams can coexist and have primary or secondary points.

Audiofocus_gain_transient_may_duck This transient audio focus, suitable for short-term warning classes, the broadcast class of audio streams, such as navigation sounds, prompts and so on.

Each time this type of audio focus is requested by another program, it is notified in the listening process, so that we can do the corresponding operation.

For example, when we receive a message like audiofocus_loss_transient, we just temporarily lose the audio focus, and when the other party casts the audio focus, the program will regain the audio focus and resume playing the audio stream. So we should pause the current sound when we receive this message, and then restart playback when we receive a audiofocus_gain message.

When we receive the Audiofocus_loss, we may not be able to get the audio focus again for a long time, and the other side of the program will occupy the audio focus. At this point we need to stop our audio stream playback, stop listening for audio focus, and log off all media button listeners. This is the equivalent of transferring the program to the background and stopping the application. If you need to restore again, you need to reopen the app.

When we receive the Audiofocus_loss_transient_can_duck, we need to reduce our audio playback volume to a certain value, and when we hear Audiofocus_gain again, restore the sound back to the previous value.


The above parsing is the entire audio focus of the request, release, monitoring the operation process. Specific situations need to be selected in the application according to the actual situation to achieve a better experience. In addition, the multimedia button is the Mediabutton of the operation of the monitoring in the source code are mentioned, want to understand the next to understand.

At this point, I understand that part of the audio control source code is over, if there is wrong to inform.

An analysis of the Android Framework Audio Management Audiomanager (cont.)

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.