Button triggering video to open and play - ios

I am very new to coding and have no experience.
I have found a way to make a video play but it autoplays / autopens. I need the video to only open and play when a button is pressed. Please can someone help me tweak my code to do this.
This is my current code:
import UIKit
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
var playerviewcontroller = AVPlayerViewController()
var playerview = AVPlayer ()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(animated: Bool) {
var fileURL = NSURL(fileURLWithPath:"/Users/MorganEvans/Documents/Apps/Warm Up/Video View/Video View/ViewController.swift")
playerview = AVPlayer(URL: fileURL)
playerviewcontroller.player = playerview
self.presentViewController(playerviewcontroller, animated: true){
self.playerviewcontroller.player?.play()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Try this:
#IBAction func playMusic(sender: AnyObject) {
var fileURL = NSURL(fileURLWithPath:"/Users/MorganEvans/Documents/Apps/Warm Up/Video View/Video View/ViewController.swift")
playerview = AVPlayer(URL: fileURL)
playerviewcontroller.player = playerview
self.presentViewController(playerviewcontroller, animated: true){
self.playerviewcontroller.player?.play()
}
}
You can simply put it anywhere in your ViewController, as long as it is not inside another function.
Then connect it with a button in your storyboard:

this is how a button would set up to look, this example is pulling a movie from firebase but other than that this is how it would look
#IBAction func playV(sender: UIButton) {
let amovieUrl:NSURL? = NSURL(string: "https://firebasestorage.googleapis.com/v0/b/messenger-test-d225b.appspot.com/o/test%2FTestVideo.mov?alt=media&token=bd4ccba3-b446-43bc-809e-b1152aa3c2ff")
if let aurl = amovieUrl {
self.avPlayer = AVPlayer(url: aurl as URL)
self.avPlayerViewController.player = self.avPlayer
self.present(self.avPlayerViewController, animated: true) { () -> Void in
self.avPlayerViewController.player?.play()
}
}
}

Create an Action Connection as explained here.
Move that code in viewDidAppear to the action you created in step 1.
Profit.
Also, you don't need those default implementation for viewDidLoad and didReceiveMemoryWarning:
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
var playerviewcontroller = AVPlayerViewController()
var playerview = AVPlayer ()
#IBAction func yourActionForButton(sender: UIButton) {
// Your code.
}

Related

why video is not getting played only showing loader in swift

I am trying to play the video from the web url it showing buffering loader only but not getting played I have used the following code.
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let url = URL(string: "https://sandbox-api.digiboxx.com/uploads/E2D6024483AB4B04/1602945683_sample_640x360.mp4")!
playVideo(url: url)
}
func playVideo(url: URL) {
let player = AVPlayer(url: url)
let vc = AVPlayerViewController()
vc.player = player
self.present(vc, animated: true) { vc.player?.play() }
}
I tried your URL just in the browser (Safari) on my computer and nothing plays. So I think something is wrong with the URL or the file at the other end.
I tested your link and the video is loading, so I don't know why your code isn't working ...
This is how I use VideoPlayer in Swift :
import UIKit
import AVKit
class MediaManager: UIViewController {
var player = AVPlayer()
override func viewDidLoad() {
super.viewDidLoad()
play(url: "yourUrl")
}
func play (url: String) {
player = AVPlayer(url: URL(string: url)!)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.view.present(playerViewController, animated: false) { self.player.play() }
}
}
Try with my code and tell me if it's okay for you

How to play video in ios swift

