How do I put an video clip in my storyboard? All I see is:
Also, where do I put the .mp4 file?
And last, what would be the correct code to include for a looping video clip when View Controller starts.
//insert looping video clip here
I am familiar with Android Studio/java and can do this there no problem. However, I am very new to swift and Xcode so I am having trouble.
To make a looping Video :-
Add a UIView
to your ViewController, set constraints accordingly.
Declare that UIView
as @IBOutlet
in your conforming class
@IBOutlet weak var videoView : VideoPlay!
//Where VideoPlay is a CustomClass for the Video player
Create a custom Class for the video player UIVew
: VideoPlay
import UIKit
import AVFoundation
class VideoPlay: UIView {
private var player : AVPlayer!
private var playerLayer : AVPlayerLayer!
init() {
super.init(frame: CGRectZero)
self.initializePlayerLayer()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.initializePlayerLayer()
self.autoresizesSubviews = false
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initializePlayerLayer()
}
private func initializePlayerLayer() {
playerLayer = AVPlayerLayer()
playerLayer.backgroundColor = UIColor.whiteColor().CGColor
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
self.layer.addSublayer(playerLayer)
playerLayer.frame = self.bounds
}
func playVideoWithURL(url: NSURL) {
player = AVPlayer(URL: url)
player.muted = false
playerLayer.player = player
player.play()
loopVideo(player)
}
func toggleMute() {
player.muted = !player.muted
}
func isMuted() -> Bool
{
return player.muted
}
func loopVideo(videoPlayer: AVPlayer) {
NSNotificationCenter.defaultCenter().addObserverForName(AVPlayerItemDidPlayToEndTimeNotification, object: nil, queue: nil) { notification in
videoPlayer.seekToTime(kCMTimeZero)
videoPlayer.play()
}
}
}
Modify your StoryBoard conforming ViewController :-
class ViewController: UIViewController {
@IBOutlet weak var videoView : VideoPlay!
override func viewDidLoad() {
super.viewDidLoad()
let bundle: NSBundle = NSBundle.mainBundle()
let moviePath: String = bundle.pathForResource("yourVideoFile_Name", ofType: "yourVideoFile_Type")!
let movieUrl : NSURL = NSURL.fileURLWithPath(moviePath)
videoView.playVideoWithURL(movieUrl)
}....
}
Since the videoView
conforms to class VideoPlay
, You can access
VideoPlay
's global function.
As for where to keep the video file , keep it in the main bundle i.e :- in your case Fighting Trainer Pro Folder
Such as :-
toggleMute()
isMuted()