Загрузка аудио itunes на сервер в IOS

Можем ли мы использовать аудио из iTunes, полученное с помощью MPMediaPickerController, и загрузить его на сервер? Я успешно загрузил записанный звук на сервер без каких-либо проблем. Но, получив URL-адрес актива от MPMediaPickerController, я не смог преобразовать его для загрузки на сервер.

- (void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
{
    MPMediaItem *theChosenSong = [[mediaItemCollection items]objectAtIndex:0];
    NSString *songTitle = [theChosenSong valueForProperty:MPMediaItemPropertyTitle];
    NSLog(@"song Title: %@", songTitle);
    NSURL *assetURL = [theChosenSong valueForProperty:MPMediaItemPropertyAssetURL];
    NSLog(@"assetURL: %@", assetURL);
    AVURLAsset  *songAsset  = [AVURLAsset URLAssetWithURL:assetURL options:nil];
    NSURL *testURl = theChosenSong.assetURL;
    [self serviceUploadAudio:testURl]; 
    [self dismissViewControllerAnimated:YES completion:nil];
}

person Amal T S    schedule 28.07.2017    source источник


Ответы (1)


MPMediaItemPropertyAssetURL — это частный URL-адрес библиотеки iPod, который указывает на объект AVFoundation на основе URL-адреса, поэтому вы не можете напрямую загрузить этот объект URL-адреса на сервер. Вы должны сначала экспортировать этот MPMediaItem в каталог документов или временный каталог, а затем загрузить на сервер.

В Swift 3

// MARK:- Convert itunes song to avsset in temp location Methode.
    func exportiTunesSong(assetURL: URL, completionHandler: @escaping (_ fileURL: URL?) -> ()) {

        let songAsset = AVURLAsset(url: assetURL, options: nil)

        let exporter = AVAssetExportSession(asset: songAsset, presetName: AVAssetExportPresetAppleM4A)

        exporter?.outputFileType =   "com.apple.m4a-audio"

        exporter?.metadata = songAsset.commonMetadata

        let filename = AVMetadataItem.metadataItems(from: songAsset.commonMetadata, withKey: AVMetadataCommonKeyTitle, keySpace: AVMetadataKeySpaceCommon)


        var songName = "Unknown"

        if filename.count > 0  {
             songName = ((filename[0] as AVMetadataItem).value?.copy(with: nil) as? String)!
        }

        //Export mediaItem to temp directory
        let exportURL = URL(fileURLWithPath: NSTemporaryDirectory())
            .appendingPathComponent(songName)
            .appendingPathExtension("m4a")

        exporter?.outputURL = exportURL

        // do the export
        // (completion handler block omitted)

        exporter?.exportAsynchronously(completionHandler: {
            let exportStatus = exporter!.status

            switch (exportStatus) {
            case .failed:
                    let exportError = exporter?.error
                    print("AVAssetExportSessionStatusFailed: \(exportError)")
                    completionHandler(nil)
                    break
            case .completed:
                    print("AVAssetExportSessionStatusCompleted")
                    completionHandler(exportURL)
                    break
            case .unknown:
                    print("AVAssetExportSessionStatusUnknown")
                break
            case .exporting:
                    print("AVAssetExportSessionStatusExporting")
                break
            case .cancelled:
                    print("AVAssetExportSessionStatusCancelled")
                    completionHandler(nil)
                break
            case .waiting:
                    print("AVAssetExportSessionStatusWaiting")
                break
            }
        })
    }

Эта функция возвращает URL-адрес временного каталога экспортированного MPMediaItem, который вы можете загрузить на сервер.

self.exportiTunesSong(assetURL: index as! URL, completionHandler: { (filePath) in
        if (filePath != nil) {

           //Upload mediaItem to server by filePath
           [self serviceUploadAudio:filePath!];
       }
})

В цели — C

#pragma mark Convert itunes song to avsset in temp location Methode.
-(void)exportiTunesSong:(NSURL*)assetURL fileURL:(void(^)(id))completionHandler {

    AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:assetURL options:nil];
    AVAssetExportSession *exporter = [AVAssetExportSession exportSessionWithAsset:songAsset presetName:AVAssetExportPresetAppleM4A];

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

    exporter.metadata = songAsset.commonMetadata;

    NSArray *filename = [AVMetadataItem metadataItemsFromArray:songAsset.commonMetadata withKey:AVMetadataCommonKeyTitle keySpace:AVMetadataKeySpaceCommon];


    NSString *songName = @"Unknown";

    if (filename.count > 0) {
        AVMetadataItem *title = [filename objectAtIndex:0];
        songName = [title.value copyWithZone:nil];
    }

    NSURL *exportURL = [[[NSURL fileURLWithPath:NSTemporaryDirectory()] URLByAppendingPathComponent:songName] URLByAppendingPathExtension:@"m4a"];

    exporter.outputURL = exportURL;

    // do the export
    // (completion handler block omitted)

    [exporter exportAsynchronouslyWithCompletionHandler:^{

        switch (exporter.status) {

            case AVAssetExportSessionStatusFailed:
                NSLog(@"AVAssetExportSessionStatusFailed: %@",exporter.error);
                completionHandler(nil);
                break;

            case AVAssetExportSessionStatusCompleted:
                NSLog(@"AVAssetExportSessionStatusCompleted");
                completionHandler(exportURL);
                break;

            case AVAssetExportSessionStatusUnknown:
                NSLog(@"AVAssetExportSessionStatusUnknown");
                break;

            case AVAssetExportSessionStatusExporting:
                NSLog(@"AVAssetExportSessionStatusExporting");
                break;

            case AVAssetExportSessionStatusCancelled:
                NSLog(@"AVAssetExportSessionStatusCancelled: %@",exporter.error);
                completionHandler(nil);
                break;

            case AVAssetExportSessionStatusWaiting:
                NSLog(@"AVAssetExportSessionStatusWaiting");
                break;

        }
    }];
}

[self exportiTunesSong:assetURL fileURL:^(id filepath) {
        if (filepath != nil) {
            [self serviceUploadAudio:filepath];
        }
    }];
person Nikhlesh Bagdiya    schedule 29.07.2017