iOS开发笔记-99:Swift5 - 录音播放AVAudioPlayer、AVAudioRecorder、AVAudioSession

AVAudioSession配置,一定要配置,否则有很多莫名其妙的问题
这个是配置手机硬件的类。

let audioSession: AVAudioSession = AVAudioSession.sharedInstance()
//        AVAudioSession.sharedInstance().overrideOutputAudioPort(.speaker)
        do {
            //设置这个,可以修复录音只录一遍的问题
            try audioSession.setCategory(.playAndRecord)
            //设置这个,可以增加录音音量
            try audioSession.overrideOutputAudioPort(.speaker)
             //设置这个,配置生效
            try audioSession.setActive(true)
        } catch let error {
            debugPrint("Couldn't force audio to speaker: \(error)")
        }
//存储地址
//        let fruitsPath: String = NSHomeDirectory() + "/Documents/" + "record" + ".wav"
        
        let url: URL = URL.init(string: fruitsPath)!
        
        let configDic: [String: AnyObject] = [
            // 编码格式
            AVFormatIDKey: NSNumber(value: Int32(kAudioFormatLinearPCM)),
            // 采样率
            AVSampleRateKey: NSNumber(value: 11025.0),
            // 通道数
            AVNumberOfChannelsKey: NSNumber(value: 2),
            // 录音质量
            AVEncoderAudioQualityKey: NSNumber(value: Int32(AVAudioQuality.min.rawValue))
        ]
        
        do {
            let recordT = try AVAudioRecorder(url: url, settings: configDic)
            // 准备录音(系统会给我们分配一些资源)
            recordT.prepareToRecord()
            record = recordT
        }catch {
            print(error)
            record = nil
        }
  //开始录音
        record?.record()
//record?.currentTime 是录音时,获取录音时长的。停止录音后,这个参数为0
let cTime: Int = Int(record?.currentTime ?? 0)
        JJLog("录音时长")
        JJLog(cTime)
        if  cTime > 2 {
            record?.stop()
            print("录音成功")
            successAct(time: cTime)
        } else {
            print("录音太短")
            JJHUDManage.show("录音时间太短")
           
            // 如果想要删除录音文件, 必须先让录音停止
            record?.stop()
 // 删除录音文件
            record?.deleteRecording()
            record = nil
        }

AVAudioPlayer

func playUrl() {

//        let fruitsPath: String = NSHomeDirectory() + "/Documents/" + "record" + ".wav"
        
        let url: URL = URL.init(string: fruitsPath)!
        do {
            let  playerT =   try AVAudioPlayer.init(contentsOf: url)
            playerT.prepareToPlay()
            player = playerT
        }catch{
            print(error)
            player = nil
        }
        player?.play()
    }

获取录音文件

let url = URL.init(fileURLWithPath: fruitsPath)
        var voiceStr: String = ""
        
        do {
            let voiceData = try? Data(contentsOf: url)
            
            voiceStr = voiceData?.base64EncodedString() ?? ""
            // 没有错误消息抛出
        } catch {
            voiceStr = ""
            // 有一个错误消息抛出
        }

推荐阅读更多精彩内容