Phoenix
Phoenix

Reputation: 1931

Swift / Spritekit: Play music through specific scenes

I have a game in which I have several tutorial scenes.

I am able to add music to each scene using AVFoundation, and an AVAudioPlayer().

What I need to do is be able to start music in a specific scene, and have it continue playing in the background for only related scenes.

For example:

  1. Start tutorialMusic in Tutorial Menu
  2. Continue tutorialMusic in Tutorial A
  3. Continue tutorialMusic in Tutorial B
  4. Continue tutorialMusic in Tutorial Menu
  5. Stop tutorialMusic and Play mainMenuMusic in the Main Menu

What I've Tried

I have tried placing the AVAudioPlayer() in the view controller, however I found that propagates to every scene, regardless of what it is. I am also unable to find the view controller's instance of AVAudioPlayer to stop it.

I have tried adding the tutorialMusic to each Tutorial scene, however that restarts the music every time a user opens a different Tutorial scene, which is sloppy, and if the user is moving quickly, it degrades performance and is really annoying.

My Question

Is there a way to extend the Main Tutorial Scene throughout each sub tutorial scene, such that the main instance of AVAudioPlayer is accessible and propagates through each tutorial?

Ultimately I want to ensure that in each section (Tutorial Menu Scene, Tutorial A Scene, Tutorial B Scene, etc.) the tutorialMusic starts only once and continuously plays until the user exits back to the Main Menu.

Thanks!

Upvotes: 2

Views: 1009

Answers (1)

lchamp
lchamp

Reputation: 6612

What you might want to do is use a Singleton. Doing so, you'll be able to have a sound player available from anywhere within your app.

Here is one that might fit your needs : https://github.com/raywenderlich/SKTUtils/blob/master/SKTUtils/SKTAudio.swift (Ray Wenderlich).

Used like so : SKTAudio.sharedInstance().playBackgroundMusic(filename: yourTutorialMusicName). Then in your menu you call it again with your other music.

Let me know if it helped.

Upvotes: 2

Related Questions