Load audio in DOCUMENTS when UITableView “cell” is

2019-07-14 07:02发布

I have a UITableView displaying a llist f files in the Documents Directory... and I want it to play the audio file in the Documents directory when pressed...

It runs with no errores but doesn't play the audio when pressed...

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

2条回答
看我几分像从前
2楼-- · 2019-07-14 07:17

To start out, the best way to declare a files path is this

- (NSString *)docsdir {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
}

in your header, declareNSString *Path;

then, declare the path like this when the view loads

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];


}

now to play it, do this

    AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:Path] error:&error];
player.delegate = self;
[player play];
查看更多
ら.Afraid
3楼-- · 2019-07-14 07:36

Change this line:

NSURL *audioURL = [NSURL URLWithString:fileName];

to this:

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

And then just do:

 if(_audioPlayer == nil)
    {
        _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:nil];
    }
    else
    {
        _audioPlayer = [self.audioAlert initWithContentsOfURL:audioURL error:nil];
    }
查看更多
登录 后发表回答