开启录音权限
NSMicrophoneUsageDescription
录音权限请求
AVAudioSession.sharedInstance().requestRecordPermission({(granted: Bool)-> Void in
if granted {
print("record permission granted")
} else{
print("record permission not granted")
}
})
AVAudioSession 场景设置
let session: AVAudioSession = AVAudioSession.sharedInstance()
do {
try session.setCategory(.playAndRecord)
try session.setActive(true)
} catch {
print(error)
}
Recorder URL
let fileName = "test1.caf"
var documentDictory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let tempDir = NSTemporaryDirectory()
let filePath = tempDir.appending(fileName)
let fileUrl = URL.init(fileURLWithPath: filePath)
AVAudioRecorder Setting
注意这里的 Dictionary Value 需要为 NSNumber,否则 AVAudioRecorder 初始化会失效
let settings: [String: NSNumber] = [
AVFormatIDKey: NSNumber.init(value: kAudioFormatAppleIMA4) , // kAudioFormatAppleIMA4, kAudioFormatMPEG4AAC, 等
AVSampleRateKey: NSNumber.init(value: 44100.0),
AVNumberOfChannelsKey: NSNumber.init(value: 2),
AVEncoderAudioQualityKey: NSNumber.init(value: AVAudioQuality.medium.rawValue),
AVEncoderBitRateKey: NSNumber.init(value: 320000)
]
AVAudioRecorder 初始化
do {
let recorder = try AVAudioRecorder.init(url: fileUrl, settings: settings)
recorder.delegate = self
recorder.isMeteringEnabled = true
if recorder.prepareToRecord() {
recorder.record()
}else {
print("recorder prepare to record failed.")
}
self.recorder = recorder
} catch {
print("AVAudioRecorder inital error \(error.localizedDescription)")
}
AVAudioRecorder Operation
- record()
- stop()
- isRecording()
网友评论