iphoneiostableviewavaudioplayercaf

Loading local audio .caf files, which object to use? iOS


The aim of this particular feature is to be able to display and play local voice recordings from a table view. The code for loading local caf files is as follows:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self loadFileInformation];
}

- (void)loadFileInformation
{
    items = [[NSMutableArray alloc] init];
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
    for (int i = 0; i < [directoryContent count]; i++) [items addObject:[directoryContent objectAtIndex:i]];
    [self.tableView reloadData];
}

With delegate method for playing a particular file as follows:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    avAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[[items objectAtIndex:indexPath.row] filePathURL] error:nil];
    avAudioPlayer.delegate = (id)self;
    [avAudioPlayer prepareToPlay];
    [avAudioPlayer play];
}

However when this method is called I get an error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString filePathURL]: unrecognized selector sent to instance 0x239420'

I'm just wondering if someone could point me in the correct direction! When the contents of the local directory are stored in the array directoryContent, what object is each element of? NSData?

Many thanks in advance


Solution

  • In your loadFileInformation method

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

    will be a proper way.

    Also have a look What is NSSearchPathForDirectoriesInDomains?

    EDIT:

    The contents are NSString by the way. Why don't you try allocating the AVudioPlayer object with the data available at that path.

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString * path = [documentsDirectory stringByAppendingPathComponent:[items objectAtIndex:indexPath.row]];
    
    NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
    AVAudioPlayer * player = [[AVAudioPlayer alloc] initWithData:data error:nil];
    

    You are having the file name in the items array but not complete path. So we will try to append it to the path and fetch the data available at that path and load ur audio player with it.