I would like to get an AVAsset
video file size, not the video's resolution, but the file weight in KB.
A solution would be to calculate an estimated filesize from the duration and the estimatedDataRate, but this seems to be a lot just to get a filesize.
I have checked all data embedded in AVAssetTrack
it doesn't seems to be in there. Even an estimated filesize would be nice.
Here is a simple Swift 4.x / 3.x extension to get you the size of any AVURLAsset
:
import AVFoundation
extension AVURLAsset {
var fileSize: Int? {
let keys: Set<URLResourceKey> = [.totalFileSizeKey, .fileSizeKey]
let resourceValues = try? url.resourceValues(forKeys: keys)
return resourceValues?.fileSize ?? resourceValues?.totalFileSize
}
}
This returns an optional Int
, since both resourceValues.fileSize
and resouceValues.totalFileSize
return optional Ints.
While it is certainly possible to modify it to return a 0 instead of nil, I choose not to since that would not be accurate. You do not know for sure that it is size 0, you just can't get the value.
To call it:
let asset = AVURLAsset(url: urlToYourAsset)
print(asset.fileSize ?? 0)
If the size returns nil, than it will print 0, or a different value if you so choose.
Using your method I get the correct answer. I post this for anyone looking, I look forward to a simpler alternative for AVAssets in the IPOD Library
AVURLAsset* asset;
asset = [[AVURLAsset alloc]initWithURL:realAssetUrl options:nil];
NSArray *tracks = [asset tracks];
float estimatedSize = 0.0 ;
for (AVAssetTrack * track in tracks) {
float rate = ([track estimatedDataRate] / 8); // convert bits per second to bytes per second
float seconds = CMTimeGetSeconds([track timeRange].duration);
estimatedSize += seconds * rate;
}
float sizeInMB = estimatedSize / 1024 / 1024;
float sizeinGB = sizeInMB / 1024;
This gives me 2.538 GB which is what I see in ITunes.
I solved this by requesting the size from the file url. The sample below will provide the number of bytes. Just divide the number by 1024 to get the number of KB.
If you need to get the file size of a single file, you can do it by constructing a file URL to it and querying the URL's attributes directly.
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSNumber *fileSizeValue = nil;
[fileURL getResourceValue:&fileSizeValue
forKey:NSURLFileSizeKey
error:nil];
if (fileSizeValue) {
NSLog(@"value for %@ is %@", fileURL, fileSizeValue);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With