Skip to content

Commit

Permalink
use GCD after async to schedule updating wave view for playing
Browse files Browse the repository at this point in the history
  • Loading branch information
alfianlosari committed May 31, 2024
1 parent 90b2d08 commit c3b97bf
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions Sources/ChatGPTUI/ViewModels/VoiceChatViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -158,12 +158,9 @@ open class VoiceChatViewModel<CustomContent: View>: NSObject, AVAudioRecorderDel
audioPlayer.delegate = self
audioPlayer.play()

animationTimer = Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true, block: { [unowned self]_ in
guard self.audioPlayer != nil else { return }
self.audioPlayer.updateMeters()
let power = min(1, max(0, 1 - abs(Double(self.audioPlayer.averagePower(forChannel: 0)) / 160) ))
self.audioPower = power
})
// Scheduled timer interval cause wave view to not updated when scrolling as audio plays
// Use GCD after with recursion until further cleaner solution can be found
self.scheduleAudioPlayerPowerUpdate()
}

open func cancelRecording() {
Expand Down Expand Up @@ -196,6 +193,16 @@ open class VoiceChatViewModel<CustomContent: View>: NSObject, AVAudioRecorderDel
}
}

func scheduleAudioPlayerPowerUpdate() {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
guard let audioPlayer = self.audioPlayer else { return }
audioPlayer.updateMeters()
let power = min(1, max(0, 1 - abs(Double(audioPlayer.averagePower(forChannel: 0)) / 160) ))
self.audioPower = power
self.scheduleAudioPlayerPowerUpdate()
}
}

open func resetValues() {
audioPower = 0
prevAudioPower = nil
Expand Down

0 comments on commit c3b97bf

Please sign in to comment.