Create a play/pause button
I am trying to create a single view app that has a volume slider and a play/pause button. I have a slider, a sound, a button, and a label that shows the current slider value. My problem is, the button starts the music, but once it is playing and I tap it again, it restarts the song instead of pausing it. Here is my ViewController:
import UIKit
import AVFoundation
var audioPlayer = AVAudioPlayer()
class ViewController: UIViewController {
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var label: UILabel!
@IBOutlet weak var playButon: UIButton!
@IBAction func valueChanged(sender: AnyObject) {
var currentValue = slider.value
label.text = "\(Int(currentValue))"
audioPlayer.volume = currentValue
}
@IBAction func playMusic(sender: AnyObject) {
let soundURL = NSBundle.mainBundle().URLForResource("backgroundMusic", withExtension: "mp3")
audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: nil)
if audioPlayer.playing {
audioPlayer.pause()
} else {
audioPlayer.play()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Posted Jun 5, 2015, 6:15 PM UTC
21
You're creating a new AVAudioPlayer every time the button is pressed, so .playing() will always return false (it was just created, so of course it isn't playing).
You should store audioPlayer in a property in the view controller, and just call play / pause on the existing instance instead of creating a new one each time.