Swift开发:CMTimeRange设置时出现警告问题求助
Hey, let's work through that warning you're seeing when setting up CMTimeRange for your export session. Even though your printed startTime and endTime look normal, there are a few common pitfalls that might be triggering the warning. Here's what to check:
1. Make sure start time doesn't come after end time
While the raw values might look okay, differences in timescale (the units used to measure time) can make a startTime appear smaller numerically but actually be later than endTime when evaluated properly. Always use CMTimeCompare to validate this:
if CMTimeCompare(startTime, endTime) > 0 { print("Warning: Start time is later than end time!") // Handle this case (swap times, show error, etc.) return }
2. Ensure the time range fits within the asset's total duration
AVAssetExportSession will warn if your timeRange extends beyond the bounds of the source asset. Add a check against the asset's duration:
let assetTotalDuration = asset.duration if CMTimeCompare(startTime, kCMTimeZero) < 0 || CMTimeCompare(endTime, assetTotalDuration) > 0 { print("Warning: Time range falls outside the asset's duration!") return }
3. Use CMTimeRangeMakeWithStartAndDuration for safer initialization
Instead of creating the range directly with start and end, building it from start time and duration can avoid precision issues that sometimes trigger warnings:
let clipDuration = CMTimeSubtract(endTime, startTime) let safeTimeRange = CMTimeRangeMake(start: startTime, duration: clipDuration) exportSession.timeRange = safeTimeRange
4. Align the timescale of your trimmer times with the asset
If the startTime/endTime from your trimmerView use a different timescale than the source asset, this can cause unexpected parsing issues. Convert them to match the asset's timescale:
let targetTimescale = asset.duration.timescale let convertedStartTime = CMTimeConvertScale(startTime, targetTimescale, .roundHalfAwayFromZero) let convertedEndTime = CMTimeConvertScale(endTime, targetTimescale, .roundHalfAwayFromZero) let alignedTimeRange = CMTimeRange(start: convertedStartTime, end: convertedEndTime)
If you can share the exact text of the warning you're seeing, that would help narrow things down even more!
内容的提问来源于stack exchange,提问作者jeongbalmountain

