【问题标题】:iOS 6 issue Convert MPMediaItem to NSDataiOS 6 问题将 MPMediaItem 转换为 NSData
【发布时间】:2013-06-16 01:47:39
【问题描述】:

我试过下面的代码。

   -(void)mediaItemToData : (MPMediaItem * ) curItem
{
    NSURL *url = [curItem valueForProperty: MPMediaItemPropertyAssetURL];

    AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL: url options:nil];

    AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset: songAsset
                                                                      presetName:AVAssetExportPresetPassthrough];

    exporter.outputFileType =  @"public.mpeg-4";

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * myDocumentsDirectory = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;

    NSString *exportFile = [myDocumentsDirectory stringByAppendingPathComponent:
                            @"exported.mp4"];

    NSURL *exportURL = [NSURL fileURLWithPath:exportFile];
    exporter.outputURL = exportURL;

    // do the export
    // (completion handler block omitted)
    [exporter exportAsynchronouslyWithCompletionHandler:
     ^{
         NSData *data = [NSData dataWithContentsOfFile: [myDocumentsDirectory
                                                         stringByAppendingPathComponent: @"exported.mp4"]];

         DLog(@"Data %@",data);
     }];
}

此代码在 iOS 5 中运行良好,但现在在 iOS 6 中运行。

AVAssetExportPresetPassthrough 中针对 iOS6 的任何更改。 ???

【问题讨论】:

标签: iphone objective-c ios6 mpmediaitem avassetexportsession


【解决方案1】:

我已经找到了 iOS 6 的解决方案。请参阅下面的修改代码

-(void)mediaItemToData : (MPMediaItem * ) curItem
{
    NSURL *url = [curItem valueForProperty: MPMediaItemPropertyAssetURL];

    AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL: url options:nil];

    AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset: songAsset
                                                                      presetName:AVAssetExportPresetAppleM4A];

    exporter.outputFileType =   @"com.apple.m4a-audio";

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * myDocumentsDirectory = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;

    [[NSDate date] timeIntervalSince1970];
    NSTimeInterval seconds = [[NSDate date] timeIntervalSince1970];
    NSString *intervalSeconds = [NSString stringWithFormat:@"%0.0f",seconds];

    NSString * fileName = [NSString stringWithFormat:@"%@.m4a",intervalSeconds];

    NSString *exportFile = [myDocumentsDirectory stringByAppendingPathComponent:fileName];

    NSURL *exportURL = [NSURL fileURLWithPath:exportFile];
    exporter.outputURL = exportURL;

    // do the export
    // (completion handler block omitted)
    [exporter exportAsynchronouslyWithCompletionHandler:
     ^{
         int exportStatus = exporter.status;

         switch (exportStatus)
         {
             case AVAssetExportSessionStatusFailed:
             {
                 NSError *exportError = exporter.error;
                 NSLog (@"AVAssetExportSessionStatusFailed: %@", exportError);
                 break;
             }
             case AVAssetExportSessionStatusCompleted:
             {
                 NSLog (@"AVAssetExportSessionStatusCompleted");

                 NSData *data = [NSData dataWithContentsOfFile: [myDocumentsDirectory
                                                                 stringByAppendingPathComponent:fileName]];

                 //DLog(@"Data %@",data);
                 data = nil;

                 break;
             }
             case AVAssetExportSessionStatusUnknown:
             {
                 NSLog (@"AVAssetExportSessionStatusUnknown"); break;
             }
             case AVAssetExportSessionStatusExporting:
             {
                 NSLog (@"AVAssetExportSessionStatusExporting"); break;
             }
             case AVAssetExportSessionStatusCancelled:
             {
                 NSLog (@"AVAssetExportSessionStatusCancelled"); break;
             }
             case AVAssetExportSessionStatusWaiting:
             {
                 NSLog (@"AVAssetExportSessionStatusWaiting"); break;
             }
             default:
             {
                 NSLog (@"didn't get export status"); break;
             }
         }
     }];
}

请参阅this link 了解更多信息。

【讨论】:

  • 效果很好!非常感谢!
【解决方案2】:

SWIFT 3 版本来自@Hitarth

func save(mediaItem: MPMediaItem) -> String? {
    let url = mediaItem.assetURL!
    let hex = MD5Hex(string: url.absoluteString)
    guard didMD5HexExist(string: hex) == false else {
        return hex
    }
    let songAsset = AVURLAsset(url: url)
    guard let exporter = AVAssetExportSession(asset: songAsset, presetName: AVAssetExportPresetAppleM4A) else {
        assertionFailure()
        return nil
    }
    exporter.outputFileType = "com.apple.m4a-audio"

    let fileHexName = hex + ".m4a"
    let fileURL = latFileManager.getResourceFolderPath().appendingPathComponent(fileHexName)
    DLog("fileURL: \(fileURL)")

    exporter.outputURL = fileURL
    // do the export
    exporter.exportAsynchronously {
        let status = exporter.status
        switch status {
        case .failed:
            assertionFailure(exporter.error as! String)
        case .completed:
            DLog("AVAssetExportSessionStatusCompleted")
            self.fileHexArray.append(fileHexName)
        default:
            DLog("default")
            break
        }
    }
    return hex
}

【讨论】:

    【解决方案3】:

    试试这个用 Swift4 写的以及使用 AVAssetExportSession https://stackoverflow.com/a/36694392/5653015的原因@

    func mediaPicker(_ mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection)
    {
        //get media item first
        guard let mediaItem = mediaItemCollection.items.first else
        {
            NSLog("No item selected.")
            return
        }
    
    
        let songUrl = mediaItem.value(forProperty: MPMediaItemPropertyAssetURL) as! URL
        print(songUrl)
    
        // get file extension andmime type
        let str = songUrl.absoluteString
        let str2 = str.replacingOccurrences( of : "ipod-library://item/item", with: "")
        let arr = str2.components(separatedBy: "?")
        var mimeType = arr[0]
        mimeType = mimeType.replacingOccurrences( of : ".", with: "")
    
        let exportSession = AVAssetExportSession(asset: AVAsset(url: songUrl), presetName: AVAssetExportPresetAppleM4A)
        exportSession?.shouldOptimizeForNetworkUse = true
        exportSession?.outputFileType = AVFileType.m4a
    
        //save it into your local directory
        let documentURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let outputURL = documentURL.appendingPathComponent(mediaItem.title!)
        print(outputURL.absoluteString)
        //Delete Existing file
        do
        {
            try FileManager.default.removeItem(at: outputURL)
        }
        catch let error as NSError
        {
            print(error.debugDescription)
        }
    
        exportSession?.outputURL = outputURL
        exportSession?.exportAsynchronously(completionHandler: { () -> Void in
    
            if exportSession!.status == AVAssetExportSessionStatus.completed
            {
                print("Export Successfull")
              //  self.getAudio()
            }
            self.dismiss(animated: true, completion: nil)
        })
    }
    

    【讨论】:

      猜你喜欢
      • 2011-09-01
      • 1970-01-01
      • 2014-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      • 2015-11-07
      相关资源
      最近更新 更多