2

我有一个 UITableView 在 Documents Directory 中显示一个 llist f 文件......我希望它在按下时播放 Documents 目录中的音频文件......

它运行没有错误,但按下时不播放音频...

    - (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];
}
4

2 回答 2

3

更改此行:

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];
    }
于 2013-01-28T03:39:17.753 回答
0

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

- (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];
于 2013-01-28T03:15:20.467 回答