Skip to content

Commit

Permalink
🎨 improve code structure
Browse files Browse the repository at this point in the history
  • Loading branch information
leonardodino committed Apr 1, 2023
1 parent f9ba65c commit eb630a4
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 16 deletions.
33 changes: 17 additions & 16 deletions Sources/AudioInput.swift
Original file line number Diff line number Diff line change
@@ -1,39 +1,40 @@
import Foundation
import CoreAudio
import Cocoa

public extension Notification.Name {
static let deviceIsRunningSomewhereDidChange = Self("deviceIsRunningSomewhereDidChange")
}


final class AudioInput {
private var devices: Set<AudioDevice>
private var callback: (Bool) -> Void
private var devices: Set<AudioDevice> {
didSet {
let added = devices.subtracting(oldValue)
added.forEach { device in
try? device.whenSelectorChanges(.isRunningSomewhere) { _ in
NotificationCenter.default.post(name: .deviceIsRunningSomewhereDidChange, object: nil)
}
}
}
}

init(_ callback: @escaping (Bool) -> Void) {
self.devices = Set()
self.callback = callback
}

private func updateDeviceList() {
let input = try? AudioDevice.devices().filter({ try $0.supportsInput() })
guard let input else { return }
let inputs = Set(input)
if (self.devices == inputs) { return }

let added = inputs.subtracting(self.devices)
added.forEach { device in
try? device.whenSelectorChanges(.isRunningSomewhere) { _ in
NotificationCenter.default.post(name: .deviceIsRunningSomewhereDidChange, object: nil)
}
}
let devices = AudioDevice.inputDevices()
guard let devices else { return }
guard devices != self.devices else { return }

self.devices = inputs
self.devices = devices
}

private lazy var listener = Debouncer(delay: 0.5) { [weak self] in
guard let self else { return }
let isRunningSomewhere = try? self.devices.contains { try $0.isRunningSomewhere() }
self.callback(isRunningSomewhere ?? false)
self.callback(self.devices.isRunningSomewhere() ?? false)
}

func startListener() {
Expand Down
17 changes: 17 additions & 0 deletions Sources/SFBAudioEngine/AudioDevice.swift
Original file line number Diff line number Diff line change
Expand Up @@ -99,3 +99,20 @@ extension AudioObjectSelector where T == AudioDevice {
/// The property selector `kAudioDevicePropertyDeviceIsRunningSomewhere`
public static let isRunningSomewhere = AudioObjectSelector(kAudioDevicePropertyDeviceIsRunningSomewhere)
}

// MARK: - BeezyLight Extensions

extension AudioDevice {
public class func inputDevices() -> Set<AudioDevice>? {
let devices = try? AudioDevice.devices()
let inputs = try? devices?.filter { try $0.supportsInput() }
guard let inputs else { return nil }
return Set(inputs)
}
}

extension Set where Element == AudioDevice {
func isRunningSomewhere() -> Bool? {
return try? self.contains { try $0.isRunningSomewhere() }
}
}

0 comments on commit eb630a4

Please sign in to comment.