I am new to ios programming, actually I need to stream video URL but i am unable to stream video URL using avplayer, but using avplayer downloaded file i am able to play.Actual problem is my file format is different
for example my file name is like this song.apa but it is song.mp4
code:
let avplayerController = AVPlayerViewController()
var avPlayer:AVPlayer?
override func viewDidLoad()
{
super.viewDidLoad()
let movieUrl = URL.init(string: "http://techslides.com/demos/sample-videos/small.3gp")
self.avPlayer = AVPlayer.init(url: movieUrl!)
self.avplayerController.player = self.avPlayer
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func playVideo(_ sender: Any)
{
self.present(self.avplayerController, animated: true) {
self.avplayerController.player?.play()
}
}
In Swift 3
import Foundation
import AVFoundation
import MediaPlayer
import AVKit
func play()
{
let player = AVPlayer(url: "Your Url")
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true)
{
playerViewController.player!.play()
}
}
You cant play this particular link (http://techslides.com/demos/sample-videos/small.3gp) using AVPlayer or AVPlayerViewController because that file is in AMR (Adaptive Multi-Rate, a format for speech) - which is not supported since iOS 4.3
Some of 3gp files can be played but only ones that have video and audio streams supported by Apple.
In Swift 3, try this code for playing video in project
import UIKit
import AVKit
import AVFoundation
import MediaPlayer
import MobileCoreServices
class VideoPlayerViewController: UIViewController,AVPlayerViewControllerDelegate {
//MARK: - Outlet -
#IBOutlet weak var viewVidioPlayer: UIView!
//MARK: - Variable
//MARK: - View Life Cycle -
override func viewDidLoad() {
super.viewDidLoad()
}
//MARK: - Action -
//for Playing Video
#IBAction func btnvideoPlayClicked(_ sender: UIButton) {
self.videoPlay()
}
func videoPlay()
{
let playerController = AVPlayerViewController()
playerController.delegate = self
let bundle = Bundle.main
let moviePath: String? = "http://techslides.com/demos/sample-videos/small.3gp"
let movieURL = URL(fileURLWithPath: moviePath!)
let player = AVPlayer(url: movieURL)
playerController.player = player
self.addChildViewController(playerController)
self.view.addSubview(playerController.view)
playerController.view.frame = self.view.frame
player.play()
}
//MARK: - other Function -
func playerViewControllerWillStartPictureInPicture(_ playerViewController: AVPlayerViewController){
print("playerViewControllerWillStartPictureInPicture")
}
func playerViewControllerDidStartPictureInPicture(_ playerViewController: AVPlayerViewController)
{
print("playerViewControllerDidStartPictureInPicture")
}
func playerViewController(_ playerViewController: AVPlayerViewController, failedToStartPictureInPictureWithError error: Error)
{
print("failedToStartPictureInPictureWithError")
}
func playerViewControllerWillStopPictureInPicture(_ playerViewController: AVPlayerViewController)
{
print("playerViewControllerWillStopPictureInPicture")
}
func playerViewControllerDidStopPictureInPicture(_ playerViewController: AVPlayerViewController)
{
print("playerViewControllerDidStopPictureInPicture")
}
func playerViewControllerShouldAutomaticallyDismissAtPictureInPictureStart(_ playerViewController: AVPlayerViewController) -> Bool
{
print("playerViewControllerShouldAutomaticallyDismissAtPictureInPictureStart")
return true
}
}
I hope it's work for you,
thank you
heres an example of streaming video..
override func viewDidLoad() {
super.viewDidLoad()
let player = AVPlayer(url: URL(string: "http://techslides.com/demos/sample-videos/small.mp4")!)
let controller = AVPlayerViewController()
present(controller, animated: true) { _ in }
controller.player = player
addChildViewController(controller)
view.addSubview(controller.view)
controller.view.frame = CGRect(x: 50, y: 50, width: 300, height: 300)
controller.player = player
controller.showsPlaybackControls = true
player.isClosedCaptionDisplayEnabled = false
player.play()
}
you can use YoutubePlayerView for playing youtube videos, and for else formats you can use UIWebView. For doing so, simply use if-else block,
if movieUrl.contains("youtube.com/") {
var videoId: String = extractYoutubeId(fromLink: movieUrl)
youtubePlayerView.load(withVideoId: videoId)
} else {
webView = UIWebView(frame: CGRect(x: 0, y: 0, width: 288, height: 277))
webView.delegate = self
webView.backgroundColor = UIColor.black
webView?.loadRequest(movieUrl)
}
For Swift 3 play video from URL
//AVPlayerViewControllerDelegate // example : class TestAudioVideoVC: UIViewController,AVPlayerViewControllerDelegate
func videoPlay()
{
let playerController = AVPlayerViewController()
playerController.delegate = self
let videoURL = NSURL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
let player = AVPlayer(url: videoURL! as URL)
playerController.player = player
self.addChildViewController(playerController)
self.view.addSubview(playerController.view)
playerController.view.frame = CGRect(x: 0, y: 64, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 64)
playerController.showsPlaybackControls = true
player.play()
}
//MARK: - AVPlayerViewController Delegate -
func playerViewControllerWillStartPictureInPicture(_ playerViewController: AVPlayerViewController){
print("playerViewControllerWillStartPictureInPicture")
}
func playerViewControllerDidStartPictureInPicture(_ playerViewController: AVPlayerViewController)
{
print("playerViewControllerDidStartPictureInPicture")
}
func playerViewController(_ playerViewController: AVPlayerViewController, failedToStartPictureInPictureWithError error: Error)
{
print("failedToStartPictureInPictureWithError")
}
func playerViewControllerWillStopPictureInPicture(_ playerViewController: AVPlayerViewController)
{
print("playerViewControllerWillStopPictureInPicture")
}
func playerViewControllerDidStopPictureInPicture(_ playerViewController: AVPlayerViewController)
{
print("playerViewControllerDidStopPictureInPicture")
}
func playerViewControllerShouldAutomaticallyDismissAtPictureInPictureStart(_ playerViewController: AVPlayerViewController) -> Bool
{
print("playerViewControllerShouldAutomaticallyDismissAtPictureInPictureStart")
return true
}
Play video in swift 5
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func playVideoUsingURL(_ sender: Any) {
playGlobalVideo()
}
#IBAction func playVideoFromLocalDrive(_ sender: Any) {
playLocalVideo()
}
func playGlobalVideo() {
guard let videoURL = URL(string: "http://static.videokart.ir/clip/100/480.mp4") else {
return
}
let player = AVPlayer(url: videoURL)
let vc = AVPlayerViewController()
vc.player = player
present(vc, animated: true) {
player.play()
}
}
func playLocalVideo() {
guard let videoPath = Bundle.main.path(forResource: "movie", ofType: "mov") else {
return
}
let player = AVPlayer(url: URL.init(fileURLWithPath: videoPath))
let playCtr = AVPlayerViewController()
playCtr.player = player
present(playCtr, animated: true) {
player.play()
}
}
}

