Mute and Unmute Swift Spritekit
I have the following code written in my file MainMenuScene.swift
to disable and enable background music music
var mute: Bool = false
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if nameOfTappedNode == "musicButton"{
if mute {
//This runs if the user wants music
print("The button will now turn on music.")
mute = false
bgMusicPlayer?.volume = 1 //this is a .mp3 file
} else {
//This happens when the user doesn't want music
print("the button will now turn off music.")
mute = true
bgMusicPlayer?.volume = 0
}
}
My question is, how can I disable all .wav and .mp3 files located in every scene in my game? What's the most efficient way? Thanks in advance!
The controls AVAudioPlayer
or players used to represent them.
I keep a global array of players and just iterate over that array whenever I want to affect all players in the game. For example:
var engineSound: AVAudioPlayer!
var shieldSound: AVAudioPlayer!
var photonSound1: AVAudioPlayer!
var photonSound2: AVAudioPlayer!
var photonSound3: AVAudioPlayer!
let arrayOfPlayers = [engineSound, shieldSound, photonSound1, photonSound2, photonSound3]
func fadeAllPlayers() {
for player in arrayOfPlayers {
player.volume = 0
}
}
One of the advantages of having an array of different players (as opposed to a single player) is that you can have multiple behaviors for different circumstances.
You can use Singleton implementation:
final class AudioManager {
static let instance = AudioManager()
//you should initialize it approp
private var player = //... initialize with whatever player you use
private init() { }
func play(){
player.play()
}
}
Then wherever you need it (from each class):
AudioManager.instance.play()
AudioManager.instance.muteAll()
AudioManager.instance.someOtherInstanceMethod()