I am developing a game where an SKAudioNode
plays the game music. When the player starts a new game, I want the music to fade in so I wrote the following code:
SKAudioNode *SFXNode = [[SKAudioNode alloc] initWithfile:@"GameMusic.mp3"];
[SFXNode runAction:[SKAction changeVolumeTo:0 duration:0]];
SFXNode.positional = NO;
[self addChild:SFXNode];
[SFXNode runAction:[SKAction changeVolumeTo:1 duration:1]];
However, when the scene initiates, the music plays at full volume for a split second, then it mutes and fades back in as it is supposed to. Does anyone have any idea why this is happening? (The music is only full volume after the user has triggered the modal segue to the scene, but before it has been displayed on the screen. As soon as the scene is displayed the music fades in normally). Also, the music does seem to be positional: as the player moves about in the scene the volume changes which I do not want happening. Solutions top either of these problems are much appreciated. Thank you!
This is because your volume change is happening after the audio is sent to the audio buffer. You need to do reset the volume before update happens. Now you can't do this as soon as you create the audio, you need to do it after it is added to the AudioEngine, so I would recommend doing this when your scene moves to the view (in the didMoveToView
function).
The code to actually change the volume should be something like
((AVAudioMixerNode *)SFXNode.avAudioNode).volume = 0
but I would recommend checking if avAudioNode
exists first and that it does conform to the AVAudioMixerNode
protocol