Reputation: 851
I am trying to add background music to my game. I have a switch that will mute the music and when you tap it again it will play the music. This is the code to play the music
var backgroundMusic = SKAction.playSoundFileNamed("Background.wav", waitForCompletion: true)
runAction(SKAction.repeatActionForever(backgroundMusic), withKey: "music")
I know that the waitForCompletion should be set to false to stop the music when you tap the switch. But when I have it set to false the music doesn't play it just is like the static sound.
self.removeActionForKey("music")
That is the code I used to stop the music. I was wonder if you can mute the music until the track finished or it there is another way to play music forever in SpriteKit.
Upvotes: 1
Views: 979
Reputation: 24572
waitForCompletion
: If true
, the duration of this action
is the same as the length of the audio playback. If false
, the action
is considered to have completed immediately.
Setting waitForCompletion
to false
, will create an action with a duration of 0
. Thus the repeat forever action will not function properly.
You have to wait for the duration its playing before playing again from the start, for the music to loop. So set waitForCompletion
to true
,
var backgroundMusic = SKAction.playSoundFileNamed("Background.wav", waitForCompletion: true)
You can stop the music by using removeActionForKey
.
Upvotes: 1
Reputation: 4334
I would recommend using ObjectAL instead of Spritekit for background music. Or here is a simple method I use for background music, borrowed from SKUtils:
-(AVAudioPlayer*)setupSound:(NSString*)file volume:(float)volume{
NSError *error;
NSURL *url = [[NSBundle mainBundle] URLForResource:file withExtension:nil];
AVAudioPlayer *s = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
s.numberOfLoops = -1;
s.volume = volume;
[s prepareToPlay];
return s;
}
Then you call it as follows:
...
AVAudioPlayer *bgplayer = [self setupSound:@"Background.wav" volume:1.0];
...
[bgplayer play];
...
[bgplayer pause];
Upvotes: 1