Reputation: 115
I am using this function to play sound on my iPhone app. the problem is that the sound isn't playing. the function works correct and read the file path correctly and I don't get any error but the sound does not play
-(void) playSound : (NSString *) fName; {
if ([audioPlayer isPlaying]) {
[audioPlayer stop];
}
audioPlayer.volume = 1.0;
soundpath = [NSString stringWithFormat:@"sounds/%@", fName];
soundFilePath = [[NSBundle mainBundle] pathForResource:soundpath ofType: @"mp3"];
soundURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];
audioPlayer.numberOfLoops = -1;
if (audioPlayer == nil){
}
else {
[audioPlayer play];
if ([audioPlayer isPlaying]) {
NSLog(@"%@", @"run");
}
}
}
Upvotes: 4
Views: 1167
Reputation: 2822
Try adding this:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive:YES error: nil];
UInt32 route = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof(route), &route);
I had as similar problem and adding this before calling the play it solved the problem for me.
Upvotes: 5