Close AVPlayer when movie is complete

I am making a simple iPad app to play a movie when a button is pressed. The movie plays and when the movie is finished I want to close AVPlayerView so it goes back to the main screen.
Currently when the video finishes it stays on the last frame.
My ViewController.Swift at the moment.
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
//MARK : Properties
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
//MARK: Actions
#IBAction func playButton(_ sender: AnyObject) {
let movieURL = Bundle.main.url(forResource: "ElephantSeals", withExtension: "mov")!
let player = AVPlayer(url: movieURL as URL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
playerViewController.player!.play()
}
// player.actionAtItemEnd = playerViewController.dismiss(animated: true)
}
}
As you can see, I think there might be something in actionAtItemEnd, but I'm not sure how to implement it.
Thank you.
This is working code in swift 5.3 and iOS 14.2, try this and let me know...:)
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
let playerViewController = AVPlayerViewController()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func playButton(_ sender: AnyObject) {
let movieURL = Bundle.main.url(forResource: "ElephantSeals", withExtension: "mp4")!
let player = AVPlayer(url: movieURL as URL)
playerViewController.player = player
NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerViewController.player?.currentItem)
self.present(playerViewController, animated: true) {
self.playerViewController.player!.play()
}
}
#objc func playerDidFinishPlaying(note: NSNotification) {
self.playerViewController.dismiss(animated: true)
}
}
You can download sample project for same from here
https://github.com/deepakiosdev/AVPlayerViewControllerDemo
Swift 4
let playerController = AVPlayerViewController()
private func playVideo() {
guard let path = Bundle.main.path(forResource: "p810", ofType:"mp4") else {
debugPrint("video.m4v not found")
return
}
let player = AVPlayer(url: URL(fileURLWithPath: path))
playerController.player = player
NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerController.player?.currentItem)
present(playerController, animated: true) {
player.play()
}
}
#objc func playerDidFinishPlaying(note: NSNotification) {
playerController.dismiss(animated: true, completion: nil)
}
Using NSNotificationCenter you can do this .
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: videoPlayer!.currentItem)
#objc func playerDidFinishPlaying(note: NSNotification) {
// here you can do your dismiss controller logic
AVPlayerViewController.dismiss(animated: true)
print("Video Finished")
}
here is objective c code
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(nextVideo:) name:AVPlayerItemDidPlayToEndTimeNotification object:playerViewController.player.currentItem];
Invoke AVPlayerViewControllerDelegate.
In viewDidLoad initialize the delegate and implement this method
func playerViewControllerDidStopPictureInPicture(AVPlayerViewController) {
AVPlayerViewController.dismiss(animated: true)
}
https://developer.apple.com/reference/avkit/avplayerviewcontrollerdelegate

