Как сохранить файл m4a, выбранный из MPMediaPickerController, как NSData?

Я новичок в разработке iPhone. Я разрабатываю приложение для iPhone. В этом я использовал MPMediaController для выбора песни. Затем я конвертирую этот файл как NSData и загружаю его на сервер. Мой код работает нормально, когда выбран файл «mp3», но я столкнулся с проблемой, когда выбрал файл «m4a». Файл преобразуется в данные, но после проверки данных результата при воспроизведении в AVAudioPlayer он не воспроизводится. Пожалуйста, дайте мне решение или предложите мне, где я ошибаюсь.

Мой код:

-(IBAction)selectMusicButtonPressed:(id)sender
{

     MPMediaPickerController *mediaPicker = [[MPMediaPickerController alloc] initWithMediaTypes:MPMediaTypeMusic];

        mediaPicker.delegate = self;
        mediaPicker.allowsPickingMultipleItems = NO;

    [self presentModalViewController:mediaPicker animated:YES];
}


- (void)mediaPicker: (MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection 
{


   NSURL *url;
   NSMutableData *songData;


    MPMediaItemCollection *collection=mediaItemCollection;//[allAlbumsArray objectAtIndex:0];
    item = [collection representativeItem];
    song_name=[item valueForProperty:MPMediaItemPropertyTitle];


    NSURL *assetURL = [item valueForProperty:MPMediaItemPropertyAssetURL];
    NSString *title=[item valueForProperty:MPMediaItemPropertyTitle];


    if (!assetURL) {

        NSLog(@"%@ has DRM",title);

    }

    else{



        url = [item valueForProperty: MPMediaItemPropertyAssetURL];

       NSString* AssetURL = [NSString stringWithFormat:@"%@",[item valueForProperty:MPMediaItemPropertyAssetURL]];




            url_string=[url absoluteString];

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

            NSError * error = nil;
            AVAssetReader * reader = [[AVAssetReader alloc] initWithAsset:songAsset error:&error];

            AVAssetTrack * songTrack = [songAsset.tracks objectAtIndex:0];

            AVAssetReaderTrackOutput * output = [[AVAssetReaderTrackOutput alloc] initWithTrack:songTrack outputSettings:nil];

            [reader addOutput:output];
            [output release];

            songData = [[NSMutableData alloc] init];

            [reader startReading];


            while (reader.status == AVAssetReaderStatusReading)
            {
                // AVAssetReaderTrackOutput method

                AVAssetReaderTrackOutput * trackOutput = (AVAssetReaderTrackOutput *)[reader.outputs objectAtIndex:0];
                CMSampleBufferRef sampleBufferRef = [trackOutput copyNextSampleBuffer];

                if (sampleBufferRef)
                {

                    CMBlockBufferRef blockBufferRef = CMSampleBufferGetDataBuffer(sampleBufferRef);
                    size_t length = CMBlockBufferGetDataLength(blockBufferRef);

                    NSLog(@"Size of the song----%zu",length);

                    UInt8 buffer[length];
                    CMBlockBufferCopyDataBytes(blockBufferRef, 0, length, buffer);
                    NSData *data = [[NSData alloc] initWithBytes:buffer length:length];
                    // NSLog(@"song length is %zu",length);
                    // NSLog(@"data is..........%@",data);
                    [songData appendData:data];
                    [data release];
                    CMSampleBufferInvalidate(sampleBufferRef);
                    CFRelease(sampleBufferRef);
                }
            }


            //Testing the result Data

     AVAudioPlayer * player = [[AVAudioPlayer alloc] initWithData:songData] error:NULL]; 

             [player play];

}

person KUMAR.A    schedule 05.10.2013    source источник
comment
Если вы передали объект NSError в строку, где вы тестируете свои данные результата (т.е. [[AVAudioPlayer alloc] initWithData:songData] error:&error];), вы можете получить некоторую полезную информацию.   -  person Michael Dautermann    schedule 05.10.2013
comment
Я тестировал с этим, но я не мог получить никакой ошибки и не играть тоже. Когда я играю с URL-адресом, он играет.   -  person KUMAR.A    schedule 05.10.2013
comment
пожалуйста, дайте какие-либо предложения .. мне также требуется .... или есть какие-либо ограничения для преобразования файла m4a в NSData ...   -  person Babul    schedule 09.10.2013


Ответы (1)


В моем старом проекте я преобразовывал файлы m4a в NSData следующим образом:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSURL *soundFileURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/memo.m4a", documentsDirectory]];;
NSData *myData = [NSData dataWithContentsOfURL:soundFileURL];

return myData;
person Andre Cytryn    schedule 11.12.2013