Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVPlayer will not stop playing when going back to the previous view controller (SWIFT)

Tags:

swift

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 )

}
like image 716
Jingo Bracamonte Avatar asked Jun 21 '15 15:06

Jingo Bracamonte


1 Answers

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
 }
like image 151
Penkey Suresh Avatar answered Jan 03 '23 16:01

Penkey Suresh