AVPlayer playback with Swift 2.0

I'm having issues with playing back a video. All I want is for the video to playback after the launch image has been displayed. I followed this (https://www.youtube.com/watch?v=iYATp9--VIM) tutorial but when I simulated I received a blank screen.
Here is the code:
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
#IBOutlet var videoView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.setupView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupView() {
let path = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("streetview", ofType: "mov")!)
let player = AVPlayer(URL:path)
let newLayer = AVPlayerLayer(player: player)
newLayer.frame = self.videoView.frame
self.videoView.layer.addSublayer(newLayer)
newLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
player.play()
}
}
Please help me if you can!
If you're just getting a blank black screen, it would generally point to an issue with the source of the video. I'd check that you're spelling the name of your file correctly and that it definitely is a .mov file.
I use this code to launch the AVPlayer and play my video. It plays a video from a URL from the internet. I have it inside my button function so it happens when the user presses the play button I have:
let videoURL = NSURL(string: "YOUR URL") {
let player = AVPlayer(URL: videoURL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.presentViewController(playerViewController, animated: true) {
playerViewController.player!.play()
}
I can confirm this works for me in Swift 2.0

Error when trying to play video in Xcode 7 / Swift 2

I am trying to play a video inside a view controller when I enter it, but a get one error, listed below.Not too familiar with video playback, so is it supposed to be in a viewcontroller and how do I fix that error?The video is stored in xcode. Thanks.
import UIKit
import MediaPlayer
import AVFoundation
class AuroraViewController: UIViewController {
#IBOutlet var AuroraViewController: UIView!
var moviePlayer: AVPlayer?
private func playVideo() {
if let path = NSBundle.mainBundle().pathForResource("Aurora", ofType:"mp4") {
let url = NSURL(fileURLWithPath: path)
The line below is where I get the error of: Type of expression is ambiguous without more context
moviePlayer = AVPlayer(contentURL: url) {
self.moviePlayer = moviePlayer
moviePlayer.AuroraViewController.frame = self.AuroraViewController.bounds
moviePlayer.prepareToPlay()
moviePlayer.scalingMode = .AspectFill
self.AuroraViewController.addSubview(moviePlayer.view)
}
} else {
debugPrint("Ops, something wrong when playing video.m4v")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
playVideo()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
UPDATE Correct code:
import UIKit
import AVFoundation
import AVKit
class AuroraViewController: AVPlayerViewController {
private func playVideo() {
if let path = NSBundle.mainBundle().pathForResource("Aurora", ofType: "mp4") {
let url = NSURL(fileURLWithPath: path)
player = AVPlayer(URL: url)
}
else {
println("Oops, could not find resource Aurora.mp4")
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
playVideo()
}
}
This was a 'total re-write'.
The following did the job:
Add "AVKit.framework" to the "Build Phases" -> "Link Binary With Libraries" in Project settings.
In Storyboard, change the identity of your UIViewController to be AuroraViewController.
The resulting code then is all that's needed:
import UIKit
import AVFoundation
import AVKit
class AuroraViewController: AVPlayerViewController {
private func playVideo() {
if let path = NSBundle.mainBundle().pathForResource("Aurora", ofType: "mp4") {
let url = NSURL(fileURLWithPath: path)
player = AVPlayer(URL: url)
}
else {
println("Oops, could not find resource Aurora.mp4")
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
playVideo()
}
}

Resources