Developer3000
Developer3000

Reputation: 247

Play sound when the app is background

The app must to play a sound when it is in background. In the capabilities background fetch and audio & airplay are checked.

The method called for play the sound is that

-(void)playSound
{
NSString* str = [[NSBundle mainBundle] pathForResource:@"alarm4" ofType:@"wav"];
NSURL* url = [NSURL fileURLWithPath:str];
NSError* erreur;

self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&erreur];

if(!erreur)
{
    [self.audioPlayer setVolume:1];
    [self.audioPlayer setNumberOfLoops:-1];
    [self.audioPlayer prepareToPlay];
    [self.audioPlayer play];
}

else
    NSLog(@"erreur de chargemnt %@", [erreur localizedDescription]);
}

Can you give me some advice, please?

Upvotes: 0

Views: 222

Answers (1)

matt
matt

Reputation: 535925

My advice is: Don't even dream of such a thing. In general, you can't do it.

You can continue playing a sound as you go into the background, but you cannot spontaneously produce a sound out of the blue in an already backgrounded app. It would be terrible if this could happen, because the user would not know where the sound is coming from, the sound could mess up the user's music listening experience, etc.

You should ask yourself why you think you need to do such a thing in the first place. You probably don't need to.

(Some Apple apps can do it. For example, the Clock app produces a repeating alarm sound out of the blue, in the background. But you, as you have probably noticed by now, are not Apple.)

Upvotes: 1

Related Questions