4

I'm trying to make a button, which is when pushed - the sound is played, and when pushed again - the sound would stop. I'm using playSoundFileNamed: runAction: withKey: and removeActionForKey, but it doesn't work.

The other question I have is if there is a way not only to stop the sound, but also to pause it (so that it will start from the same part it was paused, NOT from the beginning). I've seen a similar topic at stack overflow, but yet didn't find an answer on my question yet. Thank you in advance.

import SpriteKit
import AVFoundation

var firesoundon = false

private var backgroundMusicPlayer: AVAudioPlayer!

class GameScene2: SKScene {

override func didMoveToView(view: SKView) {

    setUpScenery()    
}

private func setUpScenery() {


    //BACKGROUND
    let background = SKSpriteNode(imageNamed: backgroundImage, normalMapped: true)
    addChild(background)


    //FIRE BUTTON

    var firePath = UIBezierPath() 
    firePath.moveToPoint(CGPointMake(0, 0)) 
    firePath.addCurveToPoint(CGPointMake(115, 215), controlPoint1: CGPointMake(5, 170), controlPoint2: CGPointMake(90, 190)) ....

//^I'm just cutting down a lot of path here - the button is drawn and it's pushable/workable.

    let fireNode = SKShapeNode(path: firePath.CGPath, centered: false)
    fireNode.alpha = 0.2

    fireNode.position = CGPointMake(size.width/2, 0)
    fireNode.name = "fireNode"

        self.addChild(fireNode)
}

//So, this is a main bummer for me:

func fireturnonoff () {

    if firesoundon == false {

        var playguitar = SKAction.playSoundFileNamed("guitar.wav", waitForCompletion: true)
        runAction(playguitar, withKey: "soundsison")

        firesoundon = true
        println("firesoundon is == \(firesoundon)")

    }

    else if firesoundon == true {

        removeActionForKey("soundsison")
        println("REMOVED")

        firesoundon = false
        println("firesoundon is == \(firesoundon)")

    }

}


override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
    for touch: AnyObject in touches {
        let touch = touches.first as? UITouch

        let touchLocation = touch!.locationInNode(self)
        let node: SKNode = nodeAtPoint(touchLocation)

        if node.name == "fireNode" {

            fireturnonoff()

        }
}
}
blancos
  • 1,576
  • 2
  • 16
  • 38
Setera
  • 287
  • 2
  • 8

2 Answers2

1

Use AVAudioPlayer. It allows you to start, stop, pause, control volume, number of loops and other features.

sangony
  • 11,636
  • 4
  • 39
  • 55
1

New functionality has been added to Swift for SKActions:

class func stop() -> SKAction

It creates an action that tells an audio node to stop playback. This action may only be executed on an SKAudioNode object. The audio is stopped, and if restarted, begins at the beginning. This action is not reversible.

Unfortunately, available only in iOS 9.0 and later.

Setera
  • 287
  • 2
  • 8