AVAudioRecorder

AVAudioRecorder

A class that provides audio recording capability in your application.
录音工具类,为App提供录音功能

//录音文件存放路径
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYY-MM-DD hh:mm:ss"
currentFileName = dateFormatter.string(from: Date()) + ".aac"

let documentPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last
let filePath = documentPath! + "/" + currentFileName!
let fileUrl = URL.init(fileURLWithPath: filePath)

//录音配置
let setting : [String:Any] =
[
AVFormatIDKey:kAudioFormatMPEG4AAC, //录音格式(aac安卓和iOS平台常用格式)
AVSampleRateKey:8000.0,//采样频率
AVNumberOfChannelsKey:1,//录音声道
AVEncoderBitDepthHintKey:16//采样深度(单次采样数据存储位数)
]

do{
    let audioRecorder = try AVAudioRecorder.init(url: fileUrl, settings: setting)
    audioRecorder.delegate = self
    audioRecorder.isMeteringEnabled = true //监听音量
    audioRecorder.record()
//轮询获取当前录音音量
    timer = Timer.init(timeInterval: 0.2, target: self, selector: #selector(monitorSound), userInfo: nil, repeats: true)
    RunLoop.main.add(timer!, forMode: RunLoopMode.commonModes)
}catch{
}

监听音量变化

@objc func monitorSound(){
    audioRecorder.updateMeters()
    if let meter = audioRecorder?.averagePower(forChannel: 0){
        print("meter = \(meter)")
    }
}

AVAudioRecorderDelegate

//录音完成
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
}

//录音文件编码失败
func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) {
}

设置录音和播放音频的音道

func resetAuidoSession(isRecord:Bool) {
    let audioSession = AVAudioSession.sharedInstance()
    do{
        try audioSession.setCategory(isRecord ? AVAudioSessionCategoryPlayAndRecord : AVAudioSessionCategoryPlayback)
        try audioSession.setActive(true)
    }catch{
    }
}

你可能感兴趣的:(AVAudioRecorder)