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

标签 iphone ios events volume

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

  • 按音量+按钮拍照

归档它的理想方式是什么? 有什么方法可以捕获音量键按下事件吗?

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

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

但是,它有两个问题:

  • 每次按下音量键时都会出现“当前系统音量”的半透明覆盖,这不是我想要的。
  • 对于原生相机,当你按下音量键作为快门时,系统音量不会改变,但是使用上述方法,系统音量会改变。

最佳答案

我找到了另一种隐藏“系统音量覆盖”和“在按下音量键时绕过系统音量变化”的方法。

不好的部分:这是一个 super UGLY hack。

然而,好的部分是:这个丑陋的 hack 不使用私有(private) API。

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

它的工作方式:“充当音乐/电影播放器​​应用程序,让音量键调整应用程序音量”。

代码:

// 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];

(花了5个小时才发现这个超丑的方法……操……草尼马啊!)

另一件事: 如果您采用上述技巧,则需要在您的应用程序激活时每次都运行代码。 因此,您可能需要将一些代码放入您的应用委托(delegate)中。

- (void)applicationDidBecomeActive:(UIApplication *)application 

关于iphone - 如何为 iPhone 实现音量键快门?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8397170/

相关文章:

iphone - 根据设备类型选择不同的 Storyboard

javascript - 火狐浏览器中的鼠标移动

Java事件: Is this a good way to go about it?

java - 在实践中,如何使结果集不等于NULL?

iphone - 是否可以在 ios5 中创建静态表格 View 而不使用 Storyboard?

iphone - 从 iOs 应用程序访问 safari session 数据

iphone - 切换 View 在 xcode 中不起作用

iphone - 如何使用ViewController类获取旋转动画?

ios - 在没有选择器的情况下从照片库加载图像?

iphone - 使 UITableView 可按索引滚动