swiftavaudiorecordercompletionhandler

Swift: how to wait for sound to be played?


Hey I have programmed a recorder app just like voice memos from apple. I also have the same sounds for starting and stopping the recording. The problem is that the sound at the start is on the recording. Is there a way to wait for the sound to be finished playing and only then start the recording?

Right now I have this:

@State var recorder: AVAudioRecorder!
@State var isRecording = false // boolean, true -> recorder is recording


let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileName = url.appendingPathComponent("myRcd.m4a") // set the location for the Audiofile
let settings = [
    AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
    AVSampleRateKey: 44100,
    AVNumberOfChannelsKey: 1,
    AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
] // settings for the recording

self.recorder = try AVAudioRecorder(url: fileName, settings: settings)
AudioServicesPlaySystemSound(1113) // play the soundeffect
self.recorder.record() // start recording
self.isRecording.toggle() // change isRecording to true

Solution

  • For anyone with the same problem, this is how I solved it:

    @State var recorder: AVAudioRecorder!
    @State var isRecording = false // boolean, true -> recorder is recording
    
    
    let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let fileName = url.appendingPathComponent("myRcd.m4a") // set the location for the Audiofile
    let settings = [
        AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
        AVSampleRateKey: 44100,
        AVNumberOfChannelsKey: 1,
        AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
    ] // settings for the recording
    
    
    // ---------------------------------------------------- the part I changed
    self.isRecording.toggle() // change isRecording to true
    self.recorder = try AVAudioRecorder(url: fileName, settings: settings)
    AudioServicesPlaySystemSoundWithCompletion(1113) { // play the sound and wait until it is finished
        self.recorder.record() // start recording when sound is played
    }
    

    Thanks to @burnsi