I'm trying to make metronome app that plays sound on repeat (BPM) and with/without each tack volume. I tried to achieve that with Timer
and GCD Timer
like that:
let interval = TimeInterval(Double(60) / Double(bpm))
timer = Timer.scheduledTimer(timeInterval: interval,
target: self,
selector: #selector(playTackt),
userInfo: nil,
repeats: true
@objc func playTackt(){
if shouldPlaySoundTackts{
audioPlayer.volume = 1
playedSoundTackts += 1
if playedSoundTackts == soundTackts{
shouldPlaySoundTackts = false
playedSoundTackts = 0
}
}else{
audioPlayer.volume = 0
playedMuteTackts += 1
if playedMuteTackts == muteTackts{
shouldPlaySoundTackts = true
playedMuteTackts = 0
}
}
audioPlayer.play()
}
But the problem is that Timer has some lags in miliseconds. Then i tried to replay sound with audioPlayerDidFinishPlaying
method but it call's after ~0.5 seconds after sound finish's playing. So is there another way to generate or repeat sound with bpm and with/without each tack volume ?
You could try using either the Sequencer or AppleSequencer and assigning the notes as Midi. One known drawback with AppleSampler is a delay in the first note playing. You can see an example of AppleSequencer in MusicToy and Sequencer in the Shaker example of AudioKit/Cookbook on Github.