'iOS - issue with AVAudioRecorder after rebuilding

Problem description:

I am currently working on an iOS application that will record user's voices via AVFoundation. The problem occurs when I re-build the application again without deleting it before building. In the above case, the audio file that I created in the previous session is not playable and when I delete it, I could initiate a new AVAudioRecorder but it won't record.

Interestingly, this problem does not occur at all if I don't rebuild the application(from Xcode). And the AVAudioRecorder works every bit as expected.

Code:

You can view the code at Github.

look at detailViewController and photoItem for this problem

Suspected causes:

  1. Problem with permission after rebuilding (dismissed because I could still delete the audio files from previous sessions)
  2. AVAudioRecorder usage issue (does not seem like so, for I follow/check the usage from multiple online examples)
  3. Something changed during that rebuilding process.
  4. AVAudioRecorder internal issue (Apple, really?)

Thanks for your input, and sorry about the messy codes.(my first attempt at iOS application).



Solution 1:[1]

iOS 15.4 onwards I face the same issue, Here got the solution - If you are using

Declare Variable: private var audioRecorder: AVAudioRecorder?

func startRecording() {
    
            audioRecorder?.stop()
            audioRecorder = nil          
            
            let audioSession = AVAudioSession.sharedInstance()
            do {
                try audioSession.setCategory(AVAudioSession.Category.playAndRecord, options: AVAudioSession.CategoryOptions.defaultToSpeaker)
                try audioSession.setActive(true)
            } catch {
                debugPrint("audioSession properties weren't set because of an error.")
            }
            
            do {
                let settings = [
                    AVFormatIDKey:Int(kAudioFormatFLAC),
                    AVSampleRateKey:18000,
                    AVNumberOfChannelsKey:1,
                    AVLinearPCMBitDepthKey:8,
                    AVLinearPCMIsFloatKey:false,
                    AVLinearPCMIsBigEndianKey:false,
                    AVEncoderAudioQualityKey:AVAudioQuality.high.rawValue
                ] as [String : Any]
    
                    let formate = AVAudioFormat(settings: settings)
    
                    audioRecorder = try AVAudioRecorder(URL: " LOCAL FILEPATH URL"), format: formate)
                    audioRecorder?.delegate = self
                    audioRecorder?.isMeteringEnabled = true
                    audioRecorder?.prepareToRecord()
                    audioRecorder?.record()
                
            } catch let error {
                debugPrint(error.localizedDescription)
            }
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matt