Search code examples
iphonensdocument

How to read data from NSDocumentDirectory


Hi everyone I am working on an application which records the user sound and save that to NSDocumentDirectory.The data files are saving well.But the problem is that i want to play those files.I am using the table view for this to populate it with the number of files in the NSDocumentDirectory.But the table shows only one cell the current sound file.I am doing mistake somewhere please help me out. I am using this code to play.

-(void)PlayAudio
{


    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSLog(@"strffdsa %@",documentsDirectory);
    NSURL *fileURL = [NSURL fileURLWithPath:recorderFilePath];

    player =    [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: nil];
    player.numberOfLoops = 0;
    //[fileURL release];

    [player play];
    [player setDelegate: self];

}

Where recorderFilePath is the path of file.The path is new everytime with the help of NSDate frmattor.But not getting how to populate the table view with all the files residing in the DocumentDirectory.

Please-2 help me...I am new to this technology.

Thanks in advance to all ........


Solution

  • Use an enumerator to simplify iterating through the Documents directory to search for music files.

            //Use an enumerator to store all the valid music file paths at the top level of your App's Documents directory
            NSDirectoryEnumerator *directoryEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:documentsDirectory];
    
            for (NSString *path in directoryEnumerator) 
            {
                //check for all music file formats you need to play
                if ([[path pathExtension] isEqualToString:@"mp3"] || [[path pathExtension] isEqualToString:@"aiff"] ) 
                { 
                    [myMusicFiles addObject:path];         
                }
            }
    
            //the NSArray 'myMusicFiles' will be the datasource for your tableview