Recording audio in Swift

后端 未结 8 1812
别那么骄傲
别那么骄傲 2020-12-04 06:12

Does anyone know where I can find info on how to record audio in a Swift application? I\'ve been looking at some of the audio playback examples but I can\'t seem to be able

8条回答
  •  时光取名叫无心
    2020-12-04 06:55

    Swift2 version of @codester's answer.

    func record() {
        //init
        let audioSession:AVAudioSession = AVAudioSession.sharedInstance()
    
        //ask for permission
        if (audioSession.respondsToSelector("requestRecordPermission:")) {
            AVAudioSession.sharedInstance().requestRecordPermission({(granted: Bool)-> Void in
                if granted {
                    print("granted")
    
                    //set category and activate recorder session
                    try! audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
                    try! audioSession.setActive(true)
    
    
                    //get documnets directory
                    let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
                    let fullPath = documentsDirectory.stringByAppendingPathComponent("voiceRecording.caf")
                    let url = NSURL.fileURLWithPath(fullPath)
    
                    //create AnyObject of settings
                    let settings: [String : AnyObject] = [
                        AVFormatIDKey:Int(kAudioFormatAppleIMA4), //Int required in Swift2
                        AVSampleRateKey:44100.0,
                        AVNumberOfChannelsKey:2,
                        AVEncoderBitRateKey:12800,
                        AVLinearPCMBitDepthKey:16,
                        AVEncoderAudioQualityKey:AVAudioQuality.Max.rawValue
                    ]
    
                    //record
                    try! self.audioRecorder = AVAudioRecorder(URL: url, settings: settings)
    
                } else{
                    print("not granted")
                }
            })
        }
    
    }
    

提交回复
热议问题