Plop Project Plop Project - 4 months ago 11
Swift Question

How to play a sound just one time SWIFT

I'm having a little problem with my code who consists to play a sound when I start my app. But here's the problem everytime that I go back to the first screen the sound is playing again and I want it to play just one time. When the menu screen pop ups for the fist time.

Here's my code

var bubbleSound: SystemSoundID!
bubbleSound = createBubbleSound()
AudioServicesPlaySystemSound(bubbleSound)


(...)

the function

func createBubbleSound() -> SystemSoundID {
var soundID: SystemSoundID = 0
let soundURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), "bubble", "wav", nil)
AudioServicesCreateSystemSoundID(soundURL, &soundID)
return soundID

}

Answer

You can define a struct like this (source):

struct MyViewState {
    static var hasPlayedSound = false
}

Then in your viewDidLoad:

if(!MyViewState.hasPlayedSound) {
    var bubbleSound: SystemSoundID!
    bubbleSound = createBubbleSound()
    AudioServicesPlaySystemSound(bubbleSound)
    MyViewState.hasPlayedSound = true
}

You can then modify MyViewState.hasPlayedSound and allow the UIViewController to play the sound again if desired.

Comments