ios - 如何在 iOS Swift 4 中的视频上添加图像水印?

标签 ios swift avfoundation avplayer

我尝试在视频上添加图像叠加并将视频保存到带有视频叠加的设备库。

let myURL = "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"

let url = URL(string:myURL)

player = AVPlayer(url: url!)

avpController.player = player
avpController.player?.play()
avpController.showsPlaybackControls = false


avpController.view.frame.size.height = videoView.frame.size.height

avpController.view.frame.size.width = videoView.frame.size.width

self.videoView.addSubview(avpController.view)

如何在视频上添加图像叠加?任何帮助非常感谢..

最佳答案

我创建了这个

import UIKit
import AVFoundation
import AVKit
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        shareClicked()
    }

     func shareClicked() {

        let url = URL(string:"https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")!

        DispatchQueue.global(qos: .background).async {

            if let urlData = try? Data(contentsOf: url) {


                let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!

                let fileUrl = URL(fileURLWithPath: documentsPath).appendingPathComponent("fffffff.mp4")

                if FileManager.default.fileExists(atPath:fileUrl.path) {

                    try? FileManager.default.removeItem(at:fileUrl)

                    print("removed")
                }

                try? urlData.write(to: fileUrl)


                self.merge(video: fileUrl.path, withForegroundImage:UIImage(named: "images.png")!, completion: { (uuu) in

                            DispatchQueue.main.async {

                                self.play(uuu!)
                            }

                        })


                }

        }

    }
    func play(_ url : URL) {

        DispatchQueue.main.async {

            let vc = AVPlayerViewController()

            vc.player = AVPlayer(url: url)

            vc.player?.externalPlaybackVideoGravity = AVLayerVideoGravity.resizeAspect

            self.present(vc, animated: true, completion: nil)

        }

    }
    private func addAudioTrack(composition: AVMutableComposition, videoUrl: URL) {


        let videoUrlAsset = AVURLAsset(url: videoUrl, options: nil)

        let audioTracks = videoUrlAsset.tracks(withMediaType: AVMediaType.audio)

        let compositionAudioTrack:AVMutableCompositionTrack = composition.addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: CMPersistentTrackID())!

        for audioTrack in audioTracks {
            try! compositionAudioTrack.insertTimeRange(audioTrack.timeRange, of: audioTrack, at: CMTime.zero)
        }
    }


    func merge(
        video videoPath: String,
        withForegroundImage foregroundImage: UIImage,
        completion: @escaping (URL?) -> Void) -> () {

        let videoUrl = URL(fileURLWithPath: videoPath)
        let videoUrlAsset = AVURLAsset(url: videoUrl, options: nil)

        // Setup `mutableComposition` from the existing video
        let mutableComposition = AVMutableComposition()
        let videoAssetTrack = videoUrlAsset.tracks(withMediaType: AVMediaType.video).first!
        let videoCompositionTrack = mutableComposition.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID: kCMPersistentTrackID_Invalid)
        videoCompositionTrack?.preferredTransform = videoAssetTrack.preferredTransform
        try! videoCompositionTrack?.insertTimeRange(CMTimeRange(start:CMTime.zero, duration:videoAssetTrack.timeRange.duration), of: videoAssetTrack, at: CMTime.zero)

        addAudioTrack(composition: mutableComposition, videoUrl: videoUrl)

        let videoSize: CGSize = (videoCompositionTrack?.naturalSize)!
        let frame = CGRect(x: 0.0, y: 0.0, width: videoSize.width, height: videoSize.height)
        let imageLayer = CALayer()
        imageLayer.contents = foregroundImage.cgImage
        imageLayer.frame = CGRect(x: 0.0, y: 0.0, width:50, height:50)


        let videoLayer = CALayer()
        videoLayer.frame = frame
        let animationLayer = CALayer()
        animationLayer.frame = frame
        animationLayer.addSublayer(videoLayer)
        animationLayer.addSublayer(imageLayer)

        let videoComposition = AVMutableVideoComposition(propertiesOf: (videoCompositionTrack?.asset!)!)
        videoComposition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, in: animationLayer)

        let documentDirectory = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first!
        let documentDirectoryUrl = URL(fileURLWithPath: documentDirectory)
        let destinationFilePath = documentDirectoryUrl.appendingPathComponent("result.mp4")

        do {

            if FileManager.default.fileExists(atPath: destinationFilePath.path) {

                try FileManager.default.removeItem(at: destinationFilePath)

                print("removed")
            }



        } catch {

            print(error)
        }


        let exportSession = AVAssetExportSession( asset: mutableComposition, presetName: AVAssetExportPresetHighestQuality)!

       exportSession.videoComposition = videoComposition
        exportSession.outputURL = destinationFilePath
        exportSession.outputFileType = AVFileType.mp4
        exportSession.exportAsynchronously { [weak exportSession] in
            if let strongExportSession = exportSession {
                completion(strongExportSession.outputURL!)

                //self.play(strongExportSession.outputURL!)
            }
        }

    }

}

你会得到这个结果

enter image description here

关于ios - 如何在 iOS Swift 4 中的视频上添加图像水印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56619053/

相关文章:

ios - 在我的 Facebook 应用程序控制台中找不到客户端 OAuth 设置部分

ios - UIDatePicker 不遵守夏令时

swift - 从 'text' 快速调用一个函数

swift - 在 UICollectionViewCompositionalLayout/UICollectionViewDiffableDataSource 的两个不同部分显示相同的对象

swift/Spritekit : Play music through specific scenes

iphone - 到底什么是私有(private) API,为什么 Apple 会拒绝使用 iOS 应用程序?

iphone - 缓存 UIView 对象作为提高性能的一种方式

ios - 写入应用程序支持目录

iphone - 在 iPhone 上无需音量 slider 即可更改音量

iPhone SDK 4 AVFoundation - 如何正确使用 captureStillImageAsynchronouslyFromConnection?