AVFoundation and video - ios

I am trying to use AVFoundation, AVPlayer and AVPlayerViewController to show a video. Does anyone know of any good tutorials out there that does NOT use MPMoviePlayer?
Please let m eknow!
thank you!

AVPlayerViewController
AVPlayerViewController is the AVKit ViewController that hides away most of the complexity involved with dealing directly with AVFoundation. Its very simple and intuitive, if you check the AVPlayerViewController Class Reference you will notice that it does not hold that many properties, if you want to initialise one and attribute a video to it, you have three options ( that I can recall ).
Initialise it in code and set the frame of it;
Subclass it and call it when you wanna use it;
Use Storyboards / nibs to allocate a AVKit Player View Controller.
Either way its up to you and this is a common pattern among iOS developers, so it shouldn't strike as a surprise to you unless you are a complete beginner. Please note that for any of these ways of creating an AVPlayerViewController, you have to initialise the AVPlayer object with an AVPlayerItem or an URL carrying the video you want to display.
Subclassing AVPlayerViewController-Swift
Obs. This is the swift example, but the Objective-C one follows the same pattern, the only change is the syntax of each language.
class AVKitPlayerViewController: AVPlayerViewController {
override func viewDidLoad() {
super.viewDidLoad()
// get the video URL
let videoURL = NSBundle.mainBundle().URLForResource("Test", withExtension: ".mov")
// Initialise with URL
player = AVPlayer(URL: videoURL!)
// Initialise with AVPlayerItem
let playerItem = AVPlayerItem(URL: videoURL!)
player = AVPlayer(playerItem: playerItem)
// If you want custom controls showsPlaybackControls should be false
// Then you must create your own buttons
//showsPlaybackControls = false
}
}
AVFoundation
AVFoundation is a very large and interesting framework, you can do a lot of advanced and interesting stuff with it. I would encourage you to go read the docs and checkout these WWDC-2015 sample code:
AVFoundationPiPPlayer: Picture-in-Picture Playback with AVKit
AVFoundationQueuePlayer-iOS: Using a Mixture of Local File Based Assets and HTTP Live Streaming Assets with AVFoundation
AVFoundationSimplePlayer-iOS: Using AVFoundation to Play Media
AVFoundation Programming Guide
AVFoundation Programming Guide
I hope this helps you. Happy Coding. :smile:

Related

AVPlayer on Swift app shows a black screen but plays audio when playing video

New to Swift! I am trying to have the app play a video from my Resources upon pressing a button. I have this method in my ViewController:
if let path = Bundle.main.path(forResource: "Cypress", ofType: "mov") {
let player = AVPlayer(url: URL(fileURLWithPath: path))
// Create a new AVPlayerViewController and pass it a reference to the player.
let controller = AVPlayerViewController()
controller.player = player
// Modally present the player and call the player's play() method when complete.
self.present(controller, animated: true) {
player.play()
}
}
However, when the video begins to play, it is a black screen but the audio is playing properly. Are there any quick fixes to this? I am using Xcode version 12.2. Any advice would be greatly appreciated thanks :)
The problem is with the video file itself / the encoding.
Deceptively, the Quicktime ".mov" format is not a video codec, but rather audio/video container format that can contain video and audio (and some other things) in any number of compression codecs (h.264, mpeg2, ProRes, MJPEG, AAC, mp3, etc.) … Your files don't work because they include video compressed with a codec which iOS does not support.
From #alexkent in this SO answer on another post.
I don't think a .mov is necessarily not going to work for you, but you'd have to make sure it was encoded in a way that is iOS-compatible. So as you mentioned in the comments, using .mp4 ensures the video is encoded in an iOS-compatible fashion.

Embedding videos in iOS app

