John Deere
John Deere

Reputation: 35

Async calling for recording than autoplay than delete the audio

By pressing the button i should record audio for 4 seconds and autoplay it and loop it for 2 times. Another pressing button i should do the same thing but before that i should delete previous record.

Here is my code:

@IBAction func loopButton(_ sender: Any) {
    if audioRecorder?.isRecording == false {
        playButton.isEnabled = false
        audioRecorder?.record(forDuration: 4.0)
        audioRecorder?.stop()
        audioPlayer?.stop()


        do {
            try audioPlayer = AVAudioPlayer(contentsOf: (audioRecorder?.url)!)
            audioPlayer!.delegate = self
            audioPlayer!.prepareToPlay()
            audioPlayer!.numberOfLoops = 2
            audioPlayer!.play()
        } catch let error as NSError {
            print("audioPlayer error: \(error.localizedDescription)")
        }
    } else {
        audioRecorder?.deleteRecording()
        audioRecorder?.record(forDuration: 4.0)
        audioRecorder?.stop()
        audioPlayer?.stop()

        do {
            try audioPlayer = AVAudioPlayer(contentsOf: (audioRecorder?.url)!)
            audioPlayer!.delegate = self
            audioPlayer!.prepareToPlay()
            audioPlayer!.numberOfLoops = 2
            audioPlayer!.play()
        } catch let error as NSError {
            print("audioPlayer error: \(error.localizedDescription)")
        }
    }
}

I should do this asynchronously, could anyone help me with this?

Thanks

Upvotes: 1

Views: 69

Answers (1)

Milos Mandic
Milos Mandic

Reputation: 1071

This work's at me, hope it's helpful

   @IBAction func loopButton(_ sender: Any) {
        DispatchQueue.main.async {
            if self.audioRecorder?.isRecording == false {
                self.audioRecorder?.record(forDuration: 4.0)
                self.playButton.isEnabled = false
            } else {
                self.audioRecorder?.deleteRecording()
                self.audioRecorder?.record(forDuration: 4.0)
                self.playButton.isEnabled = false
            }
        }

        DispatchQueue.global().asyncAfter(deadline: .now() + 4.0) {
            do {
                try self.audioPlayer = AVAudioPlayer(contentsOf: (self.audioRecorder?.url)!)
                self.audioPlayer!.delegate = self
                self.audioPlayer!.prepareToPlay()
                self.audioPlayer!.numberOfLoops = 2
                self.audioPlayer!.play()
            } catch let error as NSError {
                print("audioPlayer error: \(error.localizedDescription)")
            }
        }
    }

Upvotes: 1

Related Questions