'Swift: Triggering sound effects during a timer

I've created a super simple count down application. You press a button, and the count down runs. The end result calculating looks like this:

  • 10.0
  • 9.999
  • 9.998
  • ...

And each whole number represents a second, so as you can imagine it runs fast.

While this loop runs, I have code in it to play a sound if it finds the current values to be 3.0 or 2.0 or 1.0 or 0.0.

Everything triggers and the sound plays, however it is glitchy as heck. About 80% of the time is triggers perfectly. The rest of the time it is either delayed by a fraction of a second or misses it completely. The sound effects are critical to the app.

I've used prepare to play properly and it did nothing to improve. My current implementation is using SKTAudio which I feel like is a bit overkill for my needs.

Any advice?



Solution 1:[1]

Please mind one moment - if you are using Double class to compare two values, you may find, that 2.0 value is not real 2.0, but 2.0000000001 for example. So, 2 and 2.0000001 are different values and your sound will no be played

Use may try smth. like

let checkValue: Double = 2 // your comparison value
let timerValue = 2.00000001 //for example
if (timerValue - Double(Int(timerValue))) == 0 && checkValue == timerValue {
    print("Cool")
} else {
    print("Not cool")
}

or almost the same

let checkValue: Double = 2 // your comparison value
let timerValue = 2.00000001 //for example

if timerValue == Double(Int(timerValue)) && timerValue == checkValue {
    print("Cool")
} else {
    print("Not cool")
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Igor Lebedev