我正在开发一个项目,使您能够在选择了tableview中的单元格时播放声音。为了让事情变得简单,我实现了一个搜索功能。问题是,它不能正常工作。当您单击结果时,播放的声音来自原始数组,而不是新过滤的声音。我知道我的错误就在这里的某个地方,我想找一点帮助。
//Create new Sound Object
Sounds *sound = nil;
//check to see whether the normal table or search results table is being displayed and set the Sound object from the appropriate array
if (tableView == self.searchDisplayController.searchResultsTableView) {
sound = [filteredSoundArray objectAtIndex:indexPath.row];
}else{
sound = [soundArray objectAtIndex:indexPath.row];
}
//Configure the cell
[[cell textLabel]setText:[sound name]];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSString *selectedSoundFile = [[soundArray objectAtIndex:indexPath.row]name];
NSString *path = [[NSBundle mainBundle]pathForResource:selectedSoundFile ofType:@"mp3"];
if(path){
theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[self.theAudio play];
}
if (tableView == self.searchDisplayController.searchResultsTableView) {
theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[self.theAudio play];
}
}
谢谢!
答案 0 :(得分:1)
更改didSelectRowAtIndexPath
NSString *selectedSoundFile = [[soundArray objectAtIndex:indexPath.row]name];
如果您要从搜索结果中进行处理,请使用filteredSoundArray
代替soundArray
..
您正在播放的条件应该从您用于在表格视图中显示的阵列中播放。但是你正在使用具有所有声音的阵列。
在didSelectRowIndexPath
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSString *selectedSoundFile;
if (tableView == self.searchDisplayController.searchResultsTableView) {
selectedSoundFile = [[filteredSoundArray objectAtIndex:indexPath.row]name];
}else{
selectedSoundFile = [[soundArray objectAtIndex:indexPath.row]name];
}
NSString *path = [[NSBundle mainBundle]pathForResource:selectedSoundFile ofType:@"mp3"];
if(path){
theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[self.theAudio play];
}
}