iOS 8上最清晰的捕获音量上/下按钮的方法

Ric*_*aez 27 volume ios ios8

什么是在iOS 8上捕获音量增/减按钮的最佳/最干净的方式什么?

理想情况下,我想捕获按键并防止系统音量发生变化(或者至少阻止音量变化HUD显示).


有一些旧的答案会使用已弃用的方法,并且在iOS 8上似乎根本不起作用.这个iOS 8特定的一个也不起作用.

这个RBVolumeButtons开源类似乎也不适用于iOS 8.

Moh*_*idy 13

对于Swift,您可以在viewController类中使用下一个代码:

let volumeView = MPVolumeView(frame: CGRectMake(-CGFloat.max, 0.0, 0.0, 0.0))
self.view.addSubview(volumeView)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(volumeChanged(_:)), name: "AVSystemController_SystemVolumeDidChangeNotification", object: nil)
Run Code Online (Sandbox Code Playgroud)

然后添加此功能

func volumeChanged(notification: NSNotification) {

     if let userInfo = notification.userInfo {
        if let volumeChangeType = userInfo["AVSystemController_AudioVolumeChangeReasonNotificationParameter"] as? String {
            if volumeChangeType == "ExplicitVolumeChange" {
                // your code goes here
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

此代码检测用户的显式卷更改操作,就像您没有检查显式操作一样,此函数将定期自动调用.

此代码不会阻止系统卷更改

  • 你知道如何阻止系统显示音量hud吗? (3认同)

MFP*_*MFP 12

首先添加AVFoundationMediaPlayer Framework,然后您可以使用下面的代码来检测上/下按钮,

-(void)viewWillAppear:(BOOL)animated
{
 AVAudioSession* audioSession = [AVAudioSession sharedInstance];    
[audioSession setActive:YES error:nil];
[audioSession addObserver:self
               forKeyPath:@"outputVolume"
                  options:0
                  context:nil];
}

-(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

  if ([keyPath isEqual:@"outputVolume"]) {        
      float volumeLevel = [[MPMusicPlayerController applicationMusicPlayer] volume];
      NSLog(@"volume changed! %f",volumeLevel);
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 很好的解决方案,但请记住,如果音量已经达到最大值,它将无法检测到"音量增大"按钮(如果音量已经静音,则不会检测到'向下' (8认同)
  • 只是想知道,这不符合苹果的条款和条件,如http://stackoverflow.com/questions/29923664/is-it-possible-to-disable-volume-buttons-in-ios-apps? (2认同)

ing*_*nti 10

对于swift 3 :(记得添加:import MediaPlayer ..)

    override func viewDidLoad() {
        super.viewDidLoad()

        let volumeView = MPVolumeView(frame: CGRect(x: 0, y: 40, width: 300, height: 30))
        self.view.addSubview(volumeView)
//      volumeView.backgroundColor = UIColor.red
        NotificationCenter.default.addObserver(self, selector: #selector(volumeChanged(notification:)),
                                               name: NSNotification.Name(rawValue: "AVSystemController_SystemVolumeDidChangeNotification"),
                                               object: nil)
    }


    func volumeChanged(notification: NSNotification) {

        if let userInfo = notification.userInfo {
            if let volumeChangeType = userInfo["AVSystemController_AudioVolumeChangeReasonNotificationParameter"] as? String {
                if volumeChangeType == "ExplicitVolumeChange" {
                    // your code goes here
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

....

  • @NikKov 如果让 newVolume = userInfo["AVSystemController_AudioVolumeNotificationParameter"] 作为?双{打印(新卷)} (2认同)

sam*_*ize 5

这是一个 2 部分的答案,它们在Swift 5 中是独立的。

监听音量触发事件,

import MediaPlayer

// Observe in eg. viewDidLoad
let volumeChangedSystemName = NSNotification.Name(rawValue: "AVSystemController_SystemVolumeDidChangeNotification")
NotificationCenter.default.addObserver(self, selector: #selector(volumeChanged), name: volumeChangedSystemName, object: nil)

@objc private func volumeChanged(notification: NSNotification) {
    guard
        let info = notification.userInfo, 
        let reason = info["AVSystemController_AudioVolumeChangeReasonNotificationParameter"] as? String,
        reason == "ExplicitVolumeChange" else { return }

    // Handle it
}
Run Code Online (Sandbox Code Playgroud)

要隐藏系统音量控制,

// Add the view but not visible
let volumeView = MPVolumeView(frame: CGRect(x: -CGFloat.greatestFiniteMagnitude, y: 0, width: 0, height: 0))
view.addSubview(volumeView)
Run Code Online (Sandbox Code Playgroud)


Gar*_*hes 1

好吧,请参阅音频会话服务参考以获取更多信息。您需要使用 AudioSessionInitialize 启动音频会话,然后使用 AudioSessionSetActive 使其处于活动状态,使用 AudioSessionAddPropertyListener 侦听音量变化,并传递类型为 AudioSessionPropertyListener 的回调。

这个网站写得很好:http://fredandrandall.com/blog/2011/11/18/take-control-of-the-volume-buttons-on-ios-like-camera/