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