swift 录音实现

//
//  ViewController.swift
//  ReconderSuccess1
//
//  Created by lujun on 2022/1/27.
//

import UIKit
import AVFoundation
class ViewController: UIViewController {
    
    lazy var record: AVAudioRecorder? = {
        var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        path = (path as NSString).appendingPathComponent("\(UUID.init().uuidString).caf")
        
        var docPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        
       let _ =  docPath .appendPathComponent("\(UUID.init().uuidString).caf")
        
        let url = URL(fileURLWithPath: path)
        let configDic = [
            //编码格式
            AVFormatIDKey: NSNumber(value: Int32(kAudioFormatLinearPCM)),
            //采样率
            AVSampleRateKey: NSNumber(value: 11025.0),
            //通道数
            AVNumberOfChannelsKey: NSNumber(value: 2),
            //录音质量
            AVEncoderAudioQualityKey: NSNumber(value: Int32(AVAudioQuality.min.rawValue))
        ]
        debugPrint(path)
        do{
            let recoard = try AVAudioRecorder(url: url, settings: configDic)
            recoard.prepareToRecord()
            
          /*  recoard.record()
            recoard.record(atTime: recoard.deviceCurrentTime + 3)
            recoard.record(forDuration: recoard.deviceCurrentTime + 100.0)
            recoard.record(atTime: recoard.deviceCurrentTime + 3, forDuration: recoard.deviceCurrentTime + 100)*/
            return recoard
            
        }catch{
            debugPrint(error.localizedDescription)
            return nil
        }
        
      
    }()
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        if record?.currentTime ?? 0 > Double(2) {
            record?.stop()
        }else{
            debugPrint("录音时间短")
            record?.stop()
            record?.deleteRecording()
        }
        
        record?.record()
        
        
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        record?.stop()
        debugPrint("touchesEnded")
    }
   

}
posted @ 2022-01-27 17:05  johnson--save  阅读(339)  评论(0)    收藏  举报