1
votes

So far I found any possibility to solve this:

I'm trying to add a sound effect to a specific node. When the node is removed from parent, the sound should stop. The sound should also stop when the node is touched. I tried it with playSoundFileNamed("name", waitForCompletion: false) but you aren't able to stop this action.

In the background the AV Audio Player is playing sound.

Would be nice if someone have some new ideas to try.

2

2 Answers

1
votes

In short, you can't stop sounds played using SKAction like that. As you mentioned already, you can use AVAudioPlayer for that purpose (I am not sure about performances with this one when using for sfx). Or you can use ObjectAL library which is performant. SKAction's playSoundFileNamed method is probably meant for playing short sounds, but you don't have other control except to play a sound. You can't pause or resume it or similar. Removing the action key will also not help to stop the sound before it finishes playing (eg. you can't stop sound in the middle).

You can also check SKAudioNode which is available in iOS 9.0 and later. There is a set of SKAction methods to work with SKAudioNode. Personally I haven't tried these, but maybe it can be worth of a look.

Hope this helps.

0
votes

You can try subclassing SKSpriteNode which you can customize the spriteNode according to your taste

import SpriteKit

class SoundSourceNode: SKNode {

    let spriteNode = SKSpriteNode(color: UIColor.greenColor(), size: CGSize(width: 20, height: 20))
    let audioNode = SKAudioNode(fileNamed: "Boing-One Low.mp3")

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    init(size: CGSize)
    {
        spriteNode.position = CGPoint(x: 0, y: 0)
        audioNode.positional = true
        audioNode.position = CGPoint(x: 0, y: 0)

        super.init()

        self.addChild(spriteNode);
        self.addChild(audioNode);
    }
}

Note that the SKAudioNode is available in iOS9 and later