gpt4 book ai didi

ios - 如何在 Swift 中使用按钮和 if/else 停止背景音乐?

转载 作者:搜寻专家 更新时间:2023-11-01 06:44:38 25 4
gpt4 key购买 nike

在我的游戏中,我向 GameScene 添加了一个按钮并播放了音乐:

let url = NSBundle.mainBundle().URLForResource("Happy Background Music", withExtension: "mp3")
let bgMusic = AVAudioPlayer(contentsOfURL: url, error: nil)

@IBAction func SoundOnOff(sender: UIButton) {
bgMusic.numberOfLoops = -1
bgMusic.play()
}

并且播放了音乐,但我想添加一个如果按下按钮时音乐将停止。如果我应该写呢?

最佳答案

用这个改变你的代码,

 let url = NSBundle.mainBundle().URLForResource("Happy Background Music", withExtension: "mp3")

do{
let bgMusic = try AVAudioPlayer(contentsOfURL: url!)
}catch{
print(error)
}


@IBAction func SoundOnOff(sender: UIButton) {

if bgMusic.playing {
bgMusic.stop()
} else {
self.bgMusic.play()
}
}

编辑:描述

playing- Property
-A Boolean value that indicates whether the audio player is playing (true) or not (false). (read-only)

关于ios - 如何在 Swift 中使用按钮和 if/else 停止背景音乐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31742740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com