Reducing iTunes music size in Swift

时间:2016-12-09 12:53:54

标签: ios swift xcode itunes mpmediapickercontroller

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)

}

1 个答案:

答案 0 :(得分:0)

Change AVAssetExportPresetAppleM4A to AVAssetExportPresetLowQuality. You may also chose AVAssetExportPresetMediumQuality

相关问题