Automatically Start audio recording when user speaks

I am trying to start recording when the user starts to talk and stops recording when the user is done talking. And I want to limit the maximum record audio length.I could not be able to find enough function in AVAudioRecorderDelegate.Hope you understand my problem.Thanks in Advance

@IBAction func recordAudio(_ sender: Any) {
    recordingLabel.text = "Recording in progress..."
    let dirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask, true)[0] as String
    let recordingName = "recordedVoice.wav"
    let pathArray = [dirPath, recordingName]
    let filePath = URL(string: pathArray.joined(separator: "/"))

    let session = AVAudioSession.sharedInstance()
    try! session.setCategory(AVAudioSessionCategoryPlayAndRecord, with:AVAudioSessionCategoryOptions.defaultToSpeaker)

    try! audioRecorder = AVAudioRecorder(url: filePath!, settings: [:])
    audioRecorder.delegate = self
    audioRecorder.isMeteringEnabled = true
    audioRecorder.prepareToRecord()
    audioRecorder.record()
}

@IBAction func stopRecording(_ sender: Any) {
    recordButton.isEnabled = true
    stopRecordingButton.isEnabled = false
    recordingLabel.text = "Tap to record..."

    audioRecorder.stop()
    let audioSession = AVAudioSession.sharedInstance()
    try! audioSession.setActive(false)
}

func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
    if (flag) {
        //Success
    } else {
        print("Could not save audio recording!")
    }
}

1 answer

  • answered 2018-05-16 06:12 Abdelahad Darwish

    To Record Audio When user tak1 you need some steps

    1. Permission from User to all your app to use Mic

    In your Info Plist Add Privacy - Microphone Usage Description in user Plist and add Text Description

    2. Location to save Recorded File user FileManager

    3. To End After time : use audioRecorder.record(forDuration: 30) // record for 30 Sec

    Check complete code :

    import UIKit
    import AVFoundation
    
    class ViewController: UIViewController  {
    
       @IBOutlet weak var recordButton: UIButton!
        var recordingSession: AVAudioSession!
        var audioRecorder: AVAudioRecorder!
    
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
        }
    
        @IBAction func recordAudio(_ sender: Any) {
            self.requestRecordPermission()
        }
    
        func requestRecordPermission() {
            recordingSession = AVAudioSession.sharedInstance()
            do {
                try recordingSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
                try recordingSession.setActive(true)
                recordingSession.requestRecordPermission() { [unowned self] allowed in
                    DispatchQueue.main.async {
                        if allowed {
                            // User allow you to record
    
                            // Start recording and change UIbutton color
                            self.recordButton.backgroundColor = .red
                            self.startRecording()
    
                        } else {
                            // failed to record!
                        }
                    }
                }
            } catch {
                // failed to record!
            }
        }
        func startRecording() {
    
            let audioFilename = getDocumentsDirectory().appendingPathComponent("recordedFile.m4a")
    
            let settings = [
                AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                AVSampleRateKey: 12000,
                AVNumberOfChannelsKey: 1,
                AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
            ]
    
            do {
                audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)
                audioRecorder.delegate = self
                audioRecorder.record(forDuration: 30)  // record for 30 Sec
                recordButton.setTitle("Tap to Stop", for: .normal)
                recordButton.backgroundColor = .green
    
            } catch {
                finishRecording(success: false)
            }
        }
        func getDocumentsDirectory() -> URL {
            let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
            return paths[0]
        }
    
        @objc func recordTapped() {
            if audioRecorder == nil {
                startRecording()
            } else {
                finishRecording(success: true)
            }
        }
    
        public func finishRecording(success: Bool) {
            audioRecorder.stop()
            audioRecorder = nil
    
            if success {
                // record sucess
                recordButton.backgroundColor = .green
            } else {
                // record fail
    
                recordButton.backgroundColor = .yellow
    
            }
        }
    
    }
    
    
    extension ViewController :AVAudioRecorderDelegate{
    
    
        func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
            if !flag {
                finishRecording(success: false)
            }
        }
    }