Talk about the headset in iOS development (monitor headphone plug-in, headphone line control)-B

Source: Internet
Author: User
Tags notification center

if one of the most significant accidents occurs in a project, it is no doubt that the developer is using an element that is not controllable.

Objective iOS development in the development of audio and video playback is not uncommon, users often use an output device, that is, "headphones", this blog is about some of the development of headphones related technical points. Detect if the headset is plugged in See above the title of the time must be noted, here is said to "detect whether the headset is plugged in", here is only a one-time detection, not real-timely monitoring headphone plug, but there are some times, the following method is sufficient to meet our development needs. First, We need to import avfoundation.framework this framework as.

Import Avfoundation.framework Framework

Then import the header file to implement the following method
#import <AVFoundation/AVFoundation.h>  //导入头文件- (BOOL)isHeadsetPluggedIn {           AVAudioSessionRouteDescription* route = [[AVAudioSession sharedInstance] currentRoute];           for (AVAudioSessionPortDescription* desc in [route outputs]) {                   if ([[desc portType] isEqualToString:AVAudioSessionPortHeadphones])                           return YES;           }           return NO;   }
Headphone plug-in (iOS6.0 implementation) In fact, these days have been looking at the relevant information on the Internet, found that most of the listening headphone unplugged is some of the old method of iOS6.0 around, we will first give a try to see how iOS6.0 is listening to the headphone unplugged events. First of all, We need to import avfoundation.framework this framework as.

Import Avfoundation.framework Framework

The iOS6.0 headphone is unplugged primarily for avaudiosession singleton objects. AudioSessionAddPropertyListenerThe implementation of this block function is done, and this function is called when the headset is unplugged. Listen to the headphone unplugged event I wrote it directly in the appdelegate. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions, let's take a look at the specific code implementation.
#import "AppDelegate.h" #import <avfoundation/avfoundation.h>//Import header file @interface appdelegate () < Avaudiosessiondelegate> @end @implementation appdelegate-(BOOL) Application: (UIApplication *) application Didfinishlaunchingwithoptions: (nsdictionary *) launchoptions {[[avaudiosession sharedinstance] setDelegate:self]; Initialize the singleton settings agent [[[Avaudiosession sharedinstance] setcategory:avaudiosessioncategoryplayback error:nil];//settings avaudioses Sion the type Audiosessionaddpropertylistener of the Singleton object (Kaudiosessionproperty_audioroutechange, Audioroutechangelistenercallback, (__bridge void *) (self));//Call the block function return YES; }//implementation of the method of block function
void Audioroutechangelistenercallback (void *inuserdata, Audiosessionpropertyid Inpropertyid, UInt32 Inpropertyvaluesize,const void *inpropertyvalue) {   //Ensure that this callback is invoked for a route Chan GE     &NBSP;IF (Inpropertyid! = Kaudiosessionproperty_audioroutechange) return;      {           //determines the reason for the route change, to ensure th At it are not              //     because of a category change.              cfdictionaryref routechangedictionary = (cfdictionaryref) Inpropertyvalue;        cfnumberref routechangereasonref = (cfnumberref) cfdictionarygetvalue ( Routechangedictionary, Cfstr (Kaudiosession_audioroutechangekey_reason));              sint32 Routechangereason;            cfnumbergetvalue (Routechangereasonref, KCfnumbersint32type, &routechangereason);        if (Routechangereason = = kaudiosessionroutechangereason_olddeviceunavailable) {           //handle Headset Unplugged                 &NBSP ; NSLog (@ "no headphones! ");          } else if (Routechangereason = = kaudiosessionroutechangereason_newdeviceavailable) {&N Bsp          //handle Headset plugged in                 &NBS P NSLog (@ "has headphones! ");          }      }  }
Headphone plug-in (Implementation after iOS6.0) In fact, if not a warning complex program ape, the above monitor headphone plug implementation has been fully able to meet the needs of the work, but for me such a warning complex program ape, heart to the above program operation process warning is very offensive, After many methods have been deprecated in the above avaudiosession, we need to use notifications to enable the plug-in of the listening headset. So the following method appears. For convenience, I download the demo's Viewcontroller directly, as above, We need to import the Avfoundation.framework framework. Then we import the header file in Viewcontroller. Then we need to listen for the notification name as follows.
avaudiosessionroutechangenotification//notification name that needs to be monitored
The specific code implementation is as follows.
#import "ViewController.h" #import <AVFoundation/AVFoundation.h> @interface Viewcontroller () @          End@implementation viewcontroller-(void) viewdidload {[Super viewdidload];          [[Avaudiosession sharedinstance] Setactive:yes error:nil];//Create a singleton object and make it active. [[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (audioroutechangelistenercallback:) Name: Avaudiosessionroutechangenotification object:nil];//Settings Notification
}//Notification method implementation-(void) Audioroutechangelistenercallback: (nsnotification*) Notification {           nsdictionary *interuptiondict = Notification.userinfo;            nsinteger Routechangereason = [[Interuptiondict valueforkey: Avaudiosessionroutechangereasonkey] IntegerValue];            switch (Routechangereason) {              &NB Sp    case avaudiosessionroutechangereasonnewdeviceavailable:               & nbsp            nslog (@ "avaudiosessionroutechangereasonnewdeviceavailable");                          tipwithmessage (@ "headphone insert");                            break;                    case AvaudiosessionrOutechangereasonolddeviceunavailable:                            nslog (@ "avaudiosessionroutechangereasonolddeviceunavailable");                 Tipwithmessage (@ "Headphone unplugged, stop playing");                            break;                    case Avaudiosessionroutechangereasoncategorychange:            //called at Start-also if other audio wants to play       &NB Sp                    tipwithmessage (@ " Avaudiosessionroutechangereasoncategorychange ");                            break;        }//All observers are removed from the Dealloc method whenever a notification center appears.-(void) dealloc{        &NBSP ; [[Nsnotificationcenter Defaultcenter] removeobserver:self];  }//Custom Reminder window Ns_inline void Tipwithmessage (NSString *message) {       dispatch_async (Dispatch_ Get_main_queue (), ^{               uialertview *alerview = [[Uialertview alloc] I nitwithtitle:@ "hint" message:message delegate:nil cancelbuttontitle:nil Otherbuttontitles:nil, nil];                  [alerview show];                  [alerview performselector: @selector ( dismisswithclickedbuttonindex:animated:) withobject:@[@0, @1] afterdelay:0.9];        });  }
Considerations for unplugging the headset (Must see section)
  • 1. When the developer tests the plug-in code of the headset, it uses the real-time test. The simulator does not have a headphone jack unless you chisel a hole in the computer.
  • 2. Whether using the iOS6.0 method or the later method, there is a prerequisite that the singleton object of the Avaudiosession class must be initialized at the beginning, otherwise neither the block stealth function nor the notification method can be implemented.
  • 3. This note is a commonplace issue, that is, once a notification center appears, it is important to remove all observers from the notification hub in the Dealloc method of the current controller.
