如何在swift中制作静音和取消静音按钮?

时间:2015-08-21 22:40:39

标签: xcode swift sprite-kit avaudioplayer

我正在尝试使用sprite kit swift进行静音和取消静音。我可以将背景音乐静音,但我无法取消静音。以下是一些供参考的代码:

  -R    If source_file designates a directory, cp copies the directory and the entire subtree connected
           at that point.  If the source_file ends in a /, the contents of the directory are copied rather
           than the directory itself.  This option also causes symbolic links to be copied, rather than
           indirected through, and for cp to create special files rather than copying them as normal files.
           Created directories have the same mode as the corresponding source directory, unmodified by the
           process' umask.

           In -R mode, cp will continue copying even if errors are detected.

           Note that cp copies hard-linked files as separate files.  If you need to preserve hard links, consider using tar(1), cpio(1), or pax(1) instead.

如果有人可以帮助我如何实现这一目标,那将非常感激。在某种程度上,我想触摸扬声器位置,用nospeaker节点替换扬声器节点,然后暂停AVAudioPlayer。如果我再次触摸该位置,我需要恢复到扬声器节点并播放AVAudioPlayer。

1 个答案:

答案 0 :(得分:1)

昨晚,当我添加音乐时,我就这样做了。

你要做的就是有一个标志变量,它知道音乐是否正在播放。我创建了一个名为mute的bool变量。当我的游戏开始时,静音等于真,因为没有音乐。这是用户触摸按钮时的代码。

    //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
            backgroundMusicPlayer.play()
        } else {
            //This happens when the user doesn't want music
            println("the button will now turn off music.")
            mute = true
            backgroundMusicPlayer.pause()
        }
    }

我遇到的唯一问题是,当将SKSPriteNode音量按钮更改为静音按钮时,它将无效。我不知道为什么。所以我制作了一个单独的SKSpriteNode,它是一个红色的x,以便在音乐暂停时显示。

基本上,它只是检查音乐是否已静音。如果是,那么它将取消静音并播放(这将使mute = false)。如果再次按下它,它会检查它是否取消静音,然后它将打开音乐(静音=真)。

编辑2015年9月19日xCode 7.0 Swift 2.0

对于xCode 7和Swift 2,这应该是您的代码,除非您没有收到我所做的错误或已经修复它。

var backgroundMusicPlayer: AVAudioPlayer?

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

for touch: AnyObject in touches! {
        backgroundMusicPlayer!.pause()
        backgroundMusicPlayer!.play()
}