美文网首页
录制音频、创建文件夹

录制音频、创建文件夹

作者: 米亚流年 | 来源:发表于2018-09-25 16:41 被阅读0次
    使用懒加载创建AVFoundation
    class ViewController: UIViewController {
    
    //MARK:- 懒加载  通过闭包创建
    lazy var record : AVAudioRecorder? = {
        /**
         参数:
         url: 文件存储路径
         settings:录音的设置项
         */
        //这个方法只能取出路径 而不能创建路径
        var path = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first)!
         path = path + "/CustomeAudio"
        do {
           try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
        }catch {
            print(error)
        }
        let filePath = path + "/test.caf"
        let fileURL = NSURL(string: filePath)!
        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 record = try AVAudioRecorder(url: fileURL as URL, settings: configDic)
            //准备录音:系统会给我们分配一些资源
            record.prepareToRecord()
            return record
        } catch {
            print(error)
            return nil
        }
        
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
       let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        let documentDir = paths[0]
        let filePath = documentDir + "/Direct"
        do {
            try FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: true, attributes: nil)
        }catch {
            print(error)
        }
    }
    
    
    //MARK:- 点击屏幕时开始录音
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        //开始录音
        print("开始录音")
        record?.record()
    }
    
    //MARK:- 结束录音
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        //根据当前的录音时间,做处理
        let duration = record?.currentTime ?? 0
        if duration < 2 {
            print("录音时间太短,请重新录制")
            record?.stop()
            record?.deleteRecording()
            return
        }
        //结束录音
        print("录音时间刚刚好,可以保存")
        record?.stop()
    }
    

    }

    相关文章

      网友评论

          本文标题:录制音频、创建文件夹

          本文链接:https://www.haomeiwen.com/subject/heuloftx.html