I have two View Controllers a TableViewController where i have a list of musics and a UIViewController where it displays the music details and plays the music. The music automatically plays when the view is loaded and pauses when the pause button is pressed. However whenever I go back to the previous TableViewController to select another music, the music continues to play. And if i select another music, both of them are playing together
override func viewDidLoad() {
super.viewDidLoad()
timeLabel.text = "00:00"
if let object = currentObject {
audioTitle.text = object["audioTitle"] as? String
let days = object["daysActive"] as! Int
daysActive.text = "Powertalks: Day \(days)"
var initialThumbnail = UIImage(named: "trc_app_icon.png")
audioImage.image = initialThumbnail
if let thumbnail = object["image"] as? PFFile {
audioImage.file = thumbnail
audioImage.loadInBackground()
}
if let audioFile = object["audioFile"] as? PFFile {
if let audioPath: String = audioFile.url {
audioPlayer = AVPlayer(URL: NSURL(string: audioPath))
audioSlider.minimumValue = 0
audioSlider.maximumValue = Float(CMTimeGetSeconds(audioPlayer.currentItem.asset.duration))
audioSlider.value = Float(CMTimeGetSeconds(audioPlayer.currentTime()))
audioPlayer.volume = volumeSlider.value
playAudio()
}
}
}
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateSlider"), userInfo: nil, repeats: true )
}
You have to pause the player when the view disappears. Although AVPlayer
doesn't have a stop method, you can set the rate
to 0.0
(or use pause()
) and set currentItem
to nil to achieve the same effect. Try using the below code (not tested)
override func viewWillDisappear(animated: Bool) {
audioPlayer.pause()
audioPlayer.currentItem = nil
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With