0

I am working with accessing iTunes Library music. I stored a selected song in my Documents directory. The song's size is 13MB, and I need to reduce the song size so that I can easily send it to the server. How do I to it? Here is my overall code:

 func mediaPicker(mediaPicker: MPMediaPickerController,
                 didPickMediaItems mediaItemCollection: MPMediaItemCollection){

    let item: MPMediaItem = mediaItemCollection.items[0]

    print(mediaItemCollection)
              print("mediaItemCollection  = \(mediaItemCollection)")

    let url = item.valueForProperty(MPMediaItemPropertyAssetURL) as! NSURL
    FinalAudioName = item.valueForProperty(MPMediaItemPropertyTitle) as! NSString as String
    export(url, completionHandler: {  _, _ in })

}

func export(assetURL: NSURL, completionHandler: (NSURL?, ErrorType?) -> ())
{
    let asset = AVURLAsset(URL: assetURL)
    guard let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A) else {
        completionHandler(nil, ExportError.unableToCreateExporter)
        return
    }

    fileURL = NSURL(fileURLWithPath: NSTemporaryDirectory())
        .URLByAppendingPathComponent(NSUUID().UUIDString)!
        .URLByAppendingPathExtension("m4a")!
    print(fileURL)

    let recordSettings:[String : AnyObject] = [
        AVFormatIDKey:             NSNumber(unsignedInt: kAudioFormatMPEG4AAC),
        AVEncoderBitRateKey :      16000,

        AVNumberOfChannelsKey:     2,
        AVSampleRateKey :          44100,
        AVEncoderAudioQualityKey: AVAudioQuality.Medium.rawValue

    ]
    do
    {
        audioRecorder = try AVAudioRecorder(URL: fileURL, settings: recordSettings)
        audioRecorder!.delegate = self
        audioRecorder!.meteringEnabled = true
        audioRecorder!.prepareToRecord()
    }

    catch let error as NSError
    {
        audioRecorder = nil
        print(error.localizedDescription)
    }

    do {

        try NSFileManager.defaultManager().removeItemAtURL(fileURL)
    }
    catch _
    {

    }



    exporter.outputURL = fileURL
    exporter.outputFileType = AVFileTypeAppleM4A
    exporter.exportAsynchronouslyWithCompletionHandler {
        if exporter.status == .Completed {
            completionHandler(self.fileURL, nil)
         self.optData = NSData(contentsOfURL: self.fileURL)!
            print(self.optData)

        } else
        {
            completionHandler(nil, exporter.error)
        }
    }
    mediaPicker!.dismissViewControllerAnimated(true, completion: nil)

}
Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
HariKarthick
  • 1,369
  • 1
  • 19
  • 47
  • You need to a be a bit more helpful here in order for us to help you. does the code you have work, if not.. what is wrong with it, does it throw any errors, is the output file size the same? – Scriptable Dec 09 '16 at 12:59
  • code work fine..self.optData = NSData(contentsOfURL: self.fileURL)! print(self.optData)..The data is very large i want to reduce – HariKarthick Dec 09 '16 at 13:05
  • The bitRate is usually the property that makes the bigger difference in file size for a audio file (i'm no expert though). I quote something I found on wikipedia "the music you buy on iTunes is 256 kilobits per second, meaning there are 256 kilobits of data stored in every second of a song". Reducing the bitrate to 16 kilobits should make a significant difference. What is the new file size. Could you provide a sample I could play with? – Scriptable Dec 09 '16 at 13:20
  • Actually i don't want to store all song in my directory.The main thing is i have to upload selected itunes song to php server.We can't directly upload raw mp3 right?That's why i stored the selected song locally and uploaded it.Once if i add another song i will clear the song once if it's uploaded successfully. ok..I will try and let u know – HariKarthick Dec 09 '16 at 13:23

1 Answers1

0

Change AVAssetExportPresetAppleM4A to AVAssetExportPresetLowQuality. You may also chose AVAssetExportPresetMediumQuality

Munahil
  • 2,381
  • 1
  • 14
  • 24
  • If i changed the AVAssetExportPresetAppleM4A to AVAssetExportPresetLowQuality.It throws error in this line exporter.outputFileType = AVFileTypeAppleM4A – HariKarthick Dec 09 '16 at 13:02
  • What error? Change it at both places in your "export" func. "AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetLowQuality)" and "exporter.outputFileType = AVAssetExportPresetLowQuality" – Munahil Dec 09 '16 at 13:04
  • If i changed the AVAssetExportPresetAppleM4A to AVAssetExportPresetLowQuality this is the error :libc++abi.dylib: terminating with uncaught exception of type NSException in this line:exporter.outputFileType = AVAssetExportPresetLowQuality – HariKarthick Dec 09 '16 at 13:40
  • outputFileType needs to be of AVFileType, there are alot of presets such as mp4, quicktime etc. this is not for quality presets – Scriptable Dec 09 '16 at 14:18