Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a way to get the Samples / PowerLevels of the Recordings to be able to do animations #5

Open
NatashaTheRobot opened this issue Apr 17, 2024 · 0 comments

Comments

@NatashaTheRobot
Copy link
Collaborator

NatashaTheRobot commented Apr 17, 2024

For animation - there should be a way to get the power levels continuously. Example implementation using the framework at the moment:

import SwiftUI
import Media
import Combine

class RecordingWaveViewModel: ObservableObject {
    
    private let recorder: AudioRecorder
    
    private var cancellables = Set<AnyCancellable>()
    
    private var timer: Timer?
    @Published var samples: [Float] = []
    
    init(recorder: AudioRecorder) {
        self.recorder = recorder
        observeRecorderState()
    }
    
    private func observeRecorderState() {
        recorder.$state
            .receive(on: RunLoop.main)
            .sink { [weak self] newState in
                self?.handleStateChange(newState)
            }
            .store(in: &cancellables)
    }
    
    private func handleStateChange(_ newState: AudioRecorder.State) {
        switch newState {
        case .recording:
            startTimer()
        default:
            stopTimer()
        }
    }
    
    private func startTimer() {
        // Start or reset the timer to update the samples
        timer?.invalidate() // Invalidate any existing timer
        timer = Timer.scheduledTimer(withTimeInterval: 0.05, repeats: true) { [weak self] _ in
            guard let self = self else { return }
            let power = 1 - self.recorder.normalizedPowerLevel
            // add three times to show the wave as faster
            self.samples.append(contentsOf: [power,power,power])
        }
    }
    
    private func stopTimer() {
        timer?.invalidate()
        timer = nil
        samples = []
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant