Ios “在UITableView”时加载文档中的音频;单元格“;受压

Ios “在UITableView”时加载文档中的音频;单元格“;受压,ios,uitableview,audio,avfoundation,documents,Ios,Uitableview,Audio,Avfoundation,Documents,我有一个UITableView,在Documents目录中显示一个llist f文件。。。我想让它在按下时播放文档目录中的音频文件 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomai

我有一个UITableView,在Documents目录中显示一个llist f文件。。。我想让它在按下时播放文档目录中的音频文件

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.caf",indexPath.row+1]];
NSURL *audioURL = [NSURL URLWithString:fileName];

NSData *audioData = [NSData dataWithContentsOfURL:audioURL];

NSError *error;

_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error];

    _audioPlayer.delegate = self;
        [_audioPlayer play];
}
它运行正常,但按下时不播放音频

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.caf",indexPath.row+1]];
NSURL *audioURL = [NSURL URLWithString:fileName];

NSData *audioData = [NSData dataWithContentsOfURL:audioURL];

NSError *error;

_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error];

    _audioPlayer.delegate = self;
        [_audioPlayer play];
}

首先,声明文件路径的最佳方法是

- (NSString *)docsdir {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
}
在标题中,声明
NSString*Path

然后,在加载视图时像这样声明路径

Path = [[self docsdir]stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.caf",indexPath.row+1]];
if (![[NSFileManager defaultManager]fileExistsAtPath:Path]) {


    [[NSFileManager defaultManager]copyItemAtPath:[[NSBundle mainBundle]pathForResource:[NSString stringWithFormat:@"%d",indexPath.row+1] ofType:@"caf"] toPath:Path error:nil];


}
现在玩它,做这个

    AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:Path] error:&error];
player.delegate = self;
[player play];
更改此行:

NSURL *audioURL = [NSURL URLWithString:fileName];
为此:

NSURL *audioURL = [NSURL fileURLWithPath:fileName isDirectory:NO];
然后做:

 if(_audioPlayer == nil)
    {
        _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:nil];
    }
    else
    {
        _audioPlayer = [self.audioAlert initWithContentsOfURL:audioURL error:nil];
    }