Ankit Kumar Ankit Kumar - 1 year ago 176
Swift Question

How to make a mute and unmute button in swift?

I am trying to make a mute and unmute in sprite kit swift. I'm able to mute the background music, but I can't unmute it. Here is some code for reference:

var backgroundMusicPlayer = AVAudioPlayer()
var speaker = SKSpriteNode(imageNamed: "speaker")
var nospeaker = SKSpriteNode (imageNamed: "nospeaker")

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent)

for touch in (touches as! Set<UITouch>) {
let location = touch.locationInNode(self)
if self.nodeAtPoint(location) == self.speaker{
self.nospeaker.anchorPoint = CGPointMake(0, 0.5)
self.nospeaker.position = CGPointMake(CGRectGetMinX(self.frame) + self.speaker.size.width / 3, CGRectGetMaxY(self.frame) - self.speaker.size.height * 4)
if self.nodeAtPoint(location) == self.nospeaker{

If someone can help me with how to make this happen, that would be greatly appreciated. In a way I want to touch in the speaker location to replace the speaker node with nospeaker nodeand then pause the AVAudioPlayer. If I touch in that location again, I needs to revert to the speaker node and play the AVAudioPlayer.

Answer Source

I just did that to my game last night when I added music.

All you have to do is have a flag variable that knows if music is playing or not. I made a bool variable called mute. mute is equal to true when my game starts because there is no music. This is the code I have when the user touches the button.

    //I don't want music playing when the game starts
    var mute: Bool = true

    //Mute Button (music automatically is off)
    if muteButton.containsPoint(touchLocation) {

        if mute {
            //This runs if the user wants music
            println("The button will now turn on music.")
            mute = false
        } else {
            //This happens when the user doesn't want music
            println("the button will now turn off music.")
            mute = true

The only issue I was having with this is that when changing the SKSPriteNode volume button to a mute button, it wouldn't work. I don't know why. So I made a separate SKSpriteNode that is a red x to show up when the music is paused.

Basically, all it does is check if the music is already mute. If it is, then it will unmute it and play (this will make mute = false). If the pushes it again, then it checks if it's unmute, so it will then turn on the music (mute = true).

EDIT Sep 19, 2015 for xCode 7.0 Swift 2.0

For xCode 7 and Swift 2, this should be your code, unless you're not getting the errors I did or fixed it already.

var backgroundMusicPlayer: AVAudioPlayer?

override func touchesBegan(touches: Set<UITouch>?, withEvent event: UIEvent!)

for touch: AnyObject in touches! {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download