Monitoring of the key of the headphone line control

Line control of headphones

As we all know, the iphone headset is wired control part of, then how can we achieve it? In fact, the core of the implementation is the Uiresponder class - (void)remoteControlReceivedWithEvent:(UIEvent *)eventMethod, this method has the following two functions. What we need is the first function.
  • A remote control event was received. such as headphone control.

  • Allow remote control events to be passed, you must call UIApplication's Beginreceivingremotecontrolevents method, turn off remote control, call endreceivingremotecontrolevents.

As with the above, we still need to import the Avfoundation.framework framework. Then we import the header file in Viewcontroller. Of course, the implementation of the headphone line control key monitoring is the following three prerequisites.
  • 1. Enable remote event reception (using [[UIApplication sharedapplication] beginreceivingremotecontrolevents]; method).

  • 2. The same requirement for UI controls must be the first responder (no such requirement for view controller Uiviewcontroller or application UIApplication object snooping).

  • 3. The application must be the controller of the current audio, that is, the current audio player in the notification bar in iOS 7 must be our own development program.

Specific code implementation, as follows.
-(BOOL) canbecomefirstresponder{       return YES;} Received remote event-(void) Remotecontrolreceivedwithevent: (uievent *) event{       nslog (@ " Event tyipe:::%ld   Subtype:::%ld ", (Long) Event.type, (long) event.subtype);    //type==2  subtype== Click Pause key: 103, double-click Pause Key 104       &NBSP;IF (Event.type = = Uieventtyperemotecontrol) {               switch (event.subtype) {                       case uieventsubtyperemotecontrolplay:{                             nslog (@ "Play---------");                            }break;                         case uieventsubtyperemotecontrolpause:{           &NBsp                    nslog (@ "Pause---------");                            }break;                        case uieventsubtyperemotecontrolstop:{                                nslog (@ "Sto") P---------");                            }break;                        case Uieventsubtyperemotecontroltogglep laypause:{                                Click Pause Key: 103                               &NBS P NSLog (@ "Click Pause key: 103");                             }break;                        case Uieventsubtyperemotecontrolnexttra ck:{               //Double-click Pause key: 104               &  nbsp                nslog (@ "Double-click Pause key: 104");                            }break;                        case Uieventsubtyperemotecontrolpreviou strack:{                               ns Log (@ "Three-click Pause key: 105");                            }break;                        case Uieventsubtyperemotecontrolbeginse Ekingforward:{                               nslog (@ "Click, then press No: 108");                            }break;                        case Uieventsubtyperemotecontrolendseek ingforward:{                              &NBS P NSLog (@ "Click, press Again, Release: 109");                }break;                        default:         &N Bsp                      break;                }        }}

---> Spicy demo:https://yun.baidu.com/share/link?shareid=2650043582&uk=4079807053

Wen/neuro-Sao Building (Jane book author)
Original link: http://www.jianshu.com/p/87f3f2024038

Talk about the headset in iOS development (monitor headphone plug-in, headphone line control)-B

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.