Swift-AVAudioRecorder录制本地音频

2021-09-16  本文已影响0人  紫云夕月
import UIKit
import Foundation

class PublicFunction: NSObject {
    //MARK:document文档目录
    static func documentPath() -> String {
        let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as String
        return documentPath
    }
    //MARK:下载文件路径
    static func downloadDirectory(path:String) -> String {
        let downloadFile = PublicFunction.documentPath() + "/\(path)/"
        let fileManager = FileManager.default
        if fileManager.fileExists(atPath: downloadFile) == false {
            do {
                try fileManager.createDirectory(atPath: downloadFile, withIntermediateDirectories: true, attributes: nil)
            } catch {
                print(error)
            }
        }
        return downloadFile
    }
}

import Foundation
import AVFoundation

class LocalRecorderTool: NSObject,AVAudioRecorderDelegate {
    
    //单列
    static let sharedAudioPlayer = LocalRecorderTool()
    //录音器
    var recorder:AVAudioRecorder?
    
    let semaphore = DispatchSemaphore(value: 1)
    
    var audioPath:String = ""
    var mp3Path:String = ""
    
    //MARK:初始化录音器
    func createRecorderWith() {
        let session = AVAudioSession.sharedInstance()
        //在音频播放前,首先创建一个异常捕捉语句
        do {
            //启动音频会话管理,此时会阻断后台音乐播放
            try session.setActive(true)
            //设置音频播放类别,表示该应用仅支持音频播放
            try session.setCategory(AVAudioSession.Category.playAndRecord)
            //扬声器播放
            try session.overrideOutputAudioPort(AVAudioSession.PortOverride.speaker)
            
            //录音配置
            let recordSettingDictionary:[String:Any] =
                        [
                            AVFormatIDKey: NSNumber(value: kAudioFormatLinearPCM),//音频格式
                            AVNumberOfChannelsKey: 2, //录音的声道数,立体声为双声道
                            AVEncoderAudioQualityKey : AVAudioQuality.max.rawValue,//录音质量
                            AVLinearPCMBitDepthKey : 16,
                            AVSampleRateKey : 44100.0 //录音器每秒采集的录音样本数
                        ]

            //录音器
            let playUrl = URL(string: audioPath)
            recorder = try AVAudioRecorder.init(url: playUrl!, settings: recordSettingDictionary)
            recorder?.delegate = self
            recorder?.isMeteringEnabled = true
            recorder?.prepareToRecord()
            
        } catch {
            printLog(message: error)
        }
    }
    
    //MARK:开始录音
    func startRecording() {
        let session = AVAudioSession.sharedInstance()
        //在音频播放前,首先创建一个异常捕捉语句
        do {
            //设置音频播放类别,表示该应用仅支持音频播放
            try session.setCategory(AVAudioSession.Category.playAndRecord)
            recorder?.record()
        } catch {
            printLog(message: error)
        }
    }
    
    //MARK:结束录音
    func stopRecording() {
        recorder?.stop()
        convertMp3.audioPCMtoMP3(self.audioPath, mp3File: self.mp3Path)
        recorder = nil
    }
    
    //MARK:AVAudioRecord Delegate
    func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
        printLog(message: "finish recording---\(recorder)----\(flag)")
    }
    
    func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) {
        printLog(message: error)
    }
}
//MARK:创建本地录音器
func createLocalRecorder() {
    //音频地址
    let savePath = PublicFunction.downloadDirectory(path: "record") + "play.caf"
    
    LocalRecorderTool.sharedAudioPlayer.audioPath = savePath
    LocalRecorderTool.sharedAudioPlayer.createRecorderWith()
}
//开始录音
LocalRecorderTool.sharedAudioPlayer.startRecording()
//结束录音
LocalRecorderTool.sharedAudioPlayer.stopRecording()
上一篇 下一篇

猜你喜欢

热点阅读