[英]In Production Mode - I got "Operation Stopped" error when exporting video
[英]How to export arbitrary segment of video? “Operation Stopped” error when exporting last X seconds of video
目標是導出某些視頻的任意片段(例如,中間三分之一,最后一半),但是AVAssetExportSession
僅在起點是視頻的起點時成功。
如果cmStartTime
不為0,則AVAssetExportSession
失敗,並顯示以下錯誤:
失敗:可選(錯誤域= AVFoundationErrorDomain代碼= -11841“操作已停止” UserInfo = 0x175872d00 {NSLocalizedDescription =操作已停止,NSLocalizedFailureReason =無法合成視頻。})。
// Create main composition & its tracks
let mainComposition = AVMutableComposition()
let compositionVideoTrack = mainComposition.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: CMPersistentTrackID(kCMPersistentTrackID_Invalid))
let compositionAudioTrack = mainComposition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID(kCMPersistentTrackID_Invalid))
// Get source video & audio tracks
let videoURL = NSURL(fileURLWithPath: fileURL)
let videoAsset = AVURLAsset(URL: videoURL, options: nil)
let sourceVideoTrack = videoAsset.tracksWithMediaType(AVMediaTypeVideo)[0]
let sourceAudioTrack = videoAsset.tracksWithMediaType(AVMediaTypeAudio)[0]
// Define time values for video
let timescale = Int32(600)
let cmStartTime = CMTimeMake(Int64(CGFloat(0.5) * CGFloat(timescale)), timescale)
let cmEndTime = CMTimeMake(10, 1)
let timeRange = CMTimeRangeMake(cmStartTime, cmEndTime)
// Add source tracks to composition
do {
try compositionVideoTrack.insertTimeRange(timeRange, ofTrack: sourceVideoTrack, atTime: cmStartTime)
try compositionAudioTrack.insertTimeRange(timeRange, ofTrack: sourceAudioTrack, atTime: cmStartTime)
} catch {
printError("Error with insertTimeRange while exporting video: \(error)")
}
// Create video composition
let renderSize = compositionVideoTrack.naturalSize
let videoComposition = AVMutableVideoComposition()
videoComposition.renderSize = renderSize
videoComposition.frameDuration = CMTimeMake(Int64(1), Int32(frameRate))
// Add layer instruction to video composition
...
// Apply effects to video
...
// Define export URL
let exportPath = getUniqueTempPath(gMP4File)
let exportURL = NSURL(fileURLWithPath: exportPath)
// Create exporter
let exporter = AVAssetExportSession(asset: mainComposition, presetName: AVAssetExportPresetHighestQuality)!
exporter.videoComposition = videoComposition
exporter.outputFileType = AVFileTypeMPEG4
exporter.outputURL = exportURL
exporter.shouldOptimizeForNetworkUse = true
exporters.append(exporter)
// Export video
exporter.exportAsynchronouslyWithCompletionHandler() {
// Finish stuff
}
問題來自於不了解CMTimeRangeMake
和insertTimeRange
。
CMTimeRangeMake
的第二個值應該是剪輯的持續時間,而不是結束時間。 因此,如果您的開始時間是5秒標記,並且剪輯持續10秒,則第二個值應該是10,而不是15。
該atTime
的參數insertTimeRange
應kCMTimeZero
,因為我們的目標是創建一個新的剪輯。 換句話說,此值表示要在新軌道中從源軌道插入剪輯的位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.