I have a local .mp4 video that I would like to add as a background video. I've created a function:
func playVideo() {
let path = NSBundle.mainBundle().pathForResource("dronefootagecompressed", ofType:"mp4")
let url = NSURL.fileURLWithPath(path!)
self.moviePlayer = MPMoviePlayerController(contentURL: url)
if let player = self.moviePlayer {
player.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)
player.view.sizeToFit()
player.scalingMode = MPMovieScalingMode.Fill
player.fullscreen = true
player.controlStyle = MPMovieControlStyle.None
player.movieSourceType = MPMovieSourceType.File
player.repeatMode = MPMovieRepeatMode.One
player.play()
self.view.addSubview(player.view)
}
}
which is then called in viewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
playVideo()
}
The video is showing up, but it seems like it's covering everything else (text labels, titles, everything), or so I assume it is. Can I make the video be in the background (if that even is the issue)?
Thanks.
EDIT:
When I call playVideo() in viewDidAppear, the video shows up for about 2 seconds before going to a black background. The buttons are still visible. Is the video not loading properly?
i think putting it in viewDidAppear() method will solve the thing
Related
I want to play background video on login screen on swift 3.0. But when I run program, video do not working as full screen. It is workingHow can I fix this ? Here is the storyboard picture.
enter code here
import UIKit
import AVFoundation
class ViewController: UIViewController {
var Player: AVPlayer!
var PlayerLayer: AVPlayerLayer!
var frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let URL:NSURL = NSURL(string: "https://firebasestorage.googleapis.com/v0/b/pattyapp-34c16.appspot.com/o/dog1.mp4?alt=media&token=98ab3c41-c645-4535-a70b-41511b5df602")!
Player = AVPlayer.init(url: URL as URL)
PlayerLayer = AVPlayerLayer(player: Player)
PlayerLayer.videoGravity = AVLayerVideoGravityResizeAspect
PlayerLayer.frame.size = frame.size
Player.actionAtItemEnd = AVPlayerActionAtItemEnd.none
Player.isMuted = true
Player.play()
view.layer.insertSublayer(PlayerLayer, at: 0)
NotificationCenter.default.addObserver(self, selector: #selector(playerItemReachEnd(notification:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: Player.currentItem)
}
func playerItemReachEnd(notification: NSNotification) {
Player.seek(to: kCMTimeZero)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Play video into background you can use the following list of 3rd party library to resolve your problem.
VideoSplashKit
HAPlayerView
Video You are trying to play has dimensions different from layer size. I'd recommend You to try
PlayerLayer.videoGravity = AVLayerVideoGravityResize
or
PlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
Hi all i am trying to play a video from s3 using Avplayer. Now if i play the video, the video starts playback after the whole video is buffered. so I added player.automaticallyWaitsToMinimizeStalling = false, but now the video automatically pauses
import UIKit
import AVFoundation
import AVKit
class ViewController: UIViewController {
var player: AVPlayer!
var item : AVPlayerItem!
override func viewDidLoad() {
super.viewDidLoad()
item = AVPlayerItem(url: URL(string: "https://cent-churchconnect.s3-ap-southeast-2.amazonaws.com/cent-churchconnect/testAdmin/eb8cc8b5-80e0-468a-a2c9-979cf1b5ac76_toystory.mp4")!)
player = AVPlayer(playerItem: item)
let controller = AVPlayerViewController()
present(controller, animated: true) { _ in }
controller.player = player
addChildViewController(controller)
view.addSubview(controller.view)
controller.view.frame = CGRect(x: 0, y: 50, width: self.view.frame.size.width, height: 300)
controller.player = player
controller.showsPlaybackControls = true
if #available(iOS 10.0, *) {
player.automaticallyWaitsToMinimizeStalling = false
player.play()
} else {
// Fallback on earlier versions
}
}
}
I had the same issue below steps worked for me,
Try to use method func playImmediately(atRate:) and make sure the property player.automaticallyWaitsToMinimizeStalling = false is set properly.
Use method func playImmediately(atRate:) instead of func play()
I used the cocoa pod https://github.com/piemonte/Player.
You can use the delegate methods to control the playback.
AVPlayer layer not showing video content sometimes but plays audio.
This happens some times not each time
Here is my lines of code :
override func viewDidLoad() {
super.viewDidLoad()
self.tempVideoPath = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("tmpMov.mov")
self.player = AVPlayer(url: self.tempVideoPath!)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.playerLayer = AVPlayerLayer(player: self.player)
self.playerLayer?.frame = self.videoPlayer.bounds
self.playerLayer?.backgroundColor = UIColor.yellow.cgColor
self.videoPlayer.layer.addSublayer(playerLayer!)
print("player = \(playerLayer?.bounds)")
}
Help me to solve this issue.
the problem with you code is that the bounds of videoPlayer can change.
So you need to add the following code to your view controller to change AVPlayerLayer's frame accordingly:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
playerLayer?.frame = view.bounds
}
Hope it helps.
Although the videoplayer has been initialized correctly or created from storyboard, it seems that the layer is non-existent and creates this annoying problem.
At the beginning of your viewDidAppear first, try to create the layer , than add to it>
let layer = CALayer()
self.videoPlayer.layer = layer
//self.playerView.wantsLayer = true // this line is only for osx
I using AVPlayerViewController which I want to fadeout when the video ends... I can capture the end-of-video event, and I the code put together for AVPlayer works, but for the AVPlayerViewController not.
self.playerItem = AVPlayerItem(URL: videoURL)
self.player = AVPlayer(playerItem: self.playerItem)
self.playerLayer = AVPlayerLayer(player: self.player)
self.streamPlayer = AVPlayerViewController()
self.streamPlayer.player = self.player
self.streamPlayer.view.frame = CGRect(x: 128, y: 222, width: 512, height: 256)
This code works too, but goes full screen- I don't want full screen...
//self.presentViewController(self.streamPlayer, animated: true) {
// self.streamPlayer.player!.play()
//}
I use this?
self.view.addSubview(self.streamPlayer.view)
self.streamPlayer.player!.play()
The event capture ..
override func viewWillAppear(animated: Bool) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "finishedPlaying:", name: AVPlayerItemDidPlayToEndTimeNotification, object: playerItem)
}
The event Code ...
func finishedPlaying(myNotification:NSNotification) {
let fadeOut = CABasicAnimation(keyPath: "opacity")
fadeOut.fromValue = 1.0
fadeOut.toValue = 0.0
fadeOut.duration = 8.0
fadeOut.delegate = self
fadeOut.setValue("video", forKey:"fadeOut")
fadeOut.removedOnCompletion = false
fadeOut.fillMode = kCAFillModeForwards
This line does nothing with AVPlayerViewController/With AVPlayer it fades out nicely ?
playerLayer.addAnimation(fadeOut, forKey: nil)
This simply removes AVPlayerViewController, plan B if I cannot make this work!
//self.streamPlayer.view.removeFromSuperview()
print("VIDEO finished")
}
AVPlayerViewController has it's own AVPlayerLayer and does not know about the AVPlayerLayer you created. Thus, the line
playerLayer.addAnimation(fadeOut, forKey: nil)
has no effect. You should set or animate the alpha value of AVPlayerViewController's view. For the fade animation you may want to look at the +[UIView animateWithDuration:(...)] methods and call
self.streamPlayer.view.removeFromSuperview()
in the completion handler.
I have a video I'm trying to play using MPMoviePlayerController and it loads fine, but cuts out after 5 seconds. I found this post, but it isn't really applicable for swift.
MPMoviePlayerController stops playing the video after 5s
Here is my code.
import MediaPlayer
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var moviePlayer: MPMoviePlayerController?
let url = NSURL(string: "http://path/to/video.m3u8")
moviePlayer = MPMoviePlayerController(contentURL: url)
if let player = moviePlayer {
player.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)
player.view.sizeToFit()
player.scalingMode = MPMovieScalingMode.None
player.movieSourceType = MPMovieSourceType.Streaming
//player.repeatMode = MPMovieRepeatMode.One
player.play()
self.view.addSubview(player.view)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "metadataUpdated",
name: MPMoviePlayerTimedMetadataUpdatedNotification,
object: nil)
}
}
Could your moviePlayer be going out of scope? Have you tried making it a member variable?
moviePlayer is a local variable of viewDidLoad, so once that function finishes, I don't see any reason why your player would not be deallocated.
If you instead make it a variable of the class, its lifetime will be extended to match your class's lifetime.
something like
class ViewController: UIViewController {
var player: MPMoviePlayerController?
override func viewDidLoad() {
// ...
self.player = MPMoviePlayerController(contentURL: url) // won't go out of scope at end of viewDidLoad()
// ...
}