##This code has a button when pressed it plays the music. However there is no way to stop the music. I would like to create a code that if the button is pressed a even number of times the song plays if the button is pressed a odd number of times the song stops. Even numbers are 0, 2,4,6 etc and Odd numbers are 1,3,5,7 etc. I just want to use one button if possible. Thanks
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func PlaySound(sender: AnyObject) {
// Set the sound file name & extension
let alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("x", ofType: "mp3")!)
do {
// Preperation
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
} catch _ {
}
do {
try AVAudioSession.sharedInstance().setActive(true)
} catch _ {
}
// Play the sound
do {
audioPlayer = try AVAudioPlayer(contentsOfURL: alertSound)
} catch _{
}
audioPlayer.prepareToPlay()
audioPlayer.play()
}
}