1

very similar to this question:

Using AVAudioPlayer across multiple scenes Swift and be able to adjust volume

I want to play BGmusic across multiple scenes, but i need it to STOP when i enter certain scenes.

So for example, all my menu scenes should play the music, but when i enter the GamePlayScene the current music should stop and new music should play.

I've implemented the fix in the above post, (changed it a bit for my needs) but it isn't working... what happens now is the BGmusic continues to play and then my game music plays also

        if let vc = UIApplication.sharedApplication().keyWindow?.rootViewController as? GameViewController{
            vc.menuMusicPlayer.stop()
            println("stop the bg audio")
        }

this println isn't even being executed - suggesting the if isn't true?

my GameViewController is parent to all my scenes...

not sure where I am going wrong here. Any advice?

GameViewController code - inside

override func viewDidLoad {
    var menuMusicPlayer:AVAudioPlayer = AVAudioPlayer()

    var bgMusicURL:NSURL = NSBundle.mainBundle().URLForResource("menuSounds", withExtension: "m4a")!
    menuMusicPlayer = AVAudioPlayer(contentsOfURL: bgMusicURL, error: nil)
    menuMusicPlayer.volume = 0.25
    menuMusicPlayer.numberOfLoops = -1
    menuMusicPlayer.prepareToPlay()
    if music_on == true && menuMusicPlayer.playing == false { menuMusicPlayer.play() }

and i also have a func to stop the music in GameViewController I've tried triggering the func or just telling menuMusicPlayer to stop() directly and neither are working.

func BGMusicStop() {
    if menuMusicPlayer.playing == true {
        menuMusicPlayer.stop()
    println("bg music should stop")
    }
}

1 Answer 1

0

Your code in viewDidLoad is only assigning the audio player to a local variable. You won't ever be able to get a reference to it after viewDidLoad completes. Avoid the redeclaration of menuMusicPlayer or at least assign self.menuMusicPlayer at the end. You need to specify self here because of the ambiguity caused by using a class variable and local variable with the same name.

As for why you can't get the rootVC from wherever you want using your if let... Well I suspect your rootVC is some other class (hard to tell what you mean by "is parent to all of my scenes"), but I would recommend not using the approach you have taken for ownership of the audio player. Going through the sharedApplication->rootVC and all that seems hacky. Perhaps you should implement a singleton or a services locater to contain instances to be used across your application.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.