简体   繁体   中英

Xcode 8 Audio Stop AVAudio

Im trying to stop an SKAction where I play a sound every time I press a button (that is randomly generated in a different location on a background), but I would like to be able do do it by calling an action. I've tried to figure this out for about 2 hours now with absolutely no success. My code where I'm trying to stop the action is below:

let clickSound = SKAction.playSoundFileNamed("Click.wav", waitForCompletion: false)
    //sound action
    let playCorrectSoundEffect0 = SKAction.playSoundFileNamed("Correct0.wav", waitForCompletion: false)
    //where im tying to create an action to stop the sound file above from playing
    let stopCorrectSoundEffect0 =
    let playCorrectSoundEffect1 = SKAction.playSoundFileNamed("Correct1.wav", waitForCompletion: false)
    let playCorrectSoundEffect2 = SKAction.playSoundFileNamed("Correct2.wav", waitForCompletion: false)
    let endSoundEffect = SKAction.playSoundFileNamed("GameOverSound", waitForCompletion: false)

Thanks and if you could explain how you did this it would be amazing!

I just solved this by making an if statement for if the score was over a certain point it would stop all actions and then play the wanted sound. It looks like this:

if scoreNumber >= 10 {
            removeAllActions()
            self.run(playCorrectSoundEffect1)
        }

For any questions just ask me!

My advice don't change for the actual Swift 3, is to choose AVAudioPlayer to make your sounds in your game:

let path = Bundle.main.path(forResource: "sound.wav", ofType:nil)!
let url = URL(fileURLWithPath: path)

do {
    let sound = try AVAudioPlayer(contentsOf: url)
    clickSound = sound
    sound.play()
} catch {
    // couldn't load file 
}

and if you want to stop the sound, you should use its stop() method. But if you try to stop a sound that doesn't exist your app will crash, so it's best to check that it exists first like this

if clickSound != nil {
    clickSound.stop()
    clickSound = nil
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM