動くソース
https://github.com/Ryosuke-Hujisawa/Add-image-logo-to-movie-and-save
やりたいこと
動画に画像のロゴを追加して保存したいです。
手順
- CALayerの作成
- 合成用コンポジション作成
- インストラクション作成
- インストラクションを合成用コンポジションに設定
- exportする
わからないこと
動画に画像のロゴを追加する際に、必要な手順の論理が、解説記事を読んでもいまいちつかめません。だから、上記のような時系列で動画に画像のロゴを追加するために必要なものが揃っているのかも定かではありません。
補足
下記のような実装でアプリを実行すると、ドキュメントフォルダに、動画ファイルが生成されません。exportを消してみれば、、ドキュメントフォルダに、動画ファイルが生成され正常に動きます。
実装
swift
1 2 //動画トリミング 3 func createAudioFileFromAsset(_ asset: AVAsset){ 4 5 6 7 // ロゴのCALayerの作成 8 let logoImage: UIImage = UIImage(named: "iwk.jpg")! 9 let logoLayer: CALayer = CALayer() 10 logoLayer.contents = logoImage.cgImage 11 logoLayer.opacity = 0.9 12 // 親レイヤーを作成 13 let parentLayer: CALayer = CALayer() 14 parentLayer.frame = CGRect(x: 0, y: 0, width: 100, height: 100) 15 parentLayer.addSublayer(logoLayer) 16 17 18 // 合成用コンポジション作成 19 let videoComp: AVMutableVideoComposition = AVMutableVideoComposition() 20 let videoSize: CGSize = videoAssetSourceTrack.naturalSize 21 videoComp.renderSize = videoSize 22 videoComp.frameDuration = CMTimeMake(1, 30) 23 videoComp.animationTool = AVVideoCompositionCoreAnimationTool.init(postProcessingAsVideoLayer: parentLayer, in: parentLayer) 24 25 26 // インストラクション作成 27 let instruction: AVMutableVideoCompositionInstruction = AVMutableVideoCompositionInstruction() 28 instruction.timeRange = CMTimeRangeMake(kCMTimeZero, comp.duration) 29 let layerInstruction: AVMutableVideoCompositionLayerInstruction = AVMutableVideoCompositionLayerInstruction.init(assetTrack: videoAssetSourceTrack) 30 instruction.layerInstructions = [layerInstruction] 31 32 // インストラクションを合成用コンポジションに設定 33 videoComp.instructions = [instruction] 34 35 36 37 let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as URL 38 let filePath = documentsDirectory.appendingPathComponent("rendered-audio.m4v") 39 //filePath.videoAssetTrack.naturalSize = 320.0 40 if let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPreset640x480){ 41 //exportSession.naturalSize.preferredTransform = 320.0 42 exportSession.canPerformMultiplePassesOverSourceMediaData = true 43 exportSession.outputURL = filePath 44 exportSession.timeRange = CMTimeRangeMake(kCMTimeZero, asset.duration) 45 exportSession.outputFileType = AVFileTypeQuickTimeMovie 46 //exportSession.videoComposition = videoComp 47 exportSession.exportAsynchronously { 48 _ in 49 print("finished: \(filePath) : \(exportSession.status.rawValue) ") 50 } 51 } 52 53 } 54
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。