如何在swift中减少itunes音乐大小?

时间:2016-12-09 07:03:57

标签: ios swift itunes mpmediapickercontroller

我正在访问Itunes Library音乐。我将选定的歌曲存储在我的文档目录中。歌曲的大小是13MB,我需要减小歌曲大小,以便我可以轻松地将其发送到服务器。我该怎么做?这是我的整体代码:

@IBAction func AddSongs(sender: UIButton)
{
    displayMediaPickerAndPlayItem()
       }func displayMediaPickerAndPlayItem()
{mediaPicker = MPMediaPickerController(mediaTypes: .AnyAudio)

    if let picker = mediaPicker{

        print("Successfully instantiated a media picker")
        picker.delegate = self
        view.addSubview(picker.view)
        presentViewController(picker, animated: true, completion: nil)

    } else {
        print("Could not instantiate a media picker")
    }

}

MPMediaPickerController,                      didPickMediaItems mediaItemCollection函数

    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

   // let songAsset = AVURLAsset.init(URL: url, options: nil)
   // print("songAsset  = \(songAsset)")
    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
}

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

exporter.outputURL = fileURL
exporter.outputFileType = "com.apple.m4a-audio"

exporter.exportAsynchronouslyWithCompletionHandler {
    if exporter.status == .Completed {
        completionHandler(fileURL, nil)
    } else {
        completionHandler(nil, exporter.error)
    }
}}

1 个答案:

答案 0 :(得分:0)

如果您希望压缩视频以进行共享,则应查看AVAssetExportSession。将AVAssetExportPresetAppleM4A更改为AVAssetExportPresetLowQuality。你可以这样做:

- (void)convertVideoToLowQuailtyWithInputURL:(NSURL*)inputURL 
                                   outputURL:(NSURL*)outputURL 
                                     handler:(void (^)(AVAssetExportSession*))handler
{
    [[NSFileManager defaultManager] removeItemAtURL:outputURL error:nil];
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetLowQuality];
    exportSession.outputURL = outputURL;
    exportSession.outputFileType = AVFileTypeQuickTimeMovie;
    [exportSession exportAsynchronouslyWithCompletionHandler:^(void) 
    {
        handler(exportSession);
        [exportSession release];
    }];
}

您还可以将AVFormatIDKey设置为kAudioFormatMPEG4AAC以进行记录设置