我正在开发视频压缩功能;我的想法如下:
我有几个问题:
我尝试了下面的代码来压缩视频,但我不知道它压缩到哪个分辨率:
- (void)convertVideoToLowQuailtyWithInputURL:(NSURL*)inputURL
outputURL:(NSURL*)outputURL
handler:(void (^)(AVAssetExportSession*))handler
{
[[NSFileManager defaultManager] removeItemAtURL:outputURL error:nil];
AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset: urlAsset presetName:AVAssetExportPresetLowQuality];
session.outputURL = outputURL;
session.outputFileType = AVFileTypeQuickTimeMovie;
[session exportAsynchronouslyWithCompletionHandler:^(void)
{
handler(session);
}];
}
请给我一些建议。预先感谢。
要获取视频的分辨率,请使用以下命令:-
AVAssetTrack *videoTrack = nil;
AVURLAsset *asset = [AVAsset assetWithURL:[NSURL fileURLWithPath:originalVideo]];
NSArray *videoTracks = [asset tracksWithMediaType:AVMediaTypeVideo];
CMFormatDescriptionRef formatDescription = NULL;
NSArray *formatDescriptions = [videoTrack formatDescriptions];
if ([formatDescriptions count] > 0)
formatDescription = (CMFormatDescriptionRef)[formatDescriptions objectAtIndex:0];
if ([videoTracks count] > 0)
videoTrack = [videoTracks objectAtIndex:0];
CGSize trackDimensions = {
.width = 0.0,
.height = 0.0,
};
trackDimensions = [videoTrack naturalSize];
int width = trackDimensions.width;
int height = trackDimensions.height;
NSLog(@"Resolution = %d X %d",width ,height);
您可以按如下方式获取帧率和比特率:-
float frameRate = [videoTrack nominalFrameRate];
float bps = [videoTrack estimatedDataRate];
NSLog(@"Frame rate == %f",frameRate);
NSLog(@"bps rate == %f",bps);
Swift 中的视频分辨率:
func resolutionForLocalVideo(url:NSURL) -> CGSize?
{
guard let track = AVAsset(URL: url).tracksWithMediaType(AVMediaTypeVideo).first else { return nil }
let size = CGSizeApplyAffineTransform(track.naturalSize, track.preferredTransform)
return CGSize(width: fabs(size.width), height: fabs(size.height))
}
没有
preferredTransform
的解决方案不会为最新设备上的某些视频返回正确的值!
这是 Avt 的答案,针对 Swift 3 进行了更新和测试:
func resolutionForLocalVideo(url:URL) -> CGSize?
{
guard let track = AVURLAsset(url: url).tracks(withMediaType: AVMediaTypeVideo).first else { return nil }
let size = track.naturalSize.applying(track.preferredTransform)
return CGSize(width: fabs(size.width), height: fabs(size.height))
}
基于 @Avt 在 swift 6 中的回答
func resolutionForLocalVideo(url: URL) async throws -> CGSize? {
guard let track = try await AVAsset(url: url).loadTracks(withMediaType: .video).first else { return nil }
let size = try await CGSizeApplyAffineTransform(try track.load(.naturalSize), track.load(.preferredTransform))
return CGSize(width: abs(size.width), height: abs(size.height))
}