In my application I start an AVAudioPlayer as soon as the app starts to play a background sound that is looped indefinitely. This background sound should play the whole time the app is open.
When I open the app, the background sound starts correctly, but when I create another player and start another sound (for example when I touch the display) the second sounds starts playing and the background sound stops for some reason.
// This should start the background sound. _audioPlayer is declared in the header file.
_audioPlayer = [[AudioPlayer alloc] init];
[_audioPlayer soundPlay:@"/rainforestambience.wav" withLoops:-1];
// Starts another sound later.
AudioPlayer *monkeyPlayer = [[AudioPlayer alloc] init];
[monkeyPlayer soundPlay:@"/jungle1.wav" withLoops:1];
// Play function in my AudioPlayer class.
AVAudioPlayer *player;
- (void) soundPlay:(NSString *)filePath withLoops: (int)loops
{
NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
resourcePath = [resourcePath stringByAppendingString:filePath];
NSLog(@"Path to play: %@", resourcePath);
NSError* err;
player = [[AVAudioPlayer alloc] initWithContentsOfURL:
[NSURL fileURLWithPath:resourcePath] error:&err];
player.numberOfLoops = loops;
[player prepareToPlay];
if(err) {
NSLog(@"Failed with reason: %@", [err localizedDescription]);
} else {
[player play];
}
}
Edit: fixed it by changing one line in my AudioPlayer class.
Instead of having
AVAudioPlayer *player;
in the AudioPlayer.m File, I moved the Variable into the header file in the declaration space. Now it works perfectly and as intended. :)