iosxcodeswiftcore-audiocaf

How do I output CAF file size in log?


I know the url of blank.caf audio file what I cam creating(recording) in my iPhone app. I am concerned about its size and would like to output its size to the log. I could not find a method to do so. I am also interesting in finding out the audio file's duration.


Solution

  • 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))
        }
    }
    

    Testing

    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
        }
    }