I am very embarassed about the code below. There has to be a better way.
It would be nice if someone could point me in the right direction. Basically, I have a timer and I want to play a sound when the timer reach 15 sec, then 30 etc...
I tried for days to find a suitable way to add sounds to my SwiftUI app. To add one sound when a button is pressed is easy..
But how to do it, if when the button is pressed, I start a timer and I want to have a beep on press and every 15 seconde after that?
I have a class where I put my AV stuff as usual.. thanks for Paul to write how to play sounds in swift... thats clear!
class Player: ObservableObject {...}
So when I press the button the variable isOn below becomes true and the timer starts..
progress is for ex the offset of my animation and to show different messages on screen. When progress reaches the value of 10 then 1 sec has elapsed, therefore I divide by 10 to get the secs. I use 0.01 in the timer to get a smooth animation?
Button(action: {
isOn.toggle()
if !isOn {
progress = -5.0
timer?.invalidate()
} else {
self.timer = Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true, block: { _ in
guard progress <= 4800 else {
timer?.invalidate()
return
}
progress += 0.1
})
}
How can I play a sound every two 15 seconds? I can play the first sound but usually it ends there.
If I use a closure in Grand Dispatch it will stop my UI, and if I play sounds from a background thread then how do I get back to main?
I did some terrible code and I am ashamed. Right now it works like this.. It works when I call the function in the switch statement, but it works only when in a if condition,, otherwise it is not executed!
to give you an idea:
var text: String {
switch progress / 10 {
case -5..<0:
if player.isPlaying {
player.stopSound()
}
return "When you are ready press start"
case 0.1..<10:
if !player.isPlaying {
player.playSound()
}
return "FIRST"
case 10..<15:
if player.isPlaying {
player.stopSound()
}
return ""
case 15..<25:
if !player.isPlaying {
player.playSound()
}
return " SECOND"
// etc