我知道我在iPhone应用程序中创建的blank.caf
音频文件的URL。我担心它的尺寸,并希望将其大小输出到日志。我找不到这样做的方法。找出音频文件的持续时间也很有趣。
import UIKit
import AVFoundation
extension NSURL {
var movieDuration: Double {
if checkResourceIsReachableAndReturnError(nil) {
return Double(CMTimeGetSeconds(AVURLAsset(URL: self, options: nil).duration) )
}
return 0
}
}
extension String {
var fileAttributes:NSDictionary {
if NSFileManager.defaultManager().fileExistsAtPath(self){
return NSFileManager.defaultManager().attributesOfItemAtPath(self, error: nil)! as NSDictionary
}
return[:]
}
var fileSize:Int {
if NSFileManager.defaultManager().fileExistsAtPath(self){
return Int( fileAttributes.fileSize() )
}
return 0
}
var fileSizeKB:String {
let styler = NSByteCountFormatter()
styler.allowedUnits = NSByteCountFormatterUnits.UseKB
styler.countStyle = NSByteCountFormatterCountStyle.File
return styler.stringFromByteCount(Int64(fileSize))
}
}
测试
if let audioURL = NSURL(string:"http://freetone.org/ring/stan/iPhone_5-Alarm.mp3") {
let documentsDirectoryURL = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as! NSURL
let destinationURL = documentsDirectoryURL.URLByAppendingPathComponent(audioURL.lastPathComponent!)
if let audioData = NSData(contentsOfURL: audioURL) {
audioData.writeToURL(destinationURL, atomically: true)
destinationURL.path!.fileSizeKB // 182KB
destinationURL.movieDuration // 22.704s
}
}
字节:
let attributes = NSFileManager.defaultManager()
.attributesOfItemAtPath(filePath, error: nil) as NSDictionary?
let fileSize : UInt64 = attributes!.fileSize()