1

ボタンを押すと、音声が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)") 
     } 
    } 
} 

私は、非同期的にこれを行う必要があります誰もがこれで私を助けることができますか?

おかげ

答えて

1

この作品の私には、それが

@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)") 
      } 
     } 
    } 
便利です願っています
関連する問題