1

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.

Kashif
  • 4,642
  • 7
  • 44
  • 97
  • Can you share some of the code you're using to create the file? APIs are slightly different if you're using Core Audio vs AVFoundation. – dpassage May 12 '15 at 22:26

2 Answers2

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

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
    }
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
0

In bytes:

let attributes = NSFileManager.defaultManager()
     .attributesOfItemAtPath(filePath, error: nil) as NSDictionary?
let fileSize : UInt64 = attributes!.fileSize()
Mundi
  • 79,884
  • 17
  • 117
  • 140