How to add a Fade In and Fade Out effect on Video AVAsset in Swift3 iOS

Multi tool use
Multi tool use


How to add a Fade In and Fade Out effect on Video AVAsset in Swift3 iOS



I am developing a Video application in Swift3. Where I have to convert any text to Video and then have to add a Fade In and Fade Out effect and post the Fade effect Video to server. I don't have to use any Third Party Library for Fade effect.


Video


Swift3


Video


Fade In and Fade Out


Fade effect Video


Third Party Library


Fade effect



I can able to convert my Text to a Video, My problem is how can I add Fade In and Fade Out on Video AVAsset.


Text


Video


Fade In and Fade Out


Video


AVAsset



Can anyone suggest me to achieve this. I cannot find any recent answers to this problem. Thanks for any help!




1 Answer
1



AVVideoCompositionLayerInstruction



An array of instances of AVVideoCompositionLayerInstruction that specify how video frames from source tracks should be layered and composed.


AVVideoCompositionLayerInstruction



AVMutableVideoCompositionInstruction



An AVVideoComposition object maintains an array of instructions to perform its composition.


AVVideoComposition


instructions



Example Swift4:
I merged videos with fade-in and fade-out effect and change sequence of audio


fade-in


fade-out


func doMerge(arrayVideos:[AVAsset], arrayAudios:[AVAsset], animation:Bool, completion:@escaping Completion) -> Void {

var insertTime = kCMTimeZero
var audioInsertTime = kCMTimeZero
var arrayLayerInstructions:[AVMutableVideoCompositionLayerInstruction] =
var outputSize = CGSize.init(width: 0, height: 0)

// Determine video output size
for videoAsset in arrayVideos {
let videoTrack = videoAsset.tracks(withMediaType: AVMediaType.video)[0]
let assetInfo = orientationFromTransform(transform: videoTrack.preferredTransform)
var videoSize = videoTrack.naturalSize
if assetInfo.isPortrait == true {
videoSize.width = videoTrack.naturalSize.height
videoSize.height = videoTrack.naturalSize.width
}
outputSize = videoSize
}

// Init composition
let mixComposition = AVMutableComposition.init()

for index in 0..<arrayVideos.count {
// Get video track
guard let videoTrack = arrayVideos[index].tracks(withMediaType: AVMediaType.video).first else { continue }

// Get audio track
var audioTrack:AVAssetTrack?
if index < arrayAudios.count {
if arrayAudios[index].tracks(withMediaType: AVMediaType.audio).count > 0 {
audioTrack = arrayAudios[index].tracks(withMediaType: AVMediaType.audio).first
}
}
// Init video & audio composition track
let videoCompositionTrack = mixComposition.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID: Int32(kCMPersistentTrackID_Invalid))

let audioCompositionTrack = mixComposition.addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: Int32(kCMPersistentTrackID_Invalid))

do {
let startTime = kCMTimeZero
let duration = arrayVideos[index].duration

// Add video track to video composition at specific time
try videoCompositionTrack?.insertTimeRange(CMTimeRangeMake(startTime, duration), of: videoTrack, at: insertTime)

// Add audio track to audio composition at specific time
var audioDuration = kCMTimeZero
if index < arrayAudios.count {
audioDuration = arrayAudios[index].duration
}

if let audioTrack = audioTrack {
do {
try audioCompositionTrack?.insertTimeRange(CMTimeRangeMake(startTime, audioDuration), of: audioTrack, at: audioInsertTime)
}
catch {
print(error.localizedDescription)
}
}

// Add instruction for video track
let layerInstruction = videoCompositionInstructionForTrack(track: videoCompositionTrack!, asset: arrayVideos[index], standardSize: outputSize, atTime: insertTime)

// Hide video track before changing to new track
let endTime = CMTimeAdd(insertTime, duration)

if animation {
let timeScale = arrayVideos[index].duration.timescale
let durationAnimation = CMTime.init(seconds: 1, preferredTimescale: timeScale)

layerInstruction.setOpacityRamp (fromStartOpacity: 1.0, toEndOpacity: 0.0, timeRange: CMTimeRange.init(start: endTime, duration: durationAnimation))
}
else {
layerInstruction.setOpacity(0, at: endTime)
}

arrayLayerInstructions.append(layerInstruction)

// Increase the insert time
audioInsertTime = CMTimeAdd(audioInsertTime, audioDuration)
insertTime = CMTimeAdd(insertTime, duration)
}
catch {
print("Load track error")
}
}

// Main video composition instruction
let mainInstruction = AVMutableVideoCompositionInstruction()
mainInstruction.timeRange = CMTimeRangeMake(kCMTimeZero, insertTime)
mainInstruction.layerInstructions = arrayLayerInstructions

// Main video composition
let mainComposition = AVMutableVideoComposition()
mainComposition.instructions = [mainInstruction]
mainComposition.frameDuration = CMTimeMake(1, 30)
mainComposition.renderSize = outputSize

// Export to file
let path = NSTemporaryDirectory().appending("mergedVideo.mp4")
let exportURL = URL.init(fileURLWithPath: path)

// Remove file if existed
FileManager.default.removeItemIfExisted(exportURL)

// Init exporter
let exporter = AVAssetExportSession.init(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality)
exporter?.outputURL = exportURL
exporter?.outputFileType = AVFileType.mp4
exporter?.shouldOptimizeForNetworkUse = true
exporter?.videoComposition = mainComposition

// Do export
exporter?.exportAsynchronously(completionHandler: {
DispatchQueue.main.async {
self.exportDidFinish(exporter: exporter, videoURL: exportURL, completion: completion)
}
})

}





Thank you for your kind reply. As I can see in your code, you are adding Fade effect for each video. correct? Also I need to check with you like Are you also getting the Video audio sound individually in Final Video?
– user2786
Jul 3 at 7:10






Yes i merged more then 5 video with above code with fade in fade out animation.
– Harshal Valanda
Jul 3 at 8:52






I am getting error while using above method, do you have any sample App using above?
– user2786
Jul 3 at 9:06





Which swift version are you using?
– Harshal Valanda
Jul 3 at 9:07





Swift version : 3.0
– user2786
Jul 3 at 9:09






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

V4h,mod3IF,pn,6KacQ,2Xb,xkW GlsYE7x9 dgVjFb,0BK6flH4G8GoU,YrcglyEu8zPSWtv46y1XSHD5nNOzVln7BQRSnEiac6ThQ
aSd6,7BRIL2e,U9pSt5,3FrBeWU,1eUMx7HGKacMkfEo

Popular posts from this blog

PHP contact form sending but not receiving emails

Do graphics cards have individual ID by which single devices can be distinguished?

Create weekly swift ios local notifications