我正在制作一个掷骰子的骰子游戏,并为每个骰子分配随机数。当我按下滚动按钮时,声音效果按预期播放并且图像被替换,但我正在寻找一种方法来防止用户按下滚动直到声音效果结束(可能是2秒)。
这是我更新骰子图像的功能,我在if DispatchTime.now() + 2
之前添加arc4random_uniform
来测试此问题,但无效:
func updateDiceImages() {
randomDiceIndex1 = Int(arc4random_uniform(6))
randomDiceIndex2 = Int(arc4random_uniform(6))
randomDiceIndex3 = Int(arc4random_uniform(6))
randomDiceIndex4 = Int(arc4random_uniform(6))
randomMultiplier = Int(arc4random_uniform(4))
// determine the operator dice at random
if randomMultiplier == 0 {
addDice()
}
if randomMultiplier == 1 {
subDice()
}
if randomMultiplier == 2 {
divDice()
}
if randomMultiplier == 3 {
multDice()
}
// image changes to random dice index
diceImageView1.image = UIImage(named: diceArray[randomDiceIndex1])
diceImageView2.image = UIImage(named: diceArray[randomDiceIndex2])
diceImageView3.image = UIImage(named: diceArray[randomDiceIndex3])
diceImageView4.image = UIImage(named: diceArray[randomDiceIndex4])
multImageView1.image = UIImage(named: multArray[randomMultiplier])
}
如果有必要,这里也是我的功能,播放音效,我也试着实现DispatchTime.now() + 2
:
func rollSound() {
// Set the sound file name & extension
let alertSound = URL(fileURLWithPath: Bundle.main.path(forResource: "diceRoll", ofType: "mp3")!)
do {
// Preparation
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
} catch _ {
}
do {
try AVAudioSession.sharedInstance().setActive(true)
} catch _ {
}
// Play the sound
do {
audioPlayer = try AVAudioPlayer(contentsOf: alertSound)
} catch _{
}
audioPlayer.prepareToPlay()
audioPlayer.play()
}
这是我认为最接近的实现,但是我收到很多错误:
func rollSound() {
// Set the sound file name & extension
let when = DispatchTime.now() + 2 // change 2 to desired number of seconds
DispatchQueue.main.asyncAfter(deadline: when) {
let alertSound = URL(fileURLWithPath: Bundle.main.path(forResource: "diceRoll", ofType: "mp3")!)
do {
// Preparation
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
} catch _ {
}
do {
try AVAudioSession.sharedInstance().setActive(true)
} catch _ {
}
// Play the sound
do {
audioPlayer = try AVAudioPlayer(contentsOf: alertSound)
} catch _{
}
audioPlayer.prepareToPlay()
audioPlayer.play()
}
}
答案 0 :(得分:1)
我已为您的错误更新了代码。
func rollSound() {
// Set the sound file name & extension
let when = DispatchTime.now() + 2 // change 2 to desired number of seconds
DispatchQueue.main.asyncAfter(deadline: when) {
let alertSound = URL(fileURLWithPath: Bundle.main.path(forResource: "diceRoll", ofType: "mp3")!)
do {
// Preparation
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
} catch _ {
}
do {
try AVAudioSession.sharedInstance().setActive(true)
} catch _ {
}
// Play the sound
do {
self.audioPlayer = try AVAudioPlayer(contentsOf: alertSound)
} catch _{
}
self.audioPlayer?.prepareToPlay()
self.audioPlayer?.play()
}
}
如果要在self
附近使用类实例,则需要向属性添加DispatchQueue
。和updateDiceImages()