【发布时间】:2021-04-07 08:03:35
【问题描述】:
在我的一生中,我无法让AVAudioRecorder 使用record() 方法正确录制声音。如果我使用record(forDuration:) 方法,我只能录制声音。我已经尝试过多种设备(带 iOS 14 的 iPhone 8、带 iOS 14 的 iPad Air(第 7 代)、iPhone 12 迷你模拟器)。我还将构建目标从 iOS 13 更改为 iOS 9,并在较旧的模拟器(iPhone 8 w/iOS 10)上进行了尝试。
无论如何,在我的设备/iOS 组合中,行为总是相同的 - 停止录制时 record() 总是会产生一个空的 4kb 音频文件。我已经探索了模拟器容器,并下载了设备容器来验证这一点。同样,record(forDuration:) 将使用实际录制的声音保存适当的音频文件。
Xcode 版本:12.3
罪魁祸首:
func recordAudio() {
let dirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let recordingName = "recordedVoice.m4a"
let pathArray = [dirPath, recordingName]
let filePath = URL(string: pathArray.joined(separator: "/"))
let session = AVAudioSession.sharedInstance()
try! session.setCategory(.playAndRecord, mode: .default, options: .defaultToSpeaker)
try! session.setActive(true)
try! self.audioRecorder = AVAudioRecorder(url: filePath!, settings: [:])
self.audioRecorder.delegate = self
self.audioRecorder.isMeteringEnabled = true
self.audioRecorder.prepareToRecord()
// Problematic section
// I only use one of the following two lines, record() fails, record(forDuration:) works.
self.audioRecorder.record()
self.audioRecorder.record(forDuration: 5)
}
func stopRecord() {
self.audioRecorder.stop()
let audioSession = AVAudioSession.sharedInstance()
try! audioSession.setActive(false)
}
record() 静默失败 - 没有错误或崩溃。
我刚刚发现的另一件有趣的事情。当我打电话给audioRecorder.stop() 时,应用程序无法正确保存音频文件。不管我用record()还是record(forDuration:)
我很困惑。任何帮助表示赞赏。
【问题讨论】:
-
我也与 AVAudioRecorder 斗争。您是否在 Playground 中尝试过您的代码?我让我的代码在操场上工作。不知道有什么区别。
标签: ios swift avfoundation avaudiosession avaudiorecorder