要求:当用户通过同时具有音量增大/减小键的有线/无线方式插入iPhone的耳机时,用户可以通过该按钮执行自定义操作。 (无需更改耳机的系统音量)
当前实施:
确定是否已插入耳机:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleRouteChange:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]];
- (void)handleRouteChange:(NSNotification *)notification
{
NSDictionary *dicUserInfo = notification.userInfo;
uint reason = [dicUserInfo[AVAudioSessionRouteChangeReasonKey] intValue];
BOOL isHeadphonesConnected = NO;
switch (reason)
{
case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
{
AVAudioSession *session = [AVAudioSession sharedInstance];
for (AVAudioSessionPortDescription *output in session.currentRoute.outputs)
{
if ([output.portType isEqualToString:AVAudioSessionPortHeadphones])
{
isHeadphonesConnected = YES;
}
}
}
break;
case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
{
AVAudioSessionRouteDescription *previousRoute = dicUserInfo[AVAudioSessionRouteChangePreviousRouteKey];
for (AVAudioSessionPortDescription *output in previousRoute.outputs)
{
if ([output.portType isEqualToString:AVAudioSessionPortHeadphones])
{
isHeadphonesConnected = NO;
}
}
}
break;
default:
break;
}
if (isHeadphonesConnected)
{
NSLog(@"Headphones connected");
}
else
{
NSLog(@"Headphones disconnected");
}
}
确定是否已从耳机上按下音量键:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volumeDidChange:) name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];
- (IBAction)volumeDidChange:(NSNotification *)notification
{
CGFloat newVolume = [[notification.userInfo valueForKey:@"AVSystemController_AudioVolumeNotificationParameter"] floatValue];
if (volume == 0 || newVolume < volume)
{
// change value
}
else
{
// change value
}
volume = newVolume;
}
当前实施中我们面临的问题:
我们面临的问题是,每当用户单击耳机上的音量按钮时,我们都能够触发volumeDidChange
方法,但它也会更改系统音量并显示音量HUD警报,而无需更改。系统音量应恒定。
如果用户单击设备音量的增大和减小按钮,则可以更改系统音量,但是通过耳机,它只能执行某些操作。
Swift语言的答案也将受到赞赏。
答案 0 :(得分:0)
iOS非常严格,您不能更改硬件按钮的预期行为。即使您能够执行,您的应用也会被拒绝。