0

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

}
Wyetro
  • 8,439
  • 9
  • 46
  • 64

1 Answers1

0

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.

Community
  • 1
  • 1
Caleb
  • 5,548
  • 3
  • 25
  • 32