title: Conditional audio playing using AV Audio Player in Swift
body: <p>I would like to be able to play audio on pressing a button a maximum of twice.  After pressing the button twice it should no longer play audio even when pressed.  I have this code currently, but it doesn't work and I am unsure where I am going wrong:</p>
  
  <pre><code>var soundFileURLRef: NSURL!
  var audioPlayer = AVAudioPlayer?()
  var audioCounter = 0
  
  override func viewDidLoad() {
      super.viewDidLoad()
  
      // setup for audio
      let playObjects = NSBundle.mainBundle().URLForResource("mathsinfo", withExtension: "mp3")
  
      self.soundFileURLRef = playObjects
  
      do {
          audioPlayer = try AVAudioPlayer(contentsOfURL: soundFileURLRef)
      } catch _ {
          audioPlayer = nil
      }
      audioPlayer?.delegate = self
      audioPlayer?.prepareToPlay()
  }
  
  
  
  //function for counting times audio is played
  func countAudio() {
      if ((audioPlayer?.play()) != nil) {
          ++audioCounter
      }
  
  }
  
  //MARK: Actions
  
  //action for button playing the audio
  @IBAction func playMathsQuestion(sender: AnyObject) {
      countAudio()
      if audioCounter &lt; 2 {
         audioPlayer?.play()
      }
  }
  </code></pre>