I'm fairly new to iOS development, but I'm confident with the basics (basic interface, user interaction, logic). What I want to do now is create an app that streams/downloads a video from a personal recording website (so login required by user), and then allows basic editing (trimming) and sharing to different social media, like twitter, facebook, youtube, etc... I have absolutely no experience with this.
My research so far has pointed me towards webViews and use of AVKit import, and they seem appropriate, but I was hoping for more concrete advice.
What do I look into? Where can I start?
Its pretty easy to give a URL to AVPlayer and have it stream a video into the layer. I usually add the layer into a view and use autolayout on that view to resize it (although you can also subclass UIView and override layerClass and make the videoLayer the view's backing layer if you want). This code will stream from a remote URL or if you download the file to the documents directory and get a URL to it you can play a local file also.
let playerLayer = AVPlayerLayer()
let player = AVPlayer(playerItem: AVPlayerItem(asset: AVAsset(url: url), automaticallyLoadedAssetKeys: ["playable"]))
playerLayer = AVPlayerLayer(player: player)
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
playerLayer.frame = videoView.bounds
videoView.isHidden = false
videoView.layer.addSublayer(playerLayer)
playerLayer.player?.play()

Play a video from Youtube in a AVPlayerViewController in Swift [duplicate]

This question already has answers here:
How to embed a Youtube video into my app?
(7 answers)
Closed 7 years ago.
Okay so I'm looking to play film trailers in my app. The user will press a button, and then it plays the video. I have added the import AVKit and import AVFoundation lines to my file. This is the code I have so far for making the video play:
#IBAction func playTrailerPressed(sender: AnyObject) {
let videoURL = NSURL(string: "https://youtu.be/d88APYIGkjk")
let player = AVPlayer(URL: videoURL!)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.presentViewController(playerViewController, animated: true) {
playerViewController.player!.play()
}
}
This seems to launch an AVPlayerViewController, but doesn't play the video from YouTube. Instead, I get the below:
I have tried both the sharing and embedding link from YouTube, but neither work. If I use a link which has the video file name at the end, it plays it fine, for example: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"- So I know the code works.
Does anyone know if this is possible to use this way with a YouTube video? (I have also tried trailers from IMDb and Apple, but it's the same).
Thanks for your help!
AVPlayer only plays movie files, and YouTube videos aren't directly exposed as movie files at their URL. It looks like the preferred way to handle YouTube videos is to embed a web view into your app. See this page for information from Google on how to do that.

AVPlayer hear audio but no video for Mp4 file TVOs

I am trying to play a remote mp4 file which is there on the web using AVPlayer on TVOS. When i try to play the video i can hear the audio but there is no video and whole screen is blank. I have read many articles about that which say that i should turn off ATS (I did that. However my url is HTTPS) and i set the frame also in viewDidLayoutSubviews, but still unable to make it work. Here is my code, if some could help me in solving this issue then it will be a great help since i am scratching my head here and there since yesterday.
I am not writing the exact Url for some privacy issues.
import Foundation
import UIKit
import AVKit
class PlayViewController : UIViewController {
var moviePlayer : AVPlayer?
override func viewDidLoad() {
super.viewDidLoad()
print("In PlayViewController View Did Load")
let movieUrl = NSURL.init(string: "Some Amazon Url.mp4")!
moviePlayer = AVPlayer.init(URL: movieUrl)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let avPlayerLayer = AVPlayerLayer.init(layer: moviePlayer!)
avPlayerLayer.frame = CGRectMake(0.0, 0.0, 1024.0, 768.0)
self.view.layer.addSublayer(avPlayerLayer)
moviePlayer?.play()
}
}
The URL is somehow indicating HTTP(S) streaming, right?
Well, I also made my experience while trying to play a video stream from a set-top-box like a DVB receiver through its Web-Interface. It did not work (at least when I tried with tvOS 9.0). According to Apple documentation the video streams have to comply to the HTTP Streaming protocol they describe. It requires, that HTTP streams are split into small chunks of video snippets of a few seconds length. See https://developer.apple.com/library/tvos/referencelibrary/GettingStarted/AboutHTTPLiveStreaming/about/about.html
At the end I gave up and switched to use VLCKit from videolan.org. After some back and forth this works fine in my App (vuplusTV).

How to use AVFoundation to show subtitle while showing a video?

I'm building an app where I show a video, I need to show a subtitle inside the video. I couldn't find a way to do it. Is this doable using AVFoundation ? Or should I hock-up something around it.
player = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
player.numberOfLoops = -1 // play indefinitely
player.prepareToPlay()
player.play()
The only way is create a separate subtitles layer (CATextLayer) and add as a sublayer to the player layer. You can set up a periodic time observer to trigger every second to update the subtitles.
You can find a sample project here SubRipForCocoa. Please note that, you have to write the same concept in Swift.

Resources