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