Swift:使用开关关闭按钮声音

时间:2015-07-21 14:11:33

标签: ios swift

我正在构建一个简单的计数器,每次按下按钮时都会发出声音。 但是,我用开关静音的解决方案不起作用。有没有办法让AVAudioPlayer静音?停止似乎没有帮助,我认为这是正常的,因为没有连续播放音乐。 这是我的代码:

override func viewDidLoad() {
    super.viewDidLoad()
}

var rowValue: Int = 0

let motivationalQuotes: [String] = ["xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", "xxx", ]

@IBOutlet weak var motivationLabel: UILabel!

@IBAction func subtractRowButton(sender: AnyObject) {
    if rowValue > 0 {
        rowValue = rowValue - 1
    } else {
        rowValue = 0
    }

    rowCount.text = "\(rowValue)"

    playSubtractSound()
    motivateThem()

}

@IBAction func addRowButton(sender: AnyObject) {
    rowValue = rowValue + 1
    rowCount.text = "\(rowValue)"

    playAddSound()
    motivateThem()

}

@IBOutlet weak var rowCount: UILabel!


@IBAction func resetButton(sender: AnyObject) {
    rowValue = 0
    rowCount.text = "\(rowValue)"
}


@IBOutlet weak var soundSwitch: UISwitch!

@IBAction func switchPressed(sender: UISwitch) {

    if soundSwitch.on {
        beepPlayer.volume = 0

    } else {
        beepPlayer.stop()
    }

}

func motivateThem(){
    if(rowValue > 0 && rowValue < 2)
    {
        motivationLabel.text = motivationalQuotes[0]
    }
    else if(rowValue > 19)
    {
        motivationLabel.text = motivationalQuotes[8]
    }
}

let addSoundURL =  NSBundle.mainBundle().URLForResource("add", withExtension: "aif")!
let subtractSoundURL =  NSBundle.mainBundle().URLForResource("subtract", withExtension: "aif")!
var beepPlayer = AVAudioPlayer()

func playAddSound(){
    beepPlayer = AVAudioPlayer(contentsOfURL: addSoundURL, error: nil)
    beepPlayer.prepareToPlay()
    beepPlayer.play()
}

func playSubtractSound(){
    beepPlayer = AVAudioPlayer(contentsOfURL: subtractSoundURL, error: nil)
    beepPlayer.prepareToPlay()
    beepPlayer.play()
}

1 个答案:

答案 0 :(得分:1)

如果没有必要,请不要播放声音。

if soundSwitch.on { playAddSound() }