Alex Stone
Alex Stone

Reputation: 47364

iOS how to create audio fade in/out effect in a Sprite Kit game?

I'm interested in how I can manage background music in my Sprite Kit game to achieve fade in/out.

I noticed that Sprite Kit has a built-in sound player, but it seems to be more useful for very short effects, like "on hit" sounds:

[self runAction:[SKAction playSoundFileNamed:@"music.mp3" waitForCompletion:NO]];

It does not seem like there's a way to stop this sound.

I'm using Kobold Kit, and it comes with OALSimpleAudio library that can play sounds:

    [[OALSimpleAudio sharedInstance] preloadEffect:@"die.wav"];
    [[OALSimpleAudio sharedInstance] playEffect:@"die.wav"];

    [[OALSimpleAudio sharedInstance]preloadBg:@"battle.mp3"];
    [[OALSimpleAudio sharedInstance] playBg:@"battle.mp3" loop:YES];

There's a bgVolume property in OALSimpleAudio, but no real fade.

Should try to write my own fade in/out code of if there's something out there I can use to control volume over time of a generic music player, like OALSimpleAudio.

Upvotes: 3

Views: 4120

Answers (2)

palme
palme

Reputation: 2629

You can also just use the build in AVAudioPlayer or of course adapt the function to your player:

//play background sound
NSError *error;
NSURL * backgroundMusicURL = [[NSBundle mainBundle] URLForResource:@"SpaceLife" withExtension:@"mp3"];
self.backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:backgroundMusicURL error:&error];
self.backgroundMusicPlayer.numberOfLoops = -1;
[self.backgroundMusicPlayer prepareToPlay];
[self.backgroundMusicPlayer play];

And then you add the function from this post:

- (void)doVolumeFade
{  
    if (self.backgroundMusicPlayer.volume > 0.1) {
        self.backgroundMusicPlayer.volume = self.player.volume - 0.1;
        [self performSelector:@selector(doVolumeFade) withObject:nil afterDelay:0.1];       
     } else {
        // Stop and get the sound ready for playing again
        [self.backgroundMusicPlayer stop];
        self.backgroundMusicPlayer.currentTime = 0;
        [self.backgroundMusicPlayer prepareToPlay];
        self.backgroundMusicPlayer.volume = 1.0;
    }
}

Upvotes: 4

CodeSmile
CodeSmile

Reputation: 64477

ObjectAL has an AVAudioPlayer wrapper built in for music playback. It's called OALAudioTrack.

OALAudioTrack has a method fadeTo:duration:target:selector: that you can use to do fading. You already have an instance of OALAudioTrack available to you as the simple audio interface's backgroundTrack property:

[[OALSimpleAudio sharedInstance].backgroundTrack fadeTo:.. duration:.. ..];

Upvotes: 3

Related Questions