【发布时间】:2017-01-20 10:36:30
【问题描述】:
如果想将慢动作效果应用于视频,scaleTimeRange(timeRange: CMTimeRange, toDuration duration: CMTime) 方法非常有效。
但我注意到它只有在应用于整个视频时才有效。如果是任意时间范围,例如CMTimeRangeMake(_ start: 2, duration: 3) 已通过,该方法似乎根本不起作用。即当导出 mp4 视频时,它没有所需的慢动作效果(从 0:00:02 - 0:00:05)
Q 1) 有没有办法将此scaleTimeRange 方法仅应用于视频的一部分?如果可以,怎么做?
Q2)如果没有,这种慢动作效果如何仅应用于视频的一部分?有没有其他办法?
代码:
var asset: AVAsset?
func setupAsset(){
let videoAsset = AVURLAsset(url: Bundle.main.url(forResource: "Sample", withExtension: "mp4")!)
let comp = AVMutableComposition()
let videoAssetSourceTrack = videoAsset.tracks(withMediaType: AVMediaTypeVideo).first! as AVAssetTrack
let videoCompositionTrack = comp.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: kCMPersistentTrackID_Invalid)
do {
try videoCompositionTrack.insertTimeRange(
CMTimeRangeMake(kCMTimeZero, CMTimeMakeWithSeconds(9 , 600)),
of: videoAssetSourceTrack,
at: kCMTimeZero)
let videoScaleFactor = Int64(3.0)
let videoDuration: CMTime = videoAsset.duration
let tstStartTime = CMTime(value: 2, timescale: videoDuration.timescale)
let tstDuration = CMTime(value: 1 , timescale: videoDuration.timescale)
//1. Applies slow motion correctly (to entire video)
videoCompositionTrack.scaleTimeRange(CMTimeRangeMake(kCMTimeZero , videoDuration), toDuration: CMTimeMake(videoDuration.value * videoScaleFactor, videoDuration.timescale))
//2. Replace with 1 , the exported video plays as is with no slow motion effect
videoCompositionTrack.scaleTimeRange(CMTimeRangeMake(kCMTimeZero , tstDuration), toDuration: CMTimeMake(tstDuration.value * videoScaleFactor, videoDuration.timescale))
// 3. Replace with 1, unexpected behaviour : video only displays first frame for CMTimeMakes's value then proceeds to play video normally.
videoCompositionTrack.scaleTimeRange(CMTimeRangeMake(tstStartTime , tstDuration), toDuration: CMTimeMake(tstDuration.value * videoScaleFactor, videoDuration.timescale))
videoCompositionTrack.preferredTransform = videoAssetSourceTrack.preferredTransform
}catch { print(error) }
asset = comp
}
【问题讨论】:
-
究竟是什么问题“该方法似乎根本不起作用”?
-
视频保存成功,但没有慢动作效果。导出的 mp4 文件与源 mp4 文件相同,帧率相同。
-
CMTimes 的价值是什么?可以贴一下相关代码吗? -
我更新了问题。请看一看。
-
如果你这样做了,请分享代码或提示。
标签: ios swift avfoundation avmutablecomposition