Manage audio playback (from the official Android training course Chinese version (v0.9.5))

Source: Internet
Author: User

Written by: Kesenhoo-Original: http://developer.android.com/training/managing-audio/index.html

If our app is capable of playing audio, it's important to let users control the audio in the way they expect. To ensure a good user experience, we should allow the app to manage the current audio focus, as this will ensure that multiple apps don't play audio together at the same time.

In this series of lessons, we will create an app that responds to the volume buttons that request audio focus when the audio is played, and respond correctly when the current audio focus is changed by the system or other application.

Lessons
    • Control volume and audio playback (controlling Your App ' s Volume and Playback)

      Learn how to make sure that users can adjust the volume of your app through a hardware or software volume controller (usually these controllers also have function keys such as play, stop, pause, skip, and playback).

    • Managing audio focus (Managing)

      Because there may be multiple apps that have the ability to play audio, it's important to consider how they interact. To prevent multiple music apps from playing audio at the same time, Android uses audio focus to control the playback of audio. In this lesson, you can learn how to request audio focus, monitor the loss of audio focus, and how to respond when this happens.

  • Compatible audio output devices (dealing with audio outputs Hardware)

    Audio has a variety of output devices that you can learn in this lesson about how to find the device that plays the audio, and what happens when the headset is unplugged during playback.

    Control volume and audio playback

    Written by: Kesenhoo-Original: http://developer.android.com/training/managing-audio/volume-playback.html

    A good user experience should be predictable and controllable. If our app can play audio, then obviously we need to be able to control the volume through hardware buttons, software buttons, Bluetooth headsets, etc. Likewise, we need to be able to play (play), Stop (stop), pause (pause), skip, and play back (Previous) on the audio stream of the app, and make sure it's correct.

    Identify which audio stream is used (Identify which audio stream to use)

    To create a good audio experience, we first need to know which audio streams the app will use. Android for playing music, alarms, notification bells, call sounds, system sounds, call sounds and dial sound are maintained separately by a separate audio stream. The main purpose of this is to allow the user to individually control different kinds of audio. Most of the above audio types are restricted by the system. For example, unless your app needs to do an alarm-replacement ringtone, you can only play your audio through stream_music.

    Use the hardware volume keys to control the volume of the app (using Hardware Volume keys to control Your app's Audio Volume)

    By default, pressing the volume Control key adjusts the currently activated audio stream, and if our app does not currently play any sound, pressing the volume key will adjust the ringing volume. For a game or music player, even if there is no sound between the songs, or if the current game is in a silent state, the user presses the volume key, which usually means that they want to adjust the volume of the game or music. You may want to adjust the volume of the audio stream by listening for events that are pressed by the volume key. Actually, we don't have to do that. Android provides the Setvolumecontrolstream () method to directly control the specified audio stream. After identifying which audio stream the application will use, we need to call the method at an early stage of the application's life cycle, because the method needs to be called only once during the activity's lifetime, usually in the activity or fragment onCreate() that is responsible for controlling the multimedia. method to call it. This ensures that the audio control functions are consistent with the user's expectations, regardless of whether the app is currently visible or not.

    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    Since then, regardless of whether the target activity or fragment is visible, pressing the volume key of the device can affect the audio stream we specify (in this case, the audio stream is "music").

    Use the playback control keys of your hardware to control the audio playback of your app (using Hardware Playback control keys to control Your app S audio Playback)

    Many of the online or wireless headsets will have many media play control buttons, such as: Play, stop, pause, skip, and replay. The system broadcasts a intent with Action_media_button, regardless of whether the user presses any of the control buttons on the device. In order to respond correctly to these operations, you need to register a broadcastreceiver for the action in the manifest file, as follows:

    < Receiver  android:name  = ". Remotecontrolreceiver ";  < Intent-filter ;  android:name  = " Android.intent.action.MEDIA_BUTTON "/>  </intent-filter ;  receiver ;   

    In receiver implementation, it is necessary to determine which button the broadcast comes from, intent through extra_key_event This KEY contains this information, in addition, the KeyEvent class contains a series KEYCODE_MEDIA_* of static variables such as to represent different media buttons, such as Keycode_media_play_pause and Keycode_media_next.

     Public  class remotecontrolreceiver extends broadcastreceiver {@Override    Public   void onreceive(context context, Intent Intent) {if(Intent.ACTION_MEDIA_BUTTON.equals (Intent.getaction ())) {KeyEvent event = (keyevent) Intent.getparcelableextra (intent.extra_key_event);if(Keyevent.keycode_media_play = = Event.getkeycode ()) {//Handle key Press.}        }    }}

    Because there may be multiple programs listening to events related to media buttons, we must control when the app receives related events in the code. The following example shows how to use Audiomanager to register the Listener and Unmute Media button events for our application, which will be the only receiver capable of responding to media button broadcasts when receiver is registered.

    AudioManager am = mContext.getSystemService(Context.AUDIO_SERVICE);...// Start listening for button pressesam.registerMediaButtonEventReceiver(RemoteControlReceiver);...// Stop listening for button pressesam.unregisterMediaButtonEventReceiver(RemoteControlReceiver);

    Typically, applications need to unregister for monitoring when they lose focus or are not visible (such as in the OnStop () method). But it's not that simple for media playback apps, and in fact it's extremely important to still be able to respond to media play button events when the app is not visible (it can't be controlled by a visible UI control). To achieve this, there is a better way for us to register and cancel the listener for the Audio button event when the program gets lost with the audio focus. This content will be explained in detail in the following course.

    Managing Audio Focus

    Written by: Kesenhoo-Original: http://developer.android.com/training/managing-audio/audio-focus.html

    Since there may be multiple apps that can play audio, we should consider how they should interact. To prevent multiple music playback apps from playing audio at the same time, Android uses audio focus to control the playback of audio-that is, only apps that get audio focus can play audio.

    Before our app starts playing audio, it needs to request the audio focus before it gets to the audio focus. In addition, it needs to know how to listen for events that have lost audio focus and respond appropriately.

    Request for Audio focus

    Before our app starts playing audio, it needs to get the audio focus of the audio stream that will be used. By using the Requestaudiofocus () method, we can get the focus of the audio stream we want to get. If the request succeeds, the method returns audiofocus_request_granted.

    In addition we must specify the audio stream being used, and we need to determine whether the requested audio focus is transient (Transient) or permanent (Permanent).

      • Short Focus Lock: used when planning to play a short audio (for example, play navigation instructions).
      • Permanent focus Lock: used when you plan to play a longer but predictable audio (such as playing music).

    The following code snippet is an example of a request for permanent audio focus when playing music, and we must request the audio focus immediately before starting the playback, for example, before the user clicks the play or the next level of background music in the game begins.

    audiomanager am = Mcontext.getsystemservice (Context.AUDIO_SERVICE) ;... //Request audio focus for playback                                  int  result = Am.requestaudiofocus (Afchangelistener,                                 //Request permanent focus.  audiomanager.audiofocus_gain); if  (Result = = audiomanager.audiofocus_request_granted)    {am.registermediabuttoneventreceiver (remotecontrolreceiver); //Start playback. }  

    Once the playback is finished, you need to make sure that the Abandonaudiofocus () method is called. This is equivalent to informing the system that we no longer need to get the focus and unregister the associated Audiomanager.onaudiofocuschangelistener listener. For another situation that releases the momentary audio focus, this allows any app that we interrupt to continue playing.

    // Abandon audio focus when playback complete    am.abandonAudioFocus(afChangeListener);

    When requesting a short audio focus, we can choose whether to turn on "ducking". Typically, an app turns off its playback sound as soon as it loses its audio focus. If we choose to turn on ducking when we request a short audio focus, it means that the other app can continue playing, just to lower its volume at this point, until it returns to the normal volume after the audio focus is regained (that is, ignore the short-focus request, This does not interrupt the audio that is currently playing. For example, when playing music suddenly appeared a short text message prompt sound, at this time only the volume of the song temporarily lowered, so that users can hear the message prompt sound, after which immediately resume normal playback).

    // Request audio focus for playbackint result = am.requestAudioFocus(afChangeListener,                             // Use the music stream.                             AudioManager.STREAM_MUSIC,                             // Request permanent focus.                             AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {    // Start playback.}

    The ducking is particularly suitable for applications that intermittently use audio focus, such as voice navigation.

    If another application requests the audio focus as described above, the persistent audio focus it requests or the short audio focus (which supports ducking or does not support ducking) will be received by the listener that you registered when requesting the audio focus.

    Handling lost Audio focus (Handle the Loss of audio focus)

    If you apply a request to get the audio focus, the focus of a gets lost when application B requests the audio focus. How you respond to a lost focus event depends on how you lose focus.

    In the listener for the audio focus, the Onaudiofocuschange () callback method is triggered when the event that describes the focus change is accepted. As mentioned earlier, there are three types of focus, we also have three types of loss of focus: permanent loss, short-term loss, allowing ducking's momentary loss.

      • Short Focus: Usually we pause the playback of the current audio or lower the volume when we lose the short focus, and we need to be ready to resume playback after the focus is regained.

      • Lose permanent focus: Suppose another app starts playing music, then our app should stop itself effectively. In a real-world scenario, this means stopping playback, removing the media button listener, allowing the new audio player to uniquely listen for those button events, and discard its own audio focus. At this point, if you want to restore your audio playback, we need to wait for a specific user behavior to occur (for example, by pressing the play button in our app).

    In the following code snippet, if the loss of focus is transient, we pause the audio playback object and restore it after the focus is regained. If there is a permanent focus loss event, then our media button listener will be logged out and no longer listen for changes in the audio focus.

    Onaudiofocuschangelistener Afchangelistener =NewOnaudiofocuschangelistener () {Public   void onaudiofocuschange(int focuschange) {if(Focuschange = = Audiofocus_loss_transient//Pause playback} Else if (focuschange = = audiomanager.audiofocus_gain) {//Resume playback} Else if (focuschange = = Audiomanager.audiofocus_loss) {am.unregistermediabuttoneventreceiver (remotecontrolreceiver); Am.abandonaudiofocus (Afchangelistener);//Stop playback}    }};

    In the example where the short focus is lost, if ducking is allowed, we can choose to use "ducking" in addition to pausing the current playback.

    duck!

    When using ducking, the normally played songs will reduce the volume to highlight this short audio sound, so that this short-term sound is more prominent, without interrupting the normal sound.

    The following code snippet lets our player lower the volume when the audio focus is temporarily lost and restores the original volume after the audio focus has been regained.

    onaudiofocuschangelistener Afchangelistener = new  Onaudiofocuschangelistener () {public  void  onaudiofocuschange  int  Focuschange)  {if  (Focuschange = = Audiofocus_loss_transient_can_duck) { //Lower the volume } else   If   (Focuschange = = Audiomanager.audiofocus_gain)   {  //Raise it back to normal }}; 

    The loss of audio focus is one of the most important event broadcasts we need to respond to, but there are many other important broadcasts that we need to respond to correctly. The system broadcasts a series of intent to inform you of the various changes in the audio process that the user is using. The next lesson will show you how to listen to these broadcasts and improve the overall user experience.

    Compatible Audio output devices

    Written by: Kesenhoo-Original: http://developer.android.com/training/managing-audio/audio-output.html

    When a user wants to listen to music from an Android device, he can have a variety of options, most of which have built-in speakers, wired headphones, and many other devices that support Bluetooth connectivity, and some even support the A2DP Bluetooth audio transfer model contract. A2DP full name is the Advanced Audio distribution profile Bluetooth Audio transmission model Agreement! A2DP is able to use the chip inside the headset to stack data to achieve high-definition sound. The headset with A2DP is a Bluetooth stereo headset. Sound can reach 44.1kHz, the average headset can only reach 8kHz. If your phone supports Bluetooth, you can use the A2DP headset as long as the A2DP protocol is loaded. There are also consumers see the technical parameters mentioned Bluetooth V1.0 V1.1 V1.2 V2.0-These are the technical versions of Bluetooth, refers to the speed of transmission through Bluetooth, whether they support A2DP specifically to see whether Bluetooth product manufacturers use this technology. from Baidu Encyclopedia)

    Detecting hardware devices currently in use (check what Hardware is Being used)

    Playing sounds with different hardware can affect the behavior of your app. You can use Audiomanager to query whether the current audio is output to the speakers, wired headphones, or Bluetooth, as shown below:

    if (isBluetoothA2dpOn()) {    // Adjust output for Bluetooth.else if (isSpeakerphoneOn()) {    // Adjust output for Speakerphone.else if (isWiredHeadsetOn()) {    // Adjust output for headsetselse {     // If audio plays and noone can hear it, is it still playing?}
    Handles changes to audio output devices (Handle changes in the audio outputs Hardware)

    When the wired headset is unplugged or the Bluetooth device is disconnected, the audio stream is automatically output to the built-in speakers. Assuming the sound is loud, this time suddenly turning to the speaker will appear very noisy.

    Fortunately, the system broadcasts a intent with action_audio_becoming_noisy in this case. Whenever audio is played, we should register a broadcastreceiver to listen to this intent. When you use a music player, users will typically want to be able to pause the current song's playback at this time. In the game, users usually want to reduce the amount of bass.

    Private  class noisyaudiostreamreceiver extends broadcastreceiver {@Override    Public   void onreceive(context context, Intent Intent) {if(AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals (Intent.getaction ())) {//Pause the playback}    }}PrivateIntentfilter Intentfilter =NewIntentfilter (Audiomanager.action_audio_becoming_noisy); private void startplayback() {Registerreceiver (Mynoisyaudiostreamreceiver (), intentfilter);} private void stopplayback() {unregisterreceiver (mynoisyaudiostreamreceiver);}

Manage audio playback (from the official Android training course Chinese version (v0.9.5))

Related Article

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.