Many headphones that you use on your iPhone (including Apple's own) have either buttons, a microphone or both.
They work nicely with the Mac, and iTunes recognizes the button presses correctly.
My question is this - how would you detect these button presses in Cocoa? I'm writing a small alternative to iTunes that lives in your menu bar, and I'd want to also respond to the h开发者_开发知识库eadset buttons, not just the keyboard's media keys.
Thanks for any responses!
Check out DDHidLib at http://code.google.com/p/ddribin/. For a quick test, you can subclass DDHidKeyboard and override the 3 following methods. Then, in the provided HIDDeviceTest target's KeyboardPaneController.m - (void) awakeFromNib;
, replace NSArray * keyboards = [DDHidKeyboard allKeyboards];
with NSArray * keyboards = [<YourSubclass> allKeyboards];
or whatever you named your subclass. Now when you run the HIDDeviceTest target, you should see "Apple Mikey HID Driver" listed under the "Keyboards" tab. With luck, you will see the input from pressing the headset remote buttons. Try double tapping and triple tapping the middle button and you will see that each one is a different event type. I've only tested this on a Mid 2011 13" Macbook air running Lion 10.7.3 as well as a Mid 2010 17" Macbook Pro running SL 10.6.8.
#import "DDHidLib.h"
@implementation <YourSubclass>
+ (NSArray *) allKeyboards;
{
NSArray *array = [DDHidDevice allDevicesMatchingUsagePage: kHIDPage_Consumer
usageId: kHIDUsage_GD_Pointer
withClass: self
skipZeroLocations: NO];
//Only return "Apple Mikey HID Driver", if not found, return nil.
for (DDHidDevice *device in array) {
if ([[device productName] isEqualToString:@"Apple Mikey HID Driver"]) {
return [NSArray arrayWithObject:device];
}
}
return nil;
}
- (void) initKeyboardElements: (NSArray *) elements;
{
NSEnumerator * e = [elements objectEnumerator];
DDHidElement * element;
while (element = [e nextObject])
{
unsigned usagePage = [[element usage] usagePage];
unsigned usageId = [[element usage] usageId];
if (usagePage == kHIDPage_GenericDesktop)
{
if ((usageId >= 0x89) && (usageId <= 0x8D))
{
[mKeyElements addObject: element];
}
}
NSArray * subElements = [element elements];
if (subElements != nil)
[self initKeyboardElements: subElements];
}
}
- (void) ddhidQueueHasEvents: (DDHidQueue *) hidQueue;
{
DDHidEvent * event;
while ((event = [hidQueue nextEvent]))
{
DDHidElement * element = [self elementForCookie: [event elementCookie]];
unsigned usageId = [[element usage] usageId];
SInt32 value = [event value];
if (value == 1)
[self ddhidKeyboard: self keyDown: usageId];
}
}
精彩评论