Load audio in DOCUMENTS when UITableView “cell” is pressed

时光怂恿深爱的人放手 提交于 2019-12-11 04:04:09

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/14554462/load-audio-in-documents-when-uitableview-cell-is-pressed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!