Reputation: 61
I have an issue using Sprite Kit and when I want to play a sound after an user interaction.
User is listening music with an App (Spotify for example).
User want to play my game while he's listening his song, Currently when Use launch my app, his song is put to stop.
I would like to prevent this behavior, in fact : How can I do to either don't play sound if an other app is using the "sound" or how can I play my sound AND keep the user's music playing.
Currently this is my code :
@property (strong, nonatomic) SKAction *hitSound;
In the init Method:
_hitSound = [SKAction playSoundFileNamed:@"laugh.caf" waitForCompletion:NO];
After user press the screen:
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
SKAction *sequence = [SKAction sequence:@[_hitSound]];
[node runAction:sequence completion:^{
//Stuff
}];
}
Upvotes: 4
Views: 1206
Reputation: 5680
Your application needs to manage an AVAudioSession that allows background audio to continue to play. This will allow the background audio app to continue playing and your applications sounds will mix with it.
The AVAudioSession class is a singleton class, and is part of the AVFoundation framework. Be sure to link AVFoundation to your target. Import the framework in the classes that need it.
#import <AVFoundation/AVFoundation.h>
A good place to declare your applications audio session is in the application delegate, so the following code could be placed in application:didFinishLaunchingWithOptions: method.
// activate a mixable session
// set audio session category AVAudioSessionCategoryPlayback
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
[[AVAudioSession sharedInstance] setMode:AVAudioSessionModeDefault error:nil];
[[AVAudioSession sharedInstance] setActive:YES error: nil];
As far as your own applications sounds playing or not, one possibility would be to have a property of type BOOL named say 'mute' and check to see whether or not an SKAction is needed to play audio. You could check if background audio is playing and set the 'mute' property accordingly. You may also decide to provide an interface to the user that sets this property. The possibilities are many.
You can check if background audio is playing like this-
BOOL isPlayingAudio = [[AVAudioSession sharedInstance] otherAudioPlaying];
From here your code could decide what to set self.mute to.
AVAudioSession class reference found here - AVAudioSession Class Reference
Upvotes: 6