我正在使用AVAudioRecorder
來記錄人聲。我的代碼如下:AVAudioRecorder永不記錄
// Property of Class
var recorder:AVAudioRecorder?
func recordButtonTapped() {
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryRecord)
try audioSession.setActive(true)
if audioSession.recordPermission() != .granted {
audioSession.requestRecordPermission({ (success) in
self.startRecording()
})
}
else {
self.startRecording()
}
} catch {
print("Unable To Set Category")
}
}
func startRecording() {
// libraryPathWith(media) just gets the path to the documents directory
// Like so: Documents/MediaLibrary/Audio/<mediaID>.<mediaExtension>
if let path = MMFileManager.libraryPathWith(media: self.media) {
isRecording = true
do {
let settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 44100,
AVNumberOfChannelsKey: 1,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]
recorder = try AVAudioRecorder(url: path, settings: settings)
recorder?.delegate = self
if recorder!.prepareToRecord() {
recorder?.record()
}
}
catch {
isRecording = false
}
}
}
func stopRecording() {
self.recordingLabel.text = "Recording Complete"
self.recordingLabel.textColor = UIColor.white
if let rec = recorder {
rec.stop()
recorder = nil
}
isRecording = false
}
AVAudioRecorderDelegate
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
print("RECORDED AUDIO SUCCESSFULLY \(flag)")
}
func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) {
print("AUDIO RECORDER ERROR \(error?.localizedDescription)")
}
後,我呼籲停止對AVAudioRecorder的audioRecorderEncodeErrorDidOccur
功能不會被調用,但audioRecorderDidFinishRecording
功能的確但flag
是總是false
。它打印出"RECORDED AUDIO SUCCESSFULLY false"
問題
當我在上面我沒有將文件保存到我的文檔目錄中指定的位置記錄使用的代碼。但是這個文件不是我能玩的東西。它寫入文本文件,而不是音頻文件,因爲我指定的擴展名爲.aac
。
爲什麼AVAudioRecorder
不錄音?我怎樣才能做到這一點?