Cannot stop background music from within Game Scenes, Swift 3/Spritekit
Why not create a music helper class that you can access from anywhere. Either the singleton way or a class with static methods. This should also make your code cleaner and easier to manage.
I would also split the setup method and the play method so that you do not set up the player each time you play the file.
e.g Singleton
class MusicManager {
static let shared = MusicManager()
var audioPlayer = AVAudioPlayer()
private init() { } // private singleton init
func setup() {
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "music", ofType: "mp3")!))
audioPlayer.prepareToPlay()
} catch {
print (error)
}
}
func play() {
audioPlayer.play()
}
func stop() {
audioPlayer.stop()
audioPlayer.currentTime = 0 // I usually reset the song when I stop it. To pause it create another method and call the pause() method on the audioPlayer.
audioPlayer.prepareToPlay()
}
}
When your project launches just call the setup method
MusicManager.shared.setup()
Than from any where in your project you can say
MusicManager.shared.play()
to play the music.
To than stop it just call the stop method
MusicManager.shared.stop()
For a more feature rich example with multiple tracks check out my helper on GitHub
https://github.com/crashoverride777/SwiftyMusic
Hope this helps
Stopping Music in SpriteKit when leaving a GameScene
Stop the AVAudioPlayer before segueing to the next Scene
Insert this before your segue code
audioPlayer.pause()
Swift 2 Spritekit: Issue with background music not resuming when the game is unpaused
You'll want to look into using AVAudioPlayer and NSNotificationCenter to pass data around the game.
Start the background audio player in your actual GameViewController class.
It's better to do it this way then use SKAudioNode... That's more for sounds that are like sound effects relating to something that happened in gameplay.
By using AVAudioPlayer, the advantage is when the music is paused it's still cued up to play in it's previous spot.
This is one of the few things that will be running regardless of what's going on. So we put it in the GameViewController.
So here's an example of GameViewController code we'd need to start
import AVFoundation
var bgMusicPlayer:AVAudioPlayer?
Then in the GameViewController we make these functions as such
override func viewDidLoad() {
super.viewDidLoad()
// PlayBackgroundSound , PauseBackgroundSound will be your code to send from other "scenes" to use the audio player //
// NSNotificationCenter to pass data throughout the game //
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(GameViewController.playBackgroundSound(_:)), name: "PlayBackgroundSound", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(GameViewController.pauseBackgroundSound), name: "PauseBackgroundSound", object: nil)
}
func playBackgroundSound(notification: NSNotification) {
let name = notification.userInfo!["fileToPlay"] as! String
if (bgSoundPlayer != nil){
bgSoundPlayer!.stop()
bgSoundPlayer = nil
}
if (name != ""){
let fileURL:NSURL = NSBundle.mainBundle().URLForResource(name, withExtension: "mp3")!
do {
bgSoundPlayer = try AVAudioPlayer(contentsOfURL: fileURL)
} catch _{
bgSoundPlayer = nil
}
bgSoundPlayer!.volume = 1
bgSoundPlayer!.numberOfLoops = -1
// -1 will loop it forever //
bgSoundPlayer!.prepareToPlay()
bgSoundPlayer!.play()
}
}
func pauseBackgroundSound() {
if (bgSoundPlayer != nil){
bgSoundPlayer!.pause()
}
}
Then when you want to use the audio player in your pause or resume button functions.
Remember you need to have the player used in each scene.
import AVFoundation.AVAudioSession
override func didMoveToView(view: SKView) {
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
}
Then if you want to pause or play something just use NSNotificationCenter.
// To Pause in a scene use this line of code in the function you need to pause the music
NSNotificationCenter.defaultCenter().postNotificationName("PauseBackgroundSound", object: self)
/// To Play initially or a new song .. use this line of code in the function you need to play the music
NSNotificationCenter.defaultCenter().postNotificationName("PlayBackgroundSound", object: self, userInfo: "FILE NAME OF BACKGROUND MUSIC")
Swift / Spritekit: Play music through specific scenes
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.
Swift 3 Game Music Play
You can play the music form your AppDelegate
. Put this code in your applicationDidFinishLaunching()
let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3")!
var player: AVAudioPlayer!
do {
player = try AVAudioPlayer(contentsOf: url)
guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error {
print(error.localizedDescription)
}
This will play the music as soon as your app is launched and continue until told to stop or the app closes.
Stop playing music on third ViewController - Swift 4
Option 1
class Service {
static let shared = Service()
var gmusic :AVAudioPlayer?
}
try Service.shared.gmusic = AVAudioPlayer (contentsOf: URL(fileURLWithPath: soundFile!))
then use
Service.shared.gmusic?.stop()
Option 2
in CurrentVC
let settingsVc = //
settingsVc.delegate = self
present(settingsVc
//
calss SettingsVC:UIViewController {
var delegate:CurrentVC?
func stop () {
delegate?.gmusic.stop()
}
Related Topics
Requestaccessformediatype Doesn't Ask for Permission
Swift: How to Invalidate a Timer If the Timer Starts from a Function
Disable Email Detection in Swiftui's Text
Post Requests in Alamofire Parameter Encoding Returning Get Responses
How Is a Global Variable Set to Private Understood in Swift
Node.Physicsbody.Joints Downcasting Error
@Published Property Not Triggering Anything
What Does the Snapshot/Observer Code Do in Firebase
Uicollectionviewcell Calling Functions Over and Over
How to Disambiguate a Foreach Loop in Xcode with Swiftui
Empty Class in Swift Playground Gives _Lldb_Expr_ Error
Why Does Function Has Multiple Return Types in Swift
Cannot Stop Background Music from Within Game Scenes, Swift 3/Spritekit
Code Only Retrieving One Value from Data in Firebase
Swift Format Text Field When User Is Typing
How to Pass Arguments into a Function with Completion Swift