【发布时间】:2019-12-13 05:28:53
【问题描述】:
首先,此错误仅在 iOS 上最新的 12.4 版本中出现。该问题不会在模拟器中发生,必须在设备上运行。问题是一旦应用程序进入后台,对 AVAudioRecorder 上的记录的调用将返回 false。在所有以前的 iOS 版本中,这不会发生。 info.plist 使用 NSMicrophoneUsageDescription 标记进行更新,应用程序的功能包括音频背景模式。
我写了一个小的 ViewController 来显示这个问题。重建步骤:
1) Update the info.plist file with the NSMicrophoneUsageDescription tag so that the app gets permission to use the microphone
2) Update the app capabilities to set Audio background mode
3) Run the application
4) Send the application to the background
5) The current recording will finish, but the call to start a new recording will fail.
class ViewController: UIViewController, AVAudioRecorderDelegate {
var recordLabel: UILabel!
var recordingSession: AVAudioSession!
var audioRecorder: AVAudioRecorder!
var count: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
recordingSession = AVAudioSession.sharedInstance()
do {
try recordingSession.setCategory(.playAndRecord, mode: .default)
try recordingSession.setActive(true)
recordingSession.requestRecordPermission() { [unowned self] allowed in
DispatchQueue.main.async {
if allowed {
self.loadRecordingUI()
} else {
print("No permissions!!!")
}
}
}
} catch {
print("Exception in viewDidLoad!!!")
}
}
func loadRecordingUI() {
super.viewDidLoad()
recordLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 21))
recordLabel.center = CGPoint(x: 160, y: 285)
recordLabel.textAlignment = .center
recordLabel.text = "Waiting...."
self.view.addSubview(recordLabel)
setupRecorder()
startRecording();
}
func setupRecorder() {
let audioFilename = getDocumentsDirectory().appendingPathComponent("recording.m4a")
let settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 12000,
AVNumberOfChannelsKey: 1,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]
do {
audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)
audioRecorder.delegate = self
} catch {
print("Exception thrown in setupRecorder")
}
}
func startRecording() {
count += 1
let ret = audioRecorder.record(forDuration: 10) //record for 10 seonds
let txt = "Record returned " + ret.description + " for #\(count)"
recordLabel.text = txt
print(txt)
}
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
startRecording() //immediately start recording again
}
}
由于设置了应用程序在后台录制的功能,我希望在 AVAudioRecorder 上录制的调用返回 true
【问题讨论】:
-
没错,您无法在 iOS 12.4 和 iOS 13 beta 上开始在后台录制。所有框架都受到此问题的影响 - 更多信息在这里 forums.developer.apple.com/thread/120038 。请向苹果提交错误报告,希望他们会尽快修复它...
-
上述问题已在 iOS 13.1 中修复,但在后台访问麦克风时尝试连接蓝牙设备时仍然存在。我在这里开了一张票来描述这个问题:forums.developer.apple.com/thread/122621
-
这在 13.1 中未修复。当应用程序在后台时,对记录的调用仍然返回 false。
标签: ios swift avaudioplayer