如何为iPhone实现音量键快门?

hux*_*xia 20 iphone events volume ios

我想用以下原生相机实现相同的行为iOS5:

  • 按音量+按钮拍照

归档它的理想方式是什么?有没有办法捕捉音量键按下事件?

谷歌搜索和搜索了几个小时后,我找到了一个解决方案:使用NSNotificationCenter:

...
    [[NSNotificationCenter defaultCenter]
         addObserver:self
         selector:@selector(volumeChanged:)
         name:@"AVSystemController_SystemVolumeDidChangeNotification"
         object:nil];
...
- (void)volumeChanged:(NSNotification *)notification{
    [self takePhoto];   
}
Run Code Online (Sandbox Code Playgroud)

但是,它有两个问题:

  • 每次按音量键时都会出现"当前系统音量"的半透明叠加,这不是我想要的.
  • 对于本机相机,当您按下音量键作为快门时,系统音量不会改变,但是,使用上述方法,系统音量将会改变.

hux*_*xia 12

我找到了另一种方法来隐藏"系统音量叠加"和"当按下音量键时绕过系统音量变化".

坏的部分:这是一个超级UGLY黑客.

然而,好的部分是:这个丑陋的黑客使用NO私有API.

另一个注意事项是:它只适用于ios5 +(无论如何,对于我的问题,因为AVSystemController_SystemVolumeDidChangeNotification仅适用于ios5,所以这个UGLY黑客只适合我的问题.)

它的工作方式:"充当音乐/电影播放器​​应用程序并让音量键调整应用程序量".

码:

// these 4 lines of code tell the system that "this app needs to play sound/music"
AVAudioPlayer* p = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"photo-shutter.wav"]] error:NULL];
[p prepareToPlay];
[p stop];
[p release];

// these 5 lines of code tell the system that "this window has an volume view inside it, so there is no need to show a system overlay"
[[self.view viewWithTag:54870149] removeFromSuperview];
MPVolumeView* vv = [[MPVolumeView alloc] initWithFrame:CGRectMake(-100, -100, 100, 100)];
[self.view addSubview:vv];
vv.tag = 54870149;
[vv release];
Run Code Online (Sandbox Code Playgroud)

(5个小时花在发现这个超级丑陋的方法......狗屎......草尼马啊!)

另一件事:如果您采取上述攻击,则需要在应用程序变为活动状态时每隔一段时间运行代码.因此,您可能需要将一些代码放入您的app委托中.

- (void)applicationDidBecomeActive:(UIApplication *)application 
Run Code Online (Sandbox Code Playgroud)


Kwo*_*ung 12

基于huxia的代码,这适用于ios5 +,无需在每次激活时运行代码,只需在开始时运行一次.

// these 4 lines of code tell the system that "this app needs to play sound/music"
AVAudioPlayer* p = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"photoshutter.wav"]] error:NULL];
[p prepareToPlay];
[p stop];

//make MPVolumeView Offscreen
CGRect frame = CGRectMake(-1000, -1000, 100, 100);
MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:frame];
[volumeView sizeToFit];
[self.view addSubview:volumeView];
Run Code Online (Sandbox Code Playgroud)