I'm trying to play a sound method within the object didSelectedIndex
UITableViewController
The audio files are files with extension m4a
, but I also tried with mp3 files and the result does not change.
Below I post the code that I have implemented in the method of TableViewController:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *soundFilePath = [NSString stringWithFormat:@"%@/testaudio.m4a", [[NSBundle mainBundle] resourcePath]];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSLog(@"soundFileURL %@",soundFileURL);
NSError *error;
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:&error];
if(!player){
NSLog(@"ERRORE: %@",error);
}
[player setDelegate:self];
[player prepareToPlay];
[player play];
}
I also tried directly on the device and it still does not play any sound.
I also added a class AVSession as follows:
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:YES error:nil];
The result did not change, does anyone know what the problem is?
Try this (tested):
Set a property for your AVAudioPlayer
object in your .m
:
@property(strong, nonatomic) AVAudioPlayer *player;
Then add this in your:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *soundFilePath;
if ((soundFilePath = [[NSBundle mainBundle] pathForResource:@"testaudio" ofType:@"m4a"]))
{
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSError *error;
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:&error];
if(self.player)
{
[self.player setDelegate:self];
[self.player prepareToPlay];
[self.player play];
}
else
{
NSLog(@"ERRORE: %@", error);
}
}
}
You don't need AVAudioSession
in your case.