使用Swift在iOS中进行远程控制事件
试图找出如何读取Apple耳机的音量按钮以用作相机快门的触发器(如Apple Camera应用程序那样)。
从关于远程控制事件 , 远程控制接收事件和这个git repo的文档中,我拼凑起来,我可能需要一个AVAudioPlayer
对象, .beginReceivingRemoteControlEvents()
和remoteControlReceivedWithEvent
,以及使这个视图canBecomeFirstResponder()
return true
。
import UIKit import AVFoundation class ViewController: UIViewController, AVAudioPlayerDelegate { var player: AVAudioPlayer! override func viewDidLoad() { super.viewDidLoad() var session: AVAudioSession = AVAudioSession.sharedInstance() session.setActive(true, error: nil) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) println("viewDidAppear worked...") self.becomeFirstResponder() UIApplication.sharedApplication().beginReceivingRemoteControlEvents() } override func canBecomeFirstResponder() -> Bool { return true } override func remoteControlReceivedWithEvent(event: UIEvent) { let rc = event.subtype println("does this work? \(rc.rawValue)") //takePicture() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
当我按下耳机上的音量按钮时,我希望得到"does this work"
,而我只是看到它正常调整耳机音量。 所以我必须遗漏一些东西,可能是delegate
或AVSession
?
我在r / swift上交叉发布了这个,我被告知它可能需要播放音频(直接从文档中引用)。
因此,虽然这不是理想的解决方案,但它适用于我自己的私人用途。
import UIKit import AVFoundation import MediaPlayer class ViewController: UIViewController, AVAudioPlayerDelegate { var testPlayer: AVAudioPlayer? = nil func loadSound(filename: NSString) -> AVAudioPlayer { let url = NSBundle.mainBundle().URLForResource(filename as String, withExtension: "caf") var error: NSError? = nil let player = AVAudioPlayer(contentsOfURL: url, error: &error) if error != nil { println("Error loading \(url): \(error?.localizedDescription)") } else { player.prepareToPlay() } return player } override func viewDidLoad() { super.viewDidLoad() self.testPlayer = self.loadSound("silence") self.testPlayer?.numberOfLoops = -1 self.testPlayer?.play() } override func canBecomeFirstResponder() -> Bool { return true } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.becomeFirstResponder() UIApplication.sharedApplication().beginReceivingRemoteControlEvents() } override func remoteControlReceivedWithEvent(event: UIEvent) { let rc = event.subtype println("rc.rawValue: \(rc.rawValue)") // take photo } }
我注意到在Apple的相机应用程序中,+ / – 音量按钮触发相机,麦克风按钮暂停/播放在另一个应用程序中运行的任何音频,但在此实现中音量按钮仍然控制音量(并且任何音频已暂停当应用程序启动时)。
rc.rawValue: 103
对应于单击麦克风按钮,双击返回104
,三次点击返回105
,然后有时一次碰撞一对,返回108
或109
。