Search code examples
iosswiftavaudioplayeravaudiorecorder

How to record audio for a certain duration using AV Audio


I am trying to write a code to record audio for 2 seconds, and automatically play it after it is done recording. There are no errors in this code, but it seems to not record at all and directly jumps inside the if loop and prints "recording successful..." and does not play anything.

@IBAction func buttonPressedDAF(_ sender: UIButton) {

    print("starting DAF...")


    let filename = getDirectory().appendingPathComponent("\(fileNameString)")

    let settings = [AVFormatIDKey: Int(kAudioFormatAppleLossless),
                    AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue,
                    AVEncoderBitRateKey: 320000,
                    AVNumberOfChannelsKey: 1,
                    AVSampleRateKey: 12000.0] as [String : Any]

    do{

        audioRecorder = try AVAudioRecorder(url: filename, settings: settings)
        audioRecorder.delegate = self


        if(audioRecorder.record(forDuration: 2 ))

        {
            print("recording succesfull...")
            audioRecorder.stop()
            audioRecorder = nil
            playRecording()
        }


    }
    catch {
        print ("failed...")
    }

I have already worked with AV Audio before slightly, and have no problem in implementing a Start, Stop button based Audio Recorder, however over here it seems like the record(forDurartion: ) function is just not working.

Thanks in advance


Solution

  • If there is no completion block for this you can just use my code below to make a delay for calling the stop recording code :)

    @IBAction func buttonPressedDAF(_ sender: UIButton) {
    
            print("starting DAF...")
    
    
            let filename = getDirectory().appendingPathComponent("\(fileNameString)")
    
            let settings = [AVFormatIDKey: Int(kAudioFormatAppleLossless),
                            AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue,
                            AVEncoderBitRateKey: 320000,
                            AVNumberOfChannelsKey: 1,
                            AVSampleRateKey: 12000.0] as [String : Any]
    
            do{
    
                audioRecorder = try AVAudioRecorder(url: filename, settings: settings)
                audioRecorder.delegate = self
    
    
                if(audioRecorder.record(forDuration: 2 ))
    
                {
                    // .now() + number of seconds
                    DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
                        print("recording succesfull...")
                        self.audioRecorder.stop()
                        self.audioRecorder = nil
                        self.playRecording()
                    }
                }
    
    
            }
            catch {
                print ("failed...")
            }