Frage

Is there a way to regulate the volume of sound played via SKAction playSoundFileNamed:waitForCompletion:.

I would like to implement a simple music & sound effects slider in my game. I can easily control background music since i play it via AVAudioPlayer, but all sound effects are played via SKAction.

War es hilfreich?

Lösung 2

Unfortunately you can't modify the volume using SKAction, so you have to use AVAudioPlayer for your effects too. You could implement a custom playSoundFileNamed:waitForCompletion:volume: using runBlock as you already thought, so your code won't be very different then using playSoundFileNamed:waitForCompletion:.

Andere Tipps

Here is my code for how i handled this problem

NSError *error;
NSURL *soundURL = [[NSBundle mainBundle] URLForResource:@"pew-pew-lei" withExtension:@"caf"];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];
[player setVolume:masterVolume];
[player prepareToPlay];

SKAction*   playAction = [SKAction runBlock:^{
    [player play];
}];
SKAction *waitAction = [SKAction waitForDuration:player.duration+1];
SKAction *sequence = [SKAction sequence:@[playAction, waitAction]];

[self runAction:sequence];

The masterVolume variable is just some preset variable i have that the user can change from 0.0-1.0

The waitAction ensures that the player doesn't get removed before it has played the entire sound

Hope this helps!

Swift:

Since iOS 9.0 you can change the volume to your node running another action if you have already runned your audio (remember that this one obviusly cannot work if you have something that run with repeatForever):

let changeVolumeAction = SKAction.changeVolume(to: 0.3, duration: 0.3)
node.run(changeVolume)

Or you can create a group and launching your audio with the correct volume:

let effectAudioAction = SKAction.playSoundFileNamed("electricshockLow.mp3", waitForCompletion: false)
let changeVolumeAction = SKAction.changeVolume(to: 0.3, duration: 0.3)
let effectAudioGroup = SKAction.group([effectAudioAction,changeVolumeAction])
node.run(effectAudioGroup)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top