使用Swift

时间:2015-05-25 05:31:51

标签: ios iphone swift camera headphones

试图弄清楚如何读取Apple耳机的音量按钮以用作相机快门的触发器(如Apple Camera应用程序那样)。

Remote Control Events Remote Control Received With Eventthis 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",而我只是看到它正常调整耳机音量。所以我必须遗漏一些东西,可能是delegateAVSession

2 个答案:

答案 0 :(得分:4)

我在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,然后有时会碰到一对夫妇返回108109

答案 1 :(得分:1)

基于Cody的答案,但已于2019年更新(Swift 5)

-O