没有使用MpMediaQuery从iphone中获取M4a文件

时间:2015-05-14 10:13:22

标签: ios xcode mp3 m4a mpmediaquery

如何从iPhone上访问m4a文件。现在我只访问mp3文件并使用MpMediaQuery,但现在我也想访问m4a文件。我正在使用此代码:

MPMediaQuery *everything = [[MPMediaQuery alloc] init];
NSArray *itemsFromGenericQuery = [everything items];
for (MPMediaItem *songMedia in itemsFromGenericQuery)
{
    NSString *songTitle = [songMedia valueForProperty: MPMediaItemPropertyTitle];
    NSString *songTitle2 = [[songMedia valueForProperty: MPMediaItemPropertyAssetURL] absoluteString];
    NSString *artistName = [songMedia valueForProperty: MPMediaItemPropertyArtist];
     //NSString *duration = [songMedia valueForProperty: MPMediaItemPropertyPlaybackDuration];
    NSNumber *seconds=[songMedia valueForProperty: MPMediaItemPropertyPlaybackDuration];
    int time=[seconds intValue]*1000;
    NSString *duration=[NSString stringWithFormat:@"%d",time];
}

您能告诉我怎么做,如何从iPhone音乐库访问我的代码中的m4a文件?

1 个答案:

答案 0 :(得分:0)

如果MPMediaItemPropertyAssetURL返回的文件只是mp3文件,则可能意味着您的ipod库中没有m4a文件。

如果您想将这些mp3文件因某种原因转换为m4a文件,可以通过以下方式使用AVAssetExportSession。

//url comes from  MPMediaItemPropertyAssetURL
   AVAsset *songAsset = [AVURLAsset URLAssetWithURL:url options:nil];
    // create the export session
    AVAssetExportSession *exportSession = [AVAssetExportSession
                                           exportSessionWithAsset: songAsset
                                           presetName:AVAssetExportPresetAppleM4A];
    if (nil == exportSession)
        NSLog(@"Error");
    //presetName:AVAssetExportPresetAppleM4A
    // configure export session  output with all our parameters
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    NSString *filePath = [NSString stringWithFormat: @"%@/convertedfile.m4a", basePath];

    exportSession.outputURL = [NSURL fileURLWithPath: filePath]; // output path
    exportSession.outputFileType = AVFileTypeAppleM4A; // output file type

    [exportSession exportAsynchronouslyWithCompletionHandler:^{
        if (AVAssetExportSessionStatusCompleted == exportSession.status)
        {
            NSLog(@"AVAssetExportSessionStatusCompleted");
        }
        else if (AVAssetExportSessionStatusFailed == exportSession.status)
        {
            // a failure may happen because of an event out of your control
            // for example, an interruption like a phone call comming in
            // make sure and handle this case appropriately
            NSLog(@"AVAssetExportSessionStatusFailed");
        }
        else
        {
            NSLog(@"Export Session Status: %d", exportSession.status);
        }
    }];