Android Audio Play out Channel

Source: Internet
Author: User

1:7 Mouth 8 Tongue

Speakers, headphones, and earpiece

Is by: Audiomanager.setmode (audiomanager.mode_in_communication)
Audiomanager.setspeakerhponeon (boolean value). These two are set. But some don't seem to support it.

Switch speaker and handset on the M phone cannot switch

Android Audiotrack Audio Playback analysis
When the audio resource is playing, there are frequent conflicts, such as when the music is played, the phone calls,
There is a need for a unified processing strategy for concurrent processing of new messages that require playback. In the development of Android, by configuring different playback interfaces for different scenarios, a unified concurrency policy is implemented at the bottom, allowing developers to focus more on the application itself.
A udiotrack, MediaPlayer, Soundpool, Ringtone, jetplayer, etc. are commonly used in the Android audio processing interface, this article will be for the Audiotrack interface detailed description.
The Audiotrack Audiotrack is used to manage individual audio resources. When constructing a Audiotrack instance, it involves factors such as flow type, sample rate, channel configuration, audio format, buffer size, playback mode, and so on.
Audiotrack supports stream types such as Stream_voice_call, Stream_system, stream_ring, Stream_music, and Stream_alarm.
The Audiotrack supports sample rates of 44100Hz, 22050Hz, and 11025Hz. The audiotrack supports two channels such as Mono (Channel_out_mono), stereo (Channel_out_stereo).
Audiotrack supports two encoding formats such as Encoding_pcm_16bit and Encoding_pcm_8bit.
The Audiotrack supports two modes of playback: static mode (Staticmode) and current (streaming modes).
The static mode, because there is no delay from the Java layer to the original layer to pass the data, the delay is very small, of course, limited by the size of the audio buffer, usually in the game scene for the playback of short audio resources.
Stream mode is used when the audio stream is not large enough to write once in the audio buffer.
The playback states of Audiotrack include playstate_stopped, playstate_paused, playstate_playing, and so on.
The status of Audiotrack instances includes state_initialized, State_no_static_data, state_uninitialized, and so on.
The method to add data to the audio buffer is write ().
When you set the audio buffer, its size is related to the sample rate, channel, and audio format.
The formula is: buffer size = minimum number of frames X (channel ==channel_out_stereo? 2:1) x (audio format = = PCM16?) 2:1) while the minimum frame count is subject to factors such as sample rate and audio device latency.
In addition, in Android 2.3, the concept of session was introduced to facilitate the processing of single sound. The corresponding methods include: Attachauxeffect (), Getaudiosessionid (), Setauxeffectsendlevel () and so on.
The playback progress can be monitored by the audiotrack.onplaybackpositionupdatelistener listener.
The following is a background audio playback process:
Code 10-3 audiotrack playing an audio file


 PublicclassBackgroundaudioextendsThread { PublicStaticFinalintSample_rate = 16000;  PublicStaticFinalintAudio_format = Audioformat.encoding_pcm_16bit; PublicStatic FinalintBytes_per_sample = 2;  PublicStaticFinalintPlayback_stream =Audiomanager.stream_music; PublicBackgroundaudio (byte[] data) {  //Calculate buffer size final int minbuffersize = (buffer_time *sample_rate*bytes_per_sample)/1000; //Calculate minimum buffering for hardwareFinalintMinhardwarebuffersize =audiotrack.getminbuffersize (Sample_rate,audioformat.channel_out_mono,audio_format); Mbuffersize= Math.max (minhardwarebuffersize, minbuffersize);
Maudiotrack =NewAudiotrack (Playback_stream, Sample_rate, Audioformat.channel_out_mono, Audio_format, MBufferSize, AudioTrack.MODE_ STREAM);

if(maudiotrack.getstate () = =audiotrack.state_initialized) {
Writeaudio (); Start (); //start the background thread to push the audio data maudiotrack.play (); } else {LOG.E (TAG, "Error initializing audio track."));
}} ...PrivatevoidWriteaudio () {
intlen = mdata.length;
intcount; intMaxBytes = Math.min (mbuffersize, Len-MPos); Count= Maudiotrack.write (Mdata, MPos, MaxBytes);
if(Count < 0) {log.e (TAG,"Error writing looped audio data");
Halt ();

return;
} MPos+ = count;

if(MPos = =Len) {MPos= 0;//Wraparound
}  } }
media playback Supported media Formats Audio Capture Jetplayer Camera This time I'm going to share some of the media playback and my learning sense.          Enlightenment. The first two classes that need to be contacted by us are MediaPlayer, Mediamanager, respectively. MediaPlayer is used to control audio/video streaming or file playback, we need to note that the MediaPlayer object plus some of its supported playback operations will form a state machine, in an inappropriate state to perform an inappropriate operation will throw an exception,          If the developer does not know which state the MediaPlayer object is currently in, it is very likely that the wrong method will cause the program's exception, and these errors are difficult to detect, so error handling is particularly important in this section. The following is the audio Focus, for example, when you listen to the song, suddenly came a text message, if not added processing, the voice of the message is likely to be the music of the Sound of oblivion, you will not notice. What do we want to happen? We hope that this time the sound of music is slightly lower than before so that we can hear the text message tone, after the end of the text message prompt sound back to normal.          This process is the process of acquiring and releasing audio focus.  While writing the code, I overlooked one point: Audio Focus is cooperative in nature. Request audio Focus [Java] View Plaincopyprint? Audiomanager Audiomanager =(Audiomanager) Getsystemservice (Context.audio_service); intresult = Audiomanager.requestaudiofocus ( This, Audiomanager.stream_music, Audiomanager.audiofocus_gain); Audiomanager Audiomanager=(Audiomanager) Getsystemservice (Context.audio_service); intresult = Audiomanager.requestaudiofocus ( This, Audiomanager.stream_music, Audiomanager.audiofocus_gain); Handling the focus Change event [Java] View Plaincopyprint?classMyServiceextendsServiceImplementsAudiomanager.onaudiofocuschangelistener {// ....          Public voidOnaudiofocuschange (intFocuschange) {            //Do something based in focus change ...    }    }    classMyServiceextendsServiceImplementsAudiomanager.onaudiofocuschangelistener {// ....       Public voidOnaudiofocuschange (intFocuschange) {          //Do something based in focus change ...}} Applying for audio focus and dealing with focus change must have been implemented with each other, and I started by writing a service to play the music, but I didn't apply for audio focus until the start function was called, but I realized Onaudi The Ofocuschange function. I expect the service to stop playing when the focus change occurs, but I find that when another service applies to audio focus, the previous service will not have the music stop playing. Android training, on the choice of Chengdu Dahne, the best Chengdu software training institutions, if you have "how much money in the training needs", "How to train" and other issues, for details, please consult Danek (http://www.sctarena.com), we will give you a detailed explanation. 

Android handset playing music

// set as a call. or this code, but remember to add permission Android.permission.MODIFY_AUDIO_SETTINGS there is a point to pay attention to, after the play is finished need Audiomanager.setmode ( Audiomanager.mode_normal); otherwise the software will be playing the handset.

In practice, just the above code is not the implementation requirement:

Glory: 4. 2.2

Kernel 3.4.5


Audiomanager.setmode (Audiomanager.mode_in_call);

Nexus 5 5.0.1

Kernel 2.4.0

Audiomanager.setmode (Audiomanager.mode_in_call); cannot take effect even though adding the line still broadcasts from the speaker

2: Application Scenario

Audio output channels are many, Speaker, headset, Bluetooth A2DP and so on.

Audio output channel switching may occur during calls or music playback using the audio output. For example, when you insert a wired headset to play music, the sound is emitted from the headset, and when you unplug the headset, the audio output channel switches. If the music player does not process, the audio output is switched to the speaker, and the sound is sent directly from the speaker.

In Android, you can query the current audio output by Android.media.AudioManager and capture and handle this change as the audio output changes.

First, audio output status query and control

Android.media.AudioManager provides the following methods that can be used to query the status of the current audio output:

    • isbluetootha2dpon (): Check whether the A2dpaudio through the Bluetooth headset;
    • Isspeakerphoneon (): Check if the speaker is open;
    • Iswiredheadseton (): Check whether the line control headset is attached; Note that this method is only used to determine if the headset is plugged in, and it cannot be used to determine that the current audio is output through the headset, which also relies on other conditions.

There are also some setxyz () methods for setting these audio outputs, which are not called directly by applications that generally use audio output, and they are managed by the system to automatically switch audio output channels. Unless the interface is provided to the user to switch the menu or button, and the user chooses to change, for example, to directly select the speaker voice, you can call Setspeakerphoneon () directly.

Second, the audio output channel switching event capture and processing

The audio output path will automatically switch because the headset is plugged in and the Bluetooth headset is disconnected. The program that is playing audio at this time is notified of the occurrence of this event. Android is broadcast action_audio_becoming_noisy this intent notification.

A good way to handle broadcasts is to dynamically register/unregister the broadcasts that you care about. The following code shows the receiver that registers the broadcast when it starts playing, and the receiver that unregisters the broadcast when it stops playing. The audio output channel switching process is to pause the current playback, not directly from the new channel to make noise.

Private classNoisyaudiostreamreceiverextendsBroadcastreceiver {@Override Public voidOnReceive (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 voidStartplayback () {Registerreceiver (Mynoisyaudiostreamreceiver (), intentfilter);}Private voidStopplayback () {unregisterreceiver (mynoisyaudiostreamreceiver);}

Iii. typical scenario for audio output channel switching--unplug headphones when listening to music with headphones

When listening to music, the headset does not unplug the timing diagram as follows:

In the diagram:

    • Audionoisy client registered for listening broadcast audiomanager.action_audio_becoming_noisy[step#1 ~ #2];
    • Always listen to music with headphones;
    • Headsetobserver has been monitoring the changes in headset status. When the headset is unplugged, the broadcast audiomanager.action_audio_becoming_noisy[step#3~4] is detected;
    • The Audionoisy client receives the broadcast and sends a pause command to Mediapaybackservice to pause the current playback [step#5~6].

3:android Document building Apps with multimedia

These classes teach you "to" create rich multimedia apps that behave the "the".

  1. managing audio Playback
     if your app plays Audio, it ' s important that your users can Control the audio in a predictable manner. To ensure a great user experience, it's also important that your app manages the audio focus to ensure multiple apps aren ' T playing audio at the same time. After  this  class , you'll be able To build apps this respond to hardware audio key presses, which request audio focus when playing audio, and which respond Appropriately to changes in audio focus caused by the system or other applications. 
      

     


  2. How to respond to hardware audio key presses, request for audio focus when playing audio, and respond appropriately to changes In audio focus.

    1. Controlling Your App ' s Volume and Playback
    2. Managing Audio Focus
    3. Dealing with Audio Output Hardware

Reference:

http://blog.csdn.net/thl789/article/details/7423523

Android Audio Play out Channel

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.