Search code examples
swift3avplayeravplayerviewcontrollerios10.2

Swift3 Play multiple video files with AVPlayer


I have a little code which allows me to play a local file when I hit a UIButton. But what I want is to play multiple files on 3 different UIButtons because I have 3 video files which I want to attach to my app.

This is the current code:

import UIKit
import AVFoundation
import AVKit

class ViewController: UIViewController {

    var playerController = AVPlayerViewController()
    var player:AVPlayer?


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let videoString:String? = Bundle.main.path(forResource: "Video", ofType: ".mp4")

        if let url = videoString {

            let videoURL = NSURL(fileURLWithPath: url)

            self.player = AVPlayer(url: videoURL as URL)
            self.playerController.player = self.player



        }


    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func PlayVideo(_ sender: AnyObject) {

        self.present(self.playerController, animated: true, completion: {

            self.playerController.player?.play()

        })

    }


}

Solution

  • You can create url for different video file in your button click funtions

    @IBAction func Button1Click(_ sender: AnyObject) {
        let videoString:String? = Bundle.main.path(forResource: "Video1", ofType: ".mp4")
    
        if let url = videoString {
            let videoURL = NSURL(fileURLWithPath: url)
            self.player = AVPlayer(url: videoURL as URL)
            self.playerController.player = self.player
        }
    
        self.present(self.playerController, animated: true, completion: {
            self.playerController.player?.play()
    
        })
    
    }
    
    @IBAction func Button2Click(_ sender: AnyObject) {
        let videoString:String? = Bundle.main.path(forResource: "Video2", ofType: ".mp4")
    
        if let url = videoString {
            let videoURL = NSURL(fileURLWithPath: url)
            self.player = AVPlayer(url: videoURL as URL)
            self.playerController.player = self.player
        }
    
        self.present(self.playerController, animated: true, completion: {
            self.playerController.player?.play()
    
        })
    
    }
    
    @IBAction func Button3Click(_ sender: AnyObject) {
        let videoString:String? = Bundle.main.path(forResource: "Video3", ofType: ".mp4")
    
        if let url = videoString {
            let videoURL = NSURL(fileURLWithPath: url)
            self.player = AVPlayer(url: videoURL as URL)
            self.playerController.player = self.player
        }
    
        self.present(self.playerController, animated: true, completion: {
            self.playerController.player?.play()
    
        })
    
    }