-2

I am making a very simple IOS app. It is a button, and when pressed a long .wav file plays. I would love to be able to press the button again, and the audio would stop playing. I’ve tried many of the solutions here as there are similar questions, but I’m stuck. Any ideas?

    import UIKit
    import AVFoundation

    class ViewController: UIViewController {

   // Making a variable called player. It is the AVAudioPlayer
      var player: AVAudioPlayer!

   // No idea what this is.
    override func viewDidLoad() {
    super.viewDidLoad()
}




//This is the key pressed. Inside is the playSound and a print for checking
@IBAction func keyPressed(_ sender: UIButton) {
    
   playSound()
print("button pressed")
    
   
}






//Turn playSound into a func – and tell it what to play and play it if button is pressed
func playSound() {
        let url = Bundle.main.url(forResource: "audio", withExtension: "wav")
        player = try! AVAudioPlayer(contentsOf: url!)
        player.play()
        

}

}

Greg Funk
  • 1
  • 1
  • 1
    You should update your question to include the solutions you’ve tried. That way those trying to help you won’t waste their time by suggesting solutions you have already discounted. – Andrew Aug 07 '22 at 16:26
  • you just need to add a bool for execute stop and play. – cristian_064 Aug 07 '22 at 16:33

1 Answers1

1

AVAudioPlayer has the isPlaying (docs) property that you can check to determine if you should play or stop playback when your button is pressed.

import AVFoundation
import UIKit

class ViewController: UIViewController {

    // Making a variable called player. It is the AVAudioPlayer
    var player: AVAudioPlayer!

    // This is the key pressed. Inside is the playSound and a print for checking
    @IBAction func keyPressed(_ sender: UIButton) {
        if player.isPlaying {
            stopSound()
        } else {
            playSound()
        }
    }

    // Turn playSound into a func – and tell it what to play and play it if button is pressed
    func playSound() {
        let url = Bundle.main.url(forResource: "audio", withExtension: "wav")
        player = try! AVAudioPlayer(contentsOf: url!)
        player.play()
    }

    func stopSound() {
        player.stop()
    }
}

Sidenote: The viewDidLoad method override isn't needed unless you're wanting to have custom code run when the view is loaded by the system.

bretto
  • 61
  • 1
  • 4