Daniel Dramond
Daniel Dramond

Reputation: 1598

Swift: How do I add an image/text on top of my AVPlayerLayer for it to be a part of the video?

I am really struggling with getting an image or text to actually be a part of my video, similar to Snapchats add text/stickers feature. I don't want it to just sit on top of my video but actually be on the video itself so when it is saved, it shows. Any help would be highly appreciated and marked as answer. Thanks guys. Code is below...

import UIKit
import AVFoundation
import AVKit
import Photos

class VideoViewController: UIViewController {

    override var prefersStatusBarHidden: Bool { return true }

    var videoURL: URL
    var player: AVPlayer?
    var playerLayer: AVPlayerLayer?

    init(videoURL: URL) {
        self.videoURL = videoURL
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        UIApplication.shared.keyWindow?.backgroundColor = .black
        self.view.backgroundColor = .black

        self.player = AVPlayer(url: videoURL)
        self.playerLayer = AVPlayerLayer(player: self.player)
        self.playerLayer?.frame = self.view.frame
        self.playerLayer?.backgroundColor = UIColor.black.cgColor
        self.view.layer.addSublayer(playerLayer!)

        guard player != nil else { return }
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        player?.play()
    }

Upvotes: 5

Views: 2078

Answers (1)

Tiko
Tiko

Reputation: 570

For preview you can just add CALayers or UIViews on the top of AVPlayerLayer, if You have CAAnimations on that layers You can use AVSynchronizedLayer. See docs for more info

For export you need to use AVVideoCompositionCoreAnimationTool. See docs for more info.

Here You can find a tutorial about usage of AVVideoCompositionCoreAnimationTool. (its in Objective-C, but I think it wouldn't be hard to translate it to swift)

Upvotes: 6

Related Questions