Search code examples
iosswiftsprite-kitskvideonodeskaudionode

SKVideoNode stoping an SKAudioNode from playing


I'm trying to add background video and background music to a game I'm creating. To do this I'm creating a SKVideoNode and a SKAudioNode. When I run the game the video plays fine but most of the time the music doesn't play. It works just fine though if the SKVideoNode isn't created. I have tried to create an AVAudioPlayer for the music as well but that made the music play even less of the time. I also tried changing the order in which the elements render but that also didn't do anything. Does anyone know whats happening?

override func didMove(to view: SKView) {
        let bgMusic:SKAudioNode = SKAudioNode(fileNamed: "Gamemusic.m4a")
        bgMusic.autoplayLooped = true
        self.addChild(bgMusic)

        playVideo()
    }

    func playVideo() {
        let videoNode = SKVideoNode(fileNamed: "Background.mov")
        videoNode.position = CGPoint(x: self.frame.midX, y: self.frame.midY)

        videoNode.size = CGSize(width: self.frame.size.width, height: self.frame.size.height)
        self.addChild(videoNode)
        videoNode.play()
    }

Solution

  • Use

    AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
    

    to get audio playing in the background. Basically what this is doing is telling your app that the audio it plays is not the primary audio, so other audio could be played on top of it. To find out more, check out https://developer.apple.com/documentation/avfoundation/avaudiosession