问题
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