Asynchronous 异步调用录制而不是自动播放而不是删除音频

Asynchronous 异步调用录制而不是自动播放而不是删除音频,asynchronous,swift3,avfoundation,grand-central-dispatch,audio-recording,Asynchronous,Swift3,Avfoundation,Grand Central Dispatch,Audio Recording,通过按下按钮,我应该录制音频4秒钟,自动播放并循环播放2次。再按一个按钮,我应该做同样的事情,但在此之前,我应该删除以前的记录 这是我的密码: @IBAction func loopButton(_ sender: Any) { if audioRecorder?.isRecording == false { playButton.isEnabled = false audioRecorder?.record(forDuration: 4.0)

通过按下按钮,我应该录制音频4秒钟,自动播放并循环播放2次。再按一个按钮,我应该做同样的事情,但在此之前,我应该删除以前的记录

这是我的密码:

@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)")
        }
    }
}
我应该异步执行此操作,有人可以帮助我吗


谢谢

这项工作对我很有帮助,希望能有所帮助

   @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)")
            }
        }
    }