Android Audiomanager Audiofocus

Source: Internet
Author: User

Now start the module for the music player. Have a few problems

When playing music, to adjust the volume or the ringtone settings in the profile, there are two sounds at the same time.

The solution to this problem is that the music focus is not clear.

Now analyze several attributes of the music focus: source code in Frameworks/base/media/java/andorid/media/audiomanager.java


public static final int audiofocus_none = 0;


Indicates that the requested audio focus does not know how long it will last, usually a long-term possession. acquired the audio Focus;
public static final int audiofocus_gain = 1;

Indicates that the audiofocus to be applied is temporary and will run out very quickly;

public static final int audiofocus_gain_transient = 2;

Not only that the audiofocus to be applied for is temporary. Also indicates that you are currently using Audiofocus to continue playing, just to "duck" (Reduce the volume).

public static final int audiofocus_gain_transient_may_duck = 3;

public static final int audiofocus_gain_transient_exclusive = 4;

Audiomanager.onaudiofocuschangelistener is to monitor the use of Audiofocus after the successful application of listener, perhaps assuming that different programs to compete Audiofocus, This listener Onaudiofocuschange () method is used to inform the user of this audio focus.


Lost audio Focus and will last for a very long time

public static final int audiofocus_loss =-1 * audiofocus_gain;

Temporarily loses audio Focus and will get it again very quickly. Audio playback must be stopped. However, it is possible to get audiofocus again very quickly. This can not release media resources;

public static final int audiofocus_loss_transient =-1 * audiofocus_gain_transient;

Temporarily lost Audiofocus, but can continue to play, just to reduce the volume.

public static final int audiofocus_loss_transient_can_duck =
-1 * AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK;


Take a look at a question that has just been changed:

Description of the problem: when playing music, the alarm clock arrives, put the alarm clock in the background to enter the file Manager to play audio. The alarm clock is still responding, and the alarm clock and music are ringing at the same time;


Problem analysis: When the alarm clock rings, not to do the audio focus of processing

Workaround: Add focus to the Packages/apps/deskclock/src/com/android/deskclock/alarms/alarmklaxon.java file

the modified source code:


Package Com.android.deskclock.alarms;import Android.content.context;import Android.content.res.assetfiledescriptor;import Android.media.audiomanager;import Android.media.MediaPlayer; Import Android.media.mediaplayer.onerrorlistener;import Android.media.ringtonemanager;import Android.net.Uri; Import Android.os.vibrator;import Com.android.deskclock.log;import Com.android.deskclock.r;import Com.android.deskclock.provider.alarminstance;import Java.io.ioexception;/*add by Leo.tan 20140717 for Bugzilla 20064 Start */import android.os.handler;import Android.media.audiomanager.onaudiofocuschangelistener;import Android.os.message;/*add by <span id= "Summary_alias_container" ><span id= "Short_desc_nonedit_display" > </span></span> Leo.tan 20140717 for bugzilla 20064 End *//** * Manages playing ringtone and vibrating the Devi Ce.  */public class Alarmklaxon {private static final long[] Svibratepattern = new long[] {$, $};//Volume suggested By media team for In-call AlarMs.    Private static final float in_call_volume = 0.125f;    private static Boolean sstarted = false; private static MediaPlayer Smediaplayer = Null;/*add by Leo.tan 20140717 for Bugzilla 20064 start */private static final    int focuschange = 3000;    private static final int fadedown = 5;    private static final int fadeup = 6;    private static final int retry_request_focus = 7;    private static final int over_short_vibrator = 8; private static Onaudiofocuschangelistener Maudiofocuslistener = new Onaudiofocuschangelistener () {public void Onau Diofocuschange (int focuschange) {android.util.log.v ("Alarmklaxon", "maudiofocuslistener::focuschange-->" +            Focuschange);        Mhandler.obtainmessage (Focuschange, Focuschange, 0). Sendtotarget (); }};/*add by Leo.tan 20140717 for Bugzilla 20064 end */public static void Stop (context Context) {log.v ("Ala        Rmklaxon.stop () ");            if (sstarted) {sstarted = false; Stop AUdio playing if (smediaplayer! = null) {smediaplayer.stop ();                Audiomanager Audiomanager = (audiomanager) context.getsystemservice (Context.audio_service);                Audiomanager.abandonaudiofocus (NULL);                Smediaplayer.release ();            Smediaplayer = null; }/*add by Leo.tan 20140717 for Bugzilla 20064 start */final Audiomanager Audiomanager = (audiomanager) context.getsystems                        Ervice (Context.audio_service); Audiomanager.abandonaudiofocus (Maudiofocuslistener);/*add by Leo.tan 20140717 for Bugzilla 20064 End */((Vibra        Tor) Context.getsystemservice (Context.vibrator_service)). Cancel ();        }} public static void Start (final context context, alarminstance instance, Boolean Intelephonecall) {        LOG.V ("Alarmklaxon.start ()");        Make sure we is stop before starting stop (context); if (! AlarmInstance.NO_RINGTONE_URI.equALS (Instance.mringtone)) {Uri alarmnoise = Instance.mringtone;            Fall back to the default alarm if the database does not has AN//alarm stored.                if (alarmnoise = = null) {alarmnoise = Ringtonemanager.getdefaulturi (ringtonemanager.type_alarm);                if (LOG.LOGV) {log.v ("Using Default alarm:" + alarmnoise.tostring ());            }}  todo:reuse Mmediaplayer instead of creating a new one and/or use Ringtonemanager.            Smediaplayer = new MediaPlayer (); Smediaplayer.setonerrorlistener (New Onerrorlistener () {@Override public boolean onError (Med Iaplayer MP, int what, Int. extra) {LOG.E ("Error occurred while playing audio.                    Stopping Alarmklaxon. ");                    Alarmklaxon.stop (context);                return true;           }            }); try {//Check if we areIn a call.                If we are, use the in-call alarm//resource at a low volume to not disrupt the call.                    if (Intelephonecall) {log.v ("Using the In-call Alarm");                    Smediaplayer.setvolume (In_call_volume, In_call_volume);                Setdatasourcefromresource (context, Smediaplayer, r.raw.in_call_alarm);                } else {Smediaplayer.setdatasource (context, alarmnoise);            } startalarm (context, smediaplayer);                }catch (Exception ex) {LOG.V ("Using the Fallback ringtone"); The alarmnoise may is on the SD card which could is busy right//now.                Use the fallback ringtone.                    try {//must reset the media Player to clear the error state.                    Smediaplayer.reset ();                    Setdatasourcefromresource (context, Smediaplayer, r.raw.fallbackring); StartalaRM (context, Smediaplayer);                    } catch (Exception ex2) {//AT-this-point we just don ' t play anything.                LOG.E ("Failed to play fallback ringtone", ex2); }}} if (Instance.mvibrate &&!intelephonecall) {Vibrator Vibrator = (Vibrat            OR) Context.getsystemservice (Context.vibrator_service);        Vibrator.vibrate (Svibratepattern, 0);    } sstarted = true;    }//Do the common stuff when starting the alarm. private static void Startalarm (context context, MediaPlayer player) throws IOException {Audiomanager Audiomanager        = (Audiomanager) context.getsystemservice (Context.audio_service);        Do not play alarms if stream volume are 0 (typically because ringer mode is silent). if (Audiomanager.getstreamvolume (audiomanager.stream_alarm)! = 0) {Player.setaudiostreamtype (AudioManager.STRE            Am_alarm);         Player.setlooping (TRUE);   Player.prepare (); Audiomanager.requestaudiofocus (null, Audiomanager.stream_alarm, audiomanager.audiofocus_gain_transient)            ;        Player.start (); }/*add by Leo.tan 20140717 for Bugzilla 20064 start *//Request for focus in this place   final int requestresult = Audiomanag Er.requestaudiofocus (Maudiofocuslistener, Audiomanager.stream_alarm, Audiomanager.audiofocus    _gain_transient);  /*add by Leo.tan 20140717 for Bugzilla 20064 end */} private static void Setdatasourcefromresource (context context, MediaPlayer player, int res) throws IOException {assetfiledescriptor afd = context.getresources (). Open        RAWRESOURCEFD (RES);            if (afd! = null) {Player.setdatasource (Afd.getfiledescriptor (), Afd.getstartoffset (), afd.getlength ());        Afd.close (); }}/*add by Leo.tan 20140717 for Bugzilla 20064 start */private static void SetVolume (Float vol) {if (Smedia PlayeR! = null) {Smediaplayer.setvolume (vol, vol); }}//Use Handler to handle the focus for private static Handler Mhandler = new Handler () {public void Handlemessage (Mess                        Age msg} {switch (msg.what) {case Focuschange: {switch (MSG.ARG1) {                        Case AudioManager.AUDIOFOCUS_LOSS:case Audiomanager.audiofocus_loss_transient: Case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:mHandler.removeMessa                            GES (Fadeup);                            Mhandler.sendemptymessage (Fadedown);                        Break                            Case AudioManager.AUDIOFOCUS_GAIN:mHandler.removeMessages (Fadedown);                            Mhandler.sendemptymessage (Fadeup);                    Break                } break; } Case Fadedown://Turn Off the Sound SetVolume (0.0f);                Break                    Case Fadeup://Turn in the Sound SetVolume (1.0f);            Break  }}};/*add by Leo.tan 20140717 for Bugzilla 20064 end */}<span id= "Summary_alias_container" ></span>





Android Audiomanager Audiofocus

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.