Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 512
Alex Stone Avatar asked Dec 03 '25 22:12

Alex Stone


2 Answers

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;
    }
}
like image 85
palme Avatar answered Dec 06 '25 16:12

palme


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:.. ..];
like image 24
LearnCocos2D Avatar answered Dec 06 '25 14:12

LearnCocos2D



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!