I am very new to Swift and Xcode and I was trying to use a video as a transition from one scene to another. I have most of the code for this figured out but the size of the video does not match the size of the screen, meaning when the transition occurs the background changes size. I could fix this by changing the AVLayerVideoGravity but the commands in the documentation give me errors, and I haven't found a way to set them properly. I'm sure this is really simple I just can't find the syntax I need anywhere, especially in the newest versions of swift and Xcode so I thought I would ask. Here is the code I have.
import UIKit
import AVKit
class MainRoom: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func Backpack(_ sender: Any) {
if let path = Bundle.main.path(forResource: "OpenBackpack", ofType: "avi", inDirectory: "SegueAnimations")
{
let OpenBackpack = AVPlayer(url: URL(fileURLWithPath: path))
let animPlayer = AVPlayerViewController()
animPlayer.player = OpenBackpack
animPlayer.showsPlaybackControls = true
let avPlayerLayer = AVPlayerLayer(player: OpenBackpack)
//Set avlayervideogravity to resizeaspectfill
present(animPlayer, animated: true, completion:
{
OpenBackpack.play()
})
}
}
}
Thank you for your help!
Found it! I misunderstood the code in another post, this works well
animPlayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
Related
I'm sure this is a rather simple and common problem - however I am new to programming and cannot find an answer to this online. I'm trying to create code that plays a video on loop in the background of an app. I've created a UIView and put the video into it. Now I'm trying to put the code behind it and I'm running into issues.
I have two error messages:
'seek(to:)' was deprecated in iOS 11.0: Use
-seekToTime:completionHandler:, passing nil for the completionHandler if you don't require notification of completion
and, after trying to run the app
Thread 1: signal SIGTERM
I've tried just about everything including rewriting the entire section of code (I had actually got it running before, even with the first error listed above), to no avail.
I have heard around the web that the SIGTERM issue can be fixed by restarting, but this is not the case and I think the issue is a result of the first error which I will explain next.
Here's my code:
import UIKit
import AVFoundation
import AVKit
class ViewController: UIViewController {
#IBOutlet weak var videoView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
private func setupView() {
let path = URL(fileURLWithPath: Bundle.main.path(forResource: "Cafe Video", ofType: "mov")!)
let player = AVPlayer(url: path)
let newLayer = AVPlayerLayer(player: player)
newLayer.frame = self.videoView.frame
self.videoView.layer.addSublayer(newLayer)
newLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
player.play()
player.actionAtItemEnd = AVPlayer.ActionAtItemEnd.none
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.videoDidPlayToEnd(_:)), name: NSNotification.Name(rawValue: "AVPlayerItemDidPlayToEndTimeNotification"), object: player.currentItem)
}
#objc func videoDidPlayToEnd(_ notification: Notification) {
let player: AVPlayerItem = notification.object as! AVPlayerItem
player.seek(to: CMTime.zero)
}
}
The first error message is associated with the very last line of code (player.seek(to: CMTime.zero).
I would like to be able to run my program and have my video play and loop. Instead, I get a blank white screen on the simulator, an error on my player.seek line and this SIGTERM thing in the AppDelegate after trying to run the app.
Any help that can be provided re this will be much appreciated - even if it does not entirely solve my problem per se.
Update following code:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.setupView()
}
In setupView() function
let newLayer = AVPlayerLayer(player: player)
newLayer.frame = self.videoView.bounds
Update Observer
#objc func videoDidPlayToEnd(_ notification: Notification) {
let player: AVPlayerItem = notification.object as! AVPlayerItem
player.seek(to: CMTime.zero, completionHandler: nil)
}
We are trying to play local GIF using AVPlayer. Does AVPlayer supports GIF format? This is what we tried:
guard let gifUrl = Bundle.main.url(forResource: "myGif", withExtension: "gif") else {
return
}
let gifPlayer = AVPlayer(url: gifUrl)
self.videoContainer.player = gifPlayer
self.videoContainer.player?.play()
Is it possible to play GIF with AVPlayer?
Any help or advice will be highly appreciated. Thank you.
Best Regards, Roi
You can try these steps to play local video using AVPlayer in swift:-
1) First of all add the video into your xcode project.
2) Check your added video in Bundle. Select your project your Target -> Build Phases -> Copy Bundle Resources.
If video is not available in Copy Bundle Resources then you can add by tapping on Plus button.
3) Use the following code in you project.
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
playVideo()
}
private func playVideo() {
guard let path = Bundle.main.path(forResource: "video", ofType:"m4v") else {
debugPrint("video.m4v not found")
return
}
let player = AVPlayer(url: URL(fileURLWithPath: path))
let playerController = AVPlayerViewController()
playerController.player = player
present(playerController, animated: true) {
player.play()
}
}
}
Hope this will help you :)
I'm new in Swift. I am trying to Run this code but got an error:
Thread 1: EXC_BAD_ACCESS (code=1, address=0x48) a.
Error appears here:
self.player.play()
Can anyone help in this issue?
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
do {
if let audioPath = Bundle.main.path(forResource: "music", ofType: "mp3") {
try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: audioPath))
}
} catch {
print("ERROR")
}
self.player.play()
}
What you doing with your code is:
Creating an instance of AVAudioPlayer without any data
Trying to create a new instance with some data from music.mp3 file
Playing it
If the audioPath is not correct, then the player is not correctly created: application will use the one without valid data, leading to a crash during playback.
Your code can be written making the player optional, which helps preventing the crash:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player: AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
player = initializePlayer()
player?.play()
}
private func initializePlayer() -> AVAudioPlayer? {
guard let path = Bundle.main.path(forResource: "music", ofType: "mp3") else {
return nil
}
return try? AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
}
}
Some changes performed to the code:
player is now optional: there is no need to initialize it twice. Plus if the initialization goes well you can use it without problems, otherwise your app won't crash.
The play method is now in an optional chain
I've moved the initialization of the player in a separate private methods, to maintain the code readable. Feel free to change it, it is just a suggestion.
I've got it. The issue is that the file isn't being coping to my app bundle. To fix it:
Click your project
Click your target
Select Build Phases
Expand Copy Bundle Resources
Click '+' and select your file.
Thanks Denis Hennessy
In my login screen of my Ios app I am trying to display a video. I saw on stack overflow a great example on how to do such thing. I tried the code out for myself and ran into an error. I was going to comment my error on the original post but my account did not have enough reputation to do so. My code when I run on my simulated device returns to me an error that says:
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
I managed to track down there error using breakpoints to line 12 which is avPlayer = AVPlayer(url: video!)
Though here is my full code:
import AVFoundation
import UIKit
class VideoBackgroundController: UIViewController {
var avPlayer: AVPlayer!
var avPlayerLayer: AVPlayerLayer!
var paused: Bool = false
override func viewDidLoad() {
let video = Bundle.main.url(forResource:"space", withExtension: "mp4")
//This is where my the error happens
avPlayer = AVPlayer(url: video!)
avPlayerLayer = AVPlayerLayer(player: avPlayer)
avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
avPlayer.volume = 0
avPlayer.actionAtItemEnd = .none
avPlayerLayer.frame = view.layer.bounds
view.backgroundColor = .clear
view.layer.insertSublayer(avPlayerLayer, at: 0)
NotificationCenter.default.addObserver(self,
selector: #selector(playerItemDidReachEnd(notification:)),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: avPlayer.currentItem)
}
func playerItemDidReachEnd(notification: Notification) {
let p: AVPlayerItem = notification.object as! AVPlayerItem
p.seek(to: kCMTimeZero)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
avPlayer.play()
paused = false
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
avPlayer.pause()
paused = true
}
}
And I do have a mp4 video named "space" in my project files.
Any explanation to how or why this is happening and what actions I can take to fix this issue would be greatly appreciated.
I have checked and your code is running fine.
Just check that, the video should be under in your "Copy bundle Resources" of "Build Phases" tab in Target .
If it is not there , Please add the same as in below screenshots.
You are assigning non optional value of video. Make it optional, ? Swift means – It can have a value, but it can also be nil. It is defined by “?”.Please look below code
avPlayer = AVPlayer(url: video?)
if avPlayer != nil
{ // Video url is not empty
}
else
{ // It is empty
}
Whenever I run the project, it pulls up the video player, but the video doesn't play
.
How do I fix this? In case the code in the picture isn't clear enough, here is the code:
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
let avPlayerViewController = AVPlayerViewController()
var avPlayer:AVPlayer?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from nib.
let urlPathString = Bundle.main.path(forResource: "small", ofType: "mp4")
if urlPathString != nil {
let movieUrl = NSURL(fileURLWithPath: "/Users/kevingerman/Desktop/Pioneer News Season 2 Episode 1.mp4")
self.avPlayer = AVPlayer(url: movieUrl as URL)
self.avPlayerViewController.player = self.avPlayer
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func playButtonTapped(_ sender: AnyObject) {
//Trigger the video to play
self.present(self.avPlayerViewController, animated: true) { () -> Void in self.avPlayerViewController.player?.play() }
}
}
The solutions suggested in the comment, and the one #Guan has answered are both correct.
Your urlPathString is actually nil here,
To make it work -
1- Either add the Target Membership, as suggested in the comment and the answer above or
Do the following
1.1- Delete the small.mp4 from bundle, make sure you move it to trash
2.1 - Go to trash and drag and drop your mp4 file into the project again, you will get a window like this -
While adding it back make sure you -
Check the projectTarget checkbox like the screenshot below -
Make sure the file name is small.mp4
Make sure your urlPathString is not nil.
I don't know what the following code mean:
let movieUrl = NSURL(fileURLWithPath: "/Users/kevingerman/Desktop/Pioneer News Season 2 Episode 1.mp4")
I think the simulator can not get the path of file which in your mac.(I'm not sure, I haven't do this before).
You can check the file's target membership.
The code may work like this:
var urlPaht = Bundle.main.url(forResource: "small", withExtension:"mp4")
if urlPaht == nil {
urlPaht = NSURL(fileURLWithPath: "/Users/kevingerman/Desktop/Pioneer News Season 2 Episode 1.mp4")
}
self.avPlayer = AVPlayer(url: movieUrl as URL)
self.avPlayerViewController.player = self.avPlayer