0
votes

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. :)

2
your code looks OK, but check your variables again. common mistake is that one uses same player instance to play the other file, which makes the first one stop.krafter
But isn't my first player the global _audioPlayer variable and the second the monkeyPlayer? Aren't those two separate players, or can they link to the same instance of AudioPlayer?Mauin
Yes, you have two different players. I'm just saying people often make that mistake with these players.krafter
Thanks for your help. I found a way to fix it now :)Mauin
Could you please tell me where the problem was?krafter

2 Answers

0
votes

I guess you should invoke another player in a different thread by doing performSelectorOnMainThread.

Two instances of AVAudioPlayer may pose such issues to you.

0
votes

Well, You said, have 2 AVAudioPlayers.

I think 1st player is _audioPlayer ad second player is monkeyPlayer

The _audioPlayer is playing background. When you call the second sound (monkeyPlayer) just stop the _audioPlaer

ie,

[_audioPlayer stopPlay];
 [monkeyPlayer Play];

It will stop background Music.