AVAudioSession Swift

问题描述 投票:8回答:3

我正在尝试编写一个快速的iOS应用程序来记录用户的声音。我在swift中编写了以下代码,但它无法向用户请求mic权限。它打印已授予但它从不记录音频,并且在隐私下的设置窗格中,它不会列出应用程序。如何在swift中请求录制权限?

var session: AVAudioSession = AVAudioSession.sharedInstance()
session.requestRecordPermission({(granted: Bool)-> Void in
     if granted {
          println(" granted")
          session.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil)
          session.setActive(true, error: nil)
          self.recorder.record()
     }else{
          println("not granted")
     }
})
ios swift avaudioplayer avaudiorecorder avaudiosession
3个回答
13
投票

从iOS 7开始,您需要检查它是否响应选择器requestRecordPermission:

我使用带有iOS 8 Beta的iPhone 5S测试了这段代码,它运行得很好。一旦您授予权限,系统将不会再次请求它。

值得一提的是,它在使用模拟器时没有请求许可。

这是我尝试过并且正在运行的代码:

if (session.respondsToSelector("requestRecordPermission:")) {
    AVAudioSession.sharedInstance().requestRecordPermission({(granted: Bool)-> Void in
        if granted {
            println("granted")
            session.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil)
            session.setActive(true, error: nil)
            self.recorder ()
        } else{
            println("not granted")
        }
     })

}

3
投票

对于Swift 3

let session = AVAudioSession.sharedInstance()
    if (session.responds(to: #selector(AVAudioSession.requestRecordPermission(_:)))) {
        AVAudioSession.sharedInstance().requestRecordPermission({(granted: Bool)-> Void in
            if granted {
                Linphone.manager.callUser(username: username)

                print("granted")

                do {
                    try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
                    try session.setActive(true)
                }
                catch {

                    print("Couldn't set Audio session category")
                }
            } else{
                print("not granted")
            }
        })
    }

1
投票

斯威夫特4

var session: AVAudioSession = AVAudioSession.sharedInstance()
@IBAction func btnmike(_ sender: Any) {
   // let session = AVAudioSession.sharedInstance()
    if (session.responds(to: #selector(AVAudioSession.requestRecordPermission(_:)))) {
        AVAudioSession.sharedInstance().requestRecordPermission({(granted: Bool)-> Void in
            if granted {
                print("granted")

                do {
                    try self.session.setCategory(AVAudioSessionCategoryPlayAndRecord)
                    try self.session.setActive(true)
                }
                catch {

                    print("Couldn't set Audio session category")
                }
            } else{
                print("not granted")
            }
        })
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.