Play / Pause Swift Sound Button
I'm new to swift and don't seem to understand this. I'm trying to have one button act like a play button that loops the sound and a pause button if clicked again. I tried using the if / else statement but I keep getting this error "fatal error: unexpectedly found nil while unpacking optional value"
The code works without an if / else statement, but in this case it is cycled off without the possibility of pausing it.
Any suggestions?
var hihat16: AVAudioPlayer!
@IBAction func hat16(_ sender: Any) {
if hihat16.isPlaying == false {
let path = Bundle.main.path(forResource: "Hat 017-1.aif", ofType:nil)!
let url = URL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOf: url)
hihat16 = sound
sound.play()
hihat16.numberOfLoops = -1
} catch {
// couldn't load file :(
}
}else{ hihat16.stop()}
Image of code and error message:
+3
source to share
1 answer
Try it.
Do this in your DidLoad view
let path = Bundle.main.path(forResource: "Hat 017-1.aif", ofType:nil)!
let url = URL(fileURLWithPath: path)
do {
hihat16 = try AVAudioPlayer(contentsOf: url)
hihat16.numberOfLoops = -1
} catch {}
Then in your @IBAction you can do this.
if !hihat16.isPlaying {
hithat16.play()
}
else{ hithat.stop()}
+3
source to share