For the life of me I have not been able to get AVAudioRecorder
to properly record sound with the record()
method. I can only get sound to record if I use the record(forDuration:)
method. I've tried across multiple devices (iPhone 8 w/ iOS 14, iPad Air (7th gen) w/ iOS 14, iPhone 12 mini simulator). I've also changed the build target from iOS 13 to iOS 9 and tried on older simulators (iPhone 8 w/ iOS 10).
Regardless, of my device/iOS combination the behavior is always the same - when stopping the recording record()
always produces an empty 4kb audio file. I've explored the simulator containers, and downloaded the device containers to verify this. Again, record(forDuration:)
will save a proper audio file with the actual recorded sound.
Xcode Version: 12.3
Culprit code:
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)
}
Silent failure for record()
- no Errors or crashes.
Another interesting thing to note that I just discovered. When I call audioRecorder.stop()
the app fails to save the audio file properly. Regardless of whether I use record()
or record(forDuration:)
I'm very confused. Any help is appreciated.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…