I'm working on a project where when a cell in a tableview is pressed, a sound will play. I have put my sounds into an array, like so:
- (void)viewDidLoad
{
[super viewDidLoad];
//Data
soundArray = [NSArray arrayWithObjects:
[Sounds soundOfCategory:@"Sound" name:@"clipOne"],
[Sounds soundOfCategory:@"Sound" name:@"clipTwo"],
[Sounds soundOfCategory:@"Sound" name:@"clipThree"],
nil];
//Reload the table
[[self tableView] reloadData];
}
I'm using the following to play the sound:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath{
static NSString *cellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
//Create new Sound Object
Sounds *sound = nil;
sound = [soundArray objectAtIndex:indexPath.row];
//Configure the cell
[[cell textLabel]setText:[sound name]];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
return cell;
}
-(void)PlayClip:(NSString *)soundName
{
NSString *path = [[NSBundle mainBundle] pathForResource:soundName ofType:@"mp3"];
AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[theAudio play];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[self PlayClip:[soundArray objectAtIndex:indexPath.row]];
}
But with no luck. I receive the error : * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Sounds length]: unrecognized selector sent to instance 0xa35d720'
What is the issue? Is there a better way to play the sound? I'm new to working with tableviews, so please forgive my ignorance.
Thanks!
You have a problem in the last line of your code:
[self PlayClip:[soundArray objectAtIndex:indexPath.row]]; // PlayClip:(NSString *)
[soundArray objectAtIndex:indexPath.row] returns Sounds
not NSStrintg
.
I think it should be:
[self PlayClip:[[soundArray objectAtIndex:indexPath.row] name]];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.