Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SKAudioNode play sound once

I can't seem to find much information about SKAudioNode. How do i play a sound only once? I do not want to repeat the sound.

What i am trying to accomplish is to play a short laser sound each time a bullet spawns, in spritekit.

like image 259
Glutch Avatar asked Dec 18 '15 14:12

Glutch


2 Answers

Unfortunately, what @KnightOfDragon says is not correct (but I do not have enough reputation to comment).

SKAudioNode has been introduced in iOS 9 and is meant as a replacement for SKAction.playSoundFileNamed(...) as it is much more powerful (You can add it as a child to a SpriteKit SKNode and if the attribute positional is set to true, 3D audio mixing is added automatically).

In order to play a sound once with SKAudioNode use the following code:

if #available(iOS 9, *) {
    let pling = SKAudioNode(fileNamed: "pling.wav")
    // this is important (or else the scene starts to play the sound in 
    // an infinite loop right after adding the node to the scene).
    pling.autoplayLooped = false
    someNode.addChild(pling)
    someNode.runAction(SKAction.sequence([
        SKAction.waitForDuration(0.5),
        SKAction.runBlock {
            // this will start playing the pling once.
            pling.runAction(SKAction.play())
        }
    ])
}
else {
    // do it the old way
}

Update

Have a look here, how to use Actions on audio nodes: SKAction->Audio-Stuff. The documentation says:

Use SKAction playSoundFileNamed:waitForCompletion: only for short incidentals. Use AVAudioPlayer for long running background music.

This does not mean, that a SKAudioNode should not be used for one-time audio. With playSoundFileNamed you cannot change the volume or pause/stop playback and so on.

like image 53
Juangamnik Avatar answered Nov 15 '22 17:11

Juangamnik


if you are trying to do sound effects, you use SKAction.playSoundFileNamed(...) on the sprite that is creating the effect. SKAudioNode is more for having music playing in your game

Example:

//we have ship as an SKSpriteNode

//lets fire laser

ship.runAction(SKAction.playSoundFileNamed("pewpewpew.caf",waitForCompletion:false));
like image 20
Knight0fDragon Avatar answered Nov 15 '22 18:11

Knight0fDragon