1

blank.caf我知道我在 iPhone 应用程序中创建(录制)的音频文件的 url 。我担心它的大小,并想将它的大小输出到日志中。我找不到这样做的方法。我对找出音频文件的持续时间也很感兴趣。

4

2 回答 2

2
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
    }
}
于 2015-05-12T22:39:08.067 回答
0

以字节为单位:

let attributes = NSFileManager.defaultManager()
     .attributesOfItemAtPath(filePath, error: nil) as NSDictionary?
let fileSize : UInt64 = attributes!.fileSize()
于 2015-05-12T22:38:43.927 回答