Add macOS Audio VU Meter app with system monitoring
Features: - Real-time audio level monitoring via BlackHole virtual audio device - Classic VU meter display with dB scale (-60 to 0 dB) - Peak hold indicators with configurable hold time - System resource monitors: CPU, RAM, Disk, Network - SwiftUI interface with dark theme - Multi-device audio input selection - Settings window for configuration Built with AVAudioEngine for audio capture and Mach kernel APIs for system statistics.
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"colors" : [
|
||||
{
|
||||
"color" : {
|
||||
"color-space" : "srgb",
|
||||
"components" : {
|
||||
"alpha" : "1.000",
|
||||
"blue" : "0.459",
|
||||
"green" : "0.831",
|
||||
"red" : "0.216"
|
||||
}
|
||||
},
|
||||
"idiom" : "universal"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"scale" : "1x",
|
||||
"size" : "16x16"
|
||||
},
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"scale" : "2x",
|
||||
"size" : "16x16"
|
||||
},
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"scale" : "1x",
|
||||
"size" : "32x32"
|
||||
},
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"scale" : "2x",
|
||||
"size" : "32x32"
|
||||
},
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"scale" : "1x",
|
||||
"size" : "128x128"
|
||||
},
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"scale" : "2x",
|
||||
"size" : "128x128"
|
||||
},
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"scale" : "1x",
|
||||
"size" : "256x256"
|
||||
},
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"scale" : "2x",
|
||||
"size" : "256x256"
|
||||
},
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"scale" : "1x",
|
||||
"size" : "512x512"
|
||||
},
|
||||
{
|
||||
"idiom" : "mac",
|
||||
"scale" : "2x",
|
||||
"size" : "512x512"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,431 @@
|
||||
//
|
||||
// AudioEngine.swift
|
||||
// AudioVUMeter
|
||||
//
|
||||
// Core Audio engine for capturing audio from BlackHole or any input device
|
||||
// Calculates RMS levels and converts to dB for VU meter display
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import AVFoundation
|
||||
import CoreAudio
|
||||
import Combine
|
||||
|
||||
/// Represents an available audio input device
|
||||
struct AudioDevice: Identifiable, Hashable {
|
||||
let id: AudioDeviceID
|
||||
let name: String
|
||||
let uid: String
|
||||
let inputChannels: Int
|
||||
}
|
||||
|
||||
/// Main audio engine class for capturing and analyzing audio levels
|
||||
class AudioEngine: ObservableObject {
|
||||
// MARK: - Published Properties
|
||||
|
||||
/// Current audio levels (0.0 to 1.0)
|
||||
@Published var leftLevel: Double = 0
|
||||
@Published var rightLevel: Double = 0
|
||||
|
||||
/// Peak levels with hold
|
||||
@Published var leftPeak: Double = 0
|
||||
@Published var rightPeak: Double = 0
|
||||
|
||||
/// Levels in dB (-inf to 0)
|
||||
@Published var leftLevelDB: Double = -60
|
||||
@Published var rightLevelDB: Double = -60
|
||||
|
||||
/// Engine state
|
||||
@Published var isRunning = false
|
||||
@Published var selectedDeviceID: AudioDeviceID = 0
|
||||
@Published var selectedDeviceName: String = "No Device"
|
||||
@Published var availableDevices: [AudioDevice] = []
|
||||
|
||||
/// Settings
|
||||
@Published var referenceLevel: Double = -18 // Reference level in dB
|
||||
@Published var peakHoldTime: Double = 2.0 // Peak hold time in seconds
|
||||
|
||||
// MARK: - Private Properties
|
||||
|
||||
private var audioEngine: AVAudioEngine?
|
||||
private var inputNode: AVAudioInputNode?
|
||||
private var peakResetTimers: [Timer] = []
|
||||
|
||||
private let levelSmoothingFactor: Double = 0.3
|
||||
private var previousLeftLevel: Double = 0
|
||||
private var previousRightLevel: Double = 0
|
||||
|
||||
// MARK: - Initialization
|
||||
|
||||
init() {
|
||||
refreshDeviceList()
|
||||
selectBlackHoleDevice()
|
||||
}
|
||||
|
||||
// MARK: - Device Management
|
||||
|
||||
/// Refresh the list of available audio input devices
|
||||
func refreshDeviceList() {
|
||||
availableDevices = getInputDevices()
|
||||
|
||||
if availableDevices.isEmpty {
|
||||
selectedDeviceName = "No Input Devices"
|
||||
}
|
||||
}
|
||||
|
||||
/// Get all available audio input devices
|
||||
private func getInputDevices() -> [AudioDevice] {
|
||||
var devices: [AudioDevice] = []
|
||||
|
||||
var propertyAddress = AudioObjectPropertyAddress(
|
||||
mSelector: kAudioHardwarePropertyDevices,
|
||||
mScope: kAudioObjectPropertyScopeGlobal,
|
||||
mElement: kAudioObjectPropertyElementMain
|
||||
)
|
||||
|
||||
var propertySize: UInt32 = 0
|
||||
var status = AudioObjectGetPropertyDataSize(
|
||||
AudioObjectID(kAudioObjectSystemObject),
|
||||
&propertyAddress,
|
||||
0,
|
||||
nil,
|
||||
&propertySize
|
||||
)
|
||||
|
||||
guard status == noErr else { return devices }
|
||||
|
||||
let deviceCount = Int(propertySize) / MemoryLayout<AudioDeviceID>.size
|
||||
var deviceIDs = [AudioDeviceID](repeating: 0, count: deviceCount)
|
||||
|
||||
status = AudioObjectGetPropertyData(
|
||||
AudioObjectID(kAudioObjectSystemObject),
|
||||
&propertyAddress,
|
||||
0,
|
||||
nil,
|
||||
&propertySize,
|
||||
&deviceIDs
|
||||
)
|
||||
|
||||
guard status == noErr else { return devices }
|
||||
|
||||
for deviceID in deviceIDs {
|
||||
// Check if device has input channels
|
||||
let inputChannels = getDeviceInputChannels(deviceID: deviceID)
|
||||
guard inputChannels > 0 else { continue }
|
||||
|
||||
// Get device name
|
||||
let name = getDeviceName(deviceID: deviceID)
|
||||
let uid = getDeviceUID(deviceID: deviceID)
|
||||
|
||||
devices.append(AudioDevice(
|
||||
id: deviceID,
|
||||
name: name,
|
||||
uid: uid,
|
||||
inputChannels: inputChannels
|
||||
))
|
||||
}
|
||||
|
||||
return devices
|
||||
}
|
||||
|
||||
/// Get device name
|
||||
private func getDeviceName(deviceID: AudioDeviceID) -> String {
|
||||
var propertyAddress = AudioObjectPropertyAddress(
|
||||
mSelector: kAudioDevicePropertyDeviceNameCFString,
|
||||
mScope: kAudioObjectPropertyScopeGlobal,
|
||||
mElement: kAudioObjectPropertyElementMain
|
||||
)
|
||||
|
||||
var name: CFString = "" as CFString
|
||||
var propertySize = UInt32(MemoryLayout<CFString>.size)
|
||||
|
||||
let status = AudioObjectGetPropertyData(
|
||||
deviceID,
|
||||
&propertyAddress,
|
||||
0,
|
||||
nil,
|
||||
&propertySize,
|
||||
&name
|
||||
)
|
||||
|
||||
return status == noErr ? name as String : "Unknown Device"
|
||||
}
|
||||
|
||||
/// Get device UID
|
||||
private func getDeviceUID(deviceID: AudioDeviceID) -> String {
|
||||
var propertyAddress = AudioObjectPropertyAddress(
|
||||
mSelector: kAudioDevicePropertyDeviceUID,
|
||||
mScope: kAudioObjectPropertyScopeGlobal,
|
||||
mElement: kAudioObjectPropertyElementMain
|
||||
)
|
||||
|
||||
var uid: CFString = "" as CFString
|
||||
var propertySize = UInt32(MemoryLayout<CFString>.size)
|
||||
|
||||
let status = AudioObjectGetPropertyData(
|
||||
deviceID,
|
||||
&propertyAddress,
|
||||
0,
|
||||
nil,
|
||||
&propertySize,
|
||||
&uid
|
||||
)
|
||||
|
||||
return status == noErr ? uid as String : ""
|
||||
}
|
||||
|
||||
/// Get number of input channels for a device
|
||||
private func getDeviceInputChannels(deviceID: AudioDeviceID) -> Int {
|
||||
var propertyAddress = AudioObjectPropertyAddress(
|
||||
mSelector: kAudioDevicePropertyStreamConfiguration,
|
||||
mScope: kAudioDevicePropertyScopeInput,
|
||||
mElement: kAudioObjectPropertyElementMain
|
||||
)
|
||||
|
||||
var propertySize: UInt32 = 0
|
||||
var status = AudioObjectGetPropertyDataSize(
|
||||
deviceID,
|
||||
&propertyAddress,
|
||||
0,
|
||||
nil,
|
||||
&propertySize
|
||||
)
|
||||
|
||||
guard status == noErr, propertySize > 0 else { return 0 }
|
||||
|
||||
let bufferListPointer = UnsafeMutablePointer<AudioBufferList>.allocate(capacity: Int(propertySize))
|
||||
defer { bufferListPointer.deallocate() }
|
||||
|
||||
status = AudioObjectGetPropertyData(
|
||||
deviceID,
|
||||
&propertyAddress,
|
||||
0,
|
||||
nil,
|
||||
&propertySize,
|
||||
bufferListPointer
|
||||
)
|
||||
|
||||
guard status == noErr else { return 0 }
|
||||
|
||||
let bufferList = bufferListPointer.pointee
|
||||
var channelCount = 0
|
||||
|
||||
let buffers = UnsafeMutableAudioBufferListPointer(UnsafeMutablePointer(mutating: bufferListPointer))
|
||||
for buffer in buffers {
|
||||
channelCount += Int(buffer.mNumberChannels)
|
||||
}
|
||||
|
||||
return channelCount
|
||||
}
|
||||
|
||||
/// Select BlackHole device if available
|
||||
private func selectBlackHoleDevice() {
|
||||
// Try to find BlackHole device
|
||||
if let blackholeDevice = availableDevices.first(where: {
|
||||
$0.name.lowercased().contains("blackhole")
|
||||
}) {
|
||||
selectedDeviceID = blackholeDevice.id
|
||||
selectedDeviceName = blackholeDevice.name
|
||||
return
|
||||
}
|
||||
|
||||
// Fall back to first available device
|
||||
if let firstDevice = availableDevices.first {
|
||||
selectedDeviceID = firstDevice.id
|
||||
selectedDeviceName = firstDevice.name
|
||||
}
|
||||
}
|
||||
|
||||
/// Switch to selected audio device
|
||||
func switchDevice() {
|
||||
let wasRunning = isRunning
|
||||
|
||||
if wasRunning {
|
||||
stop()
|
||||
}
|
||||
|
||||
if let device = availableDevices.first(where: { $0.id == selectedDeviceID }) {
|
||||
selectedDeviceName = device.name
|
||||
setSystemInputDevice(deviceID: selectedDeviceID)
|
||||
}
|
||||
|
||||
if wasRunning {
|
||||
start()
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the system default input device
|
||||
private func setSystemInputDevice(deviceID: AudioDeviceID) {
|
||||
var deviceID = deviceID
|
||||
var propertyAddress = AudioObjectPropertyAddress(
|
||||
mSelector: kAudioHardwarePropertyDefaultInputDevice,
|
||||
mScope: kAudioObjectPropertyScopeGlobal,
|
||||
mElement: kAudioObjectPropertyElementMain
|
||||
)
|
||||
|
||||
AudioObjectSetPropertyData(
|
||||
AudioObjectID(kAudioObjectSystemObject),
|
||||
&propertyAddress,
|
||||
0,
|
||||
nil,
|
||||
UInt32(MemoryLayout<AudioDeviceID>.size),
|
||||
&deviceID
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Audio Engine Control
|
||||
|
||||
/// Start audio capture
|
||||
func start() {
|
||||
guard !isRunning else { return }
|
||||
|
||||
do {
|
||||
audioEngine = AVAudioEngine()
|
||||
guard let engine = audioEngine else { return }
|
||||
|
||||
inputNode = engine.inputNode
|
||||
guard let input = inputNode else { return }
|
||||
|
||||
let format = input.outputFormat(forBus: 0)
|
||||
|
||||
// Install tap on input node to capture audio
|
||||
input.installTap(onBus: 0, bufferSize: 1024, format: format) { [weak self] buffer, _ in
|
||||
self?.processAudioBuffer(buffer)
|
||||
}
|
||||
|
||||
try engine.start()
|
||||
isRunning = true
|
||||
|
||||
print("Audio engine started - capturing from: \(selectedDeviceName)")
|
||||
print("Format: \(format)")
|
||||
|
||||
} catch {
|
||||
print("Failed to start audio engine: \(error)")
|
||||
isRunning = false
|
||||
}
|
||||
}
|
||||
|
||||
/// Stop audio capture
|
||||
func stop() {
|
||||
guard isRunning else { return }
|
||||
|
||||
inputNode?.removeTap(onBus: 0)
|
||||
audioEngine?.stop()
|
||||
audioEngine = nil
|
||||
inputNode = nil
|
||||
isRunning = false
|
||||
|
||||
// Reset levels
|
||||
DispatchQueue.main.async {
|
||||
self.leftLevel = 0
|
||||
self.rightLevel = 0
|
||||
self.leftLevelDB = -60
|
||||
self.rightLevelDB = -60
|
||||
}
|
||||
|
||||
print("Audio engine stopped")
|
||||
}
|
||||
|
||||
/// Reset peak indicators
|
||||
func resetPeaks() {
|
||||
DispatchQueue.main.async {
|
||||
self.leftPeak = 0
|
||||
self.rightPeak = 0
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Audio Processing
|
||||
|
||||
/// Process incoming audio buffer
|
||||
private func processAudioBuffer(_ buffer: AVAudioPCMBuffer) {
|
||||
guard let floatData = buffer.floatChannelData else { return }
|
||||
|
||||
let frameCount = Int(buffer.frameLength)
|
||||
let channelCount = Int(buffer.format.channelCount)
|
||||
|
||||
var leftRMS: Float = 0
|
||||
var rightRMS: Float = 0
|
||||
|
||||
// Calculate RMS for left channel
|
||||
let leftChannel = floatData[0]
|
||||
var leftSum: Float = 0
|
||||
for i in 0..<frameCount {
|
||||
let sample = leftChannel[i]
|
||||
leftSum += sample * sample
|
||||
}
|
||||
leftRMS = sqrt(leftSum / Float(frameCount))
|
||||
|
||||
// Calculate RMS for right channel (or use left if mono)
|
||||
if channelCount > 1 {
|
||||
let rightChannel = floatData[1]
|
||||
var rightSum: Float = 0
|
||||
for i in 0..<frameCount {
|
||||
let sample = rightChannel[i]
|
||||
rightSum += sample * sample
|
||||
}
|
||||
rightRMS = sqrt(rightSum / Float(frameCount))
|
||||
} else {
|
||||
rightRMS = leftRMS
|
||||
}
|
||||
|
||||
// Convert to dB
|
||||
let leftDB = 20 * log10(max(leftRMS, 1e-10))
|
||||
let rightDB = 20 * log10(max(rightRMS, 1e-10))
|
||||
|
||||
// Normalize to 0-1 range (assuming -60dB is silence)
|
||||
let minDB: Float = -60
|
||||
let maxDB: Float = 0
|
||||
|
||||
let normalizedLeft = Double(max(0, min(1, (leftDB - minDB) / (maxDB - minDB))))
|
||||
let normalizedRight = Double(max(0, min(1, (rightDB - minDB) / (maxDB - minDB))))
|
||||
|
||||
// Apply smoothing
|
||||
let smoothedLeft = previousLeftLevel * (1 - levelSmoothingFactor) + normalizedLeft * levelSmoothingFactor
|
||||
let smoothedRight = previousRightLevel * (1 - levelSmoothingFactor) + normalizedRight * levelSmoothingFactor
|
||||
|
||||
previousLeftLevel = smoothedLeft
|
||||
previousRightLevel = smoothedRight
|
||||
|
||||
// Update UI on main thread
|
||||
DispatchQueue.main.async {
|
||||
self.leftLevel = smoothedLeft
|
||||
self.rightLevel = smoothedRight
|
||||
self.leftLevelDB = Double(leftDB)
|
||||
self.rightLevelDB = Double(rightDB)
|
||||
|
||||
// Update peaks
|
||||
if smoothedLeft > self.leftPeak {
|
||||
self.leftPeak = smoothedLeft
|
||||
self.schedulePeakReset(channel: 0)
|
||||
}
|
||||
if smoothedRight > self.rightPeak {
|
||||
self.rightPeak = smoothedRight
|
||||
self.schedulePeakReset(channel: 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Schedule peak reset after hold time
|
||||
private func schedulePeakReset(channel: Int) {
|
||||
// Cancel existing timer for this channel
|
||||
if channel < peakResetTimers.count {
|
||||
peakResetTimers[channel].invalidate()
|
||||
}
|
||||
|
||||
let timer = Timer.scheduledTimer(withTimeInterval: peakHoldTime, repeats: false) { [weak self] _ in
|
||||
DispatchQueue.main.async {
|
||||
if channel == 0 {
|
||||
self?.leftPeak = self?.leftLevel ?? 0
|
||||
} else {
|
||||
self?.rightPeak = self?.rightLevel ?? 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if peakResetTimers.count > channel {
|
||||
peakResetTimers[channel] = timer
|
||||
} else {
|
||||
peakResetTimers.append(timer)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.app-sandbox</key>
|
||||
<true/>
|
||||
<key>com.apple.security.device.audio-input</key>
|
||||
<true/>
|
||||
<key>com.apple.security.files.user-selected.read-only</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,30 @@
|
||||
//
|
||||
// AudioVUMeterApp.swift
|
||||
// AudioVUMeter
|
||||
//
|
||||
// macOS Audio VU Meter with System Monitoring
|
||||
// Captures audio from BlackHole virtual audio device
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
|
||||
@main
|
||||
struct AudioVUMeterApp: App {
|
||||
@StateObject private var audioEngine = AudioEngine()
|
||||
@StateObject private var systemMonitor = SystemMonitor()
|
||||
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
ContentView()
|
||||
.environmentObject(audioEngine)
|
||||
.environmentObject(systemMonitor)
|
||||
}
|
||||
.windowStyle(.hiddenTitleBar)
|
||||
.windowResizability(.contentSize)
|
||||
|
||||
Settings {
|
||||
SettingsView()
|
||||
.environmentObject(audioEngine)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
//
|
||||
// ContentView.swift
|
||||
// AudioVUMeter
|
||||
//
|
||||
// Main view containing all VU meters
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
|
||||
struct ContentView: View {
|
||||
@EnvironmentObject var audioEngine: AudioEngine
|
||||
@EnvironmentObject var systemMonitor: SystemMonitor
|
||||
|
||||
@State private var showSettings = false
|
||||
|
||||
var body: some View {
|
||||
ZStack {
|
||||
// Background gradient
|
||||
LinearGradient(
|
||||
gradient: Gradient(colors: [
|
||||
Color(red: 0.1, green: 0.1, blue: 0.15),
|
||||
Color(red: 0.05, green: 0.05, blue: 0.1)
|
||||
]),
|
||||
startPoint: .top,
|
||||
endPoint: .bottom
|
||||
)
|
||||
.ignoresSafeArea()
|
||||
|
||||
VStack(spacing: 20) {
|
||||
// Header
|
||||
HStack {
|
||||
Text("Audio VU Meter")
|
||||
.font(.system(size: 24, weight: .bold, design: .rounded))
|
||||
.foregroundColor(.white)
|
||||
|
||||
Spacer()
|
||||
|
||||
// Settings button
|
||||
Button(action: { showSettings.toggle() }) {
|
||||
Image(systemName: "gear")
|
||||
.font(.system(size: 18))
|
||||
.foregroundColor(.gray)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.popover(isPresented: $showSettings) {
|
||||
QuickSettingsView()
|
||||
.environmentObject(audioEngine)
|
||||
}
|
||||
}
|
||||
.padding(.horizontal)
|
||||
.padding(.top, 10)
|
||||
|
||||
// Audio device info
|
||||
HStack {
|
||||
Circle()
|
||||
.fill(audioEngine.isRunning ? Color.green : Color.red)
|
||||
.frame(width: 8, height: 8)
|
||||
|
||||
Text(audioEngine.selectedDeviceName)
|
||||
.font(.system(size: 12, design: .monospaced))
|
||||
.foregroundColor(.gray)
|
||||
|
||||
Spacer()
|
||||
|
||||
Text(audioEngine.isRunning ? "ACTIVE" : "STOPPED")
|
||||
.font(.system(size: 10, weight: .semibold, design: .monospaced))
|
||||
.foregroundColor(audioEngine.isRunning ? .green : .red)
|
||||
}
|
||||
.padding(.horizontal)
|
||||
|
||||
Divider()
|
||||
.background(Color.gray.opacity(0.3))
|
||||
|
||||
// Audio VU Meters
|
||||
VStack(spacing: 15) {
|
||||
Text("AUDIO LEVELS")
|
||||
.font(.system(size: 11, weight: .semibold, design: .monospaced))
|
||||
.foregroundColor(.gray)
|
||||
|
||||
HStack(spacing: 30) {
|
||||
// Left Channel
|
||||
VUMeterView(
|
||||
level: audioEngine.leftLevel,
|
||||
peakLevel: audioEngine.leftPeak,
|
||||
label: "L",
|
||||
colorScheme: .audio
|
||||
)
|
||||
|
||||
// Right Channel
|
||||
VUMeterView(
|
||||
level: audioEngine.rightLevel,
|
||||
peakLevel: audioEngine.rightPeak,
|
||||
label: "R",
|
||||
colorScheme: .audio
|
||||
)
|
||||
}
|
||||
|
||||
// dB Display
|
||||
HStack(spacing: 40) {
|
||||
VStack {
|
||||
Text(String(format: "%.1f dB", audioEngine.leftLevelDB))
|
||||
.font(.system(size: 14, weight: .bold, design: .monospaced))
|
||||
.foregroundColor(dbColor(for: audioEngine.leftLevelDB))
|
||||
Text("LEFT")
|
||||
.font(.system(size: 9, design: .monospaced))
|
||||
.foregroundColor(.gray)
|
||||
}
|
||||
|
||||
VStack {
|
||||
Text(String(format: "%.1f dB", audioEngine.rightLevelDB))
|
||||
.font(.system(size: 14, weight: .bold, design: .monospaced))
|
||||
.foregroundColor(dbColor(for: audioEngine.rightLevelDB))
|
||||
Text("RIGHT")
|
||||
.font(.system(size: 9, design: .monospaced))
|
||||
.foregroundColor(.gray)
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding()
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: 12)
|
||||
.fill(Color.black.opacity(0.3))
|
||||
)
|
||||
.padding(.horizontal)
|
||||
|
||||
Divider()
|
||||
.background(Color.gray.opacity(0.3))
|
||||
|
||||
// System Monitors
|
||||
VStack(spacing: 15) {
|
||||
Text("SYSTEM MONITOR")
|
||||
.font(.system(size: 11, weight: .semibold, design: .monospaced))
|
||||
.foregroundColor(.gray)
|
||||
|
||||
HStack(spacing: 25) {
|
||||
// CPU Meter
|
||||
SystemMeterView(
|
||||
value: systemMonitor.cpuUsage,
|
||||
label: "CPU",
|
||||
unit: "%",
|
||||
colorScheme: .cpu
|
||||
)
|
||||
|
||||
// RAM Meter
|
||||
SystemMeterView(
|
||||
value: systemMonitor.memoryUsage,
|
||||
label: "RAM",
|
||||
unit: "%",
|
||||
colorScheme: .ram
|
||||
)
|
||||
|
||||
// Disk I/O Meter
|
||||
SystemMeterView(
|
||||
value: systemMonitor.diskActivity,
|
||||
label: "DISK",
|
||||
unit: "%",
|
||||
colorScheme: .disk
|
||||
)
|
||||
|
||||
// Network Meter
|
||||
SystemMeterView(
|
||||
value: systemMonitor.networkActivity,
|
||||
label: "NET",
|
||||
unit: "%",
|
||||
colorScheme: .network
|
||||
)
|
||||
}
|
||||
}
|
||||
.padding()
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: 12)
|
||||
.fill(Color.black.opacity(0.3))
|
||||
)
|
||||
.padding(.horizontal)
|
||||
|
||||
// Control buttons
|
||||
HStack(spacing: 15) {
|
||||
Button(action: {
|
||||
if audioEngine.isRunning {
|
||||
audioEngine.stop()
|
||||
} else {
|
||||
audioEngine.start()
|
||||
}
|
||||
}) {
|
||||
HStack {
|
||||
Image(systemName: audioEngine.isRunning ? "stop.fill" : "play.fill")
|
||||
Text(audioEngine.isRunning ? "Stop" : "Start")
|
||||
}
|
||||
.frame(width: 80)
|
||||
}
|
||||
.buttonStyle(ControlButtonStyle(color: audioEngine.isRunning ? .red : .green))
|
||||
|
||||
Button(action: {
|
||||
audioEngine.resetPeaks()
|
||||
}) {
|
||||
HStack {
|
||||
Image(systemName: "arrow.counterclockwise")
|
||||
Text("Reset")
|
||||
}
|
||||
.frame(width: 80)
|
||||
}
|
||||
.buttonStyle(ControlButtonStyle(color: .orange))
|
||||
}
|
||||
.padding(.bottom, 15)
|
||||
}
|
||||
}
|
||||
.frame(width: 400, height: 580)
|
||||
.onAppear {
|
||||
audioEngine.start()
|
||||
systemMonitor.startMonitoring()
|
||||
}
|
||||
.onDisappear {
|
||||
audioEngine.stop()
|
||||
systemMonitor.stopMonitoring()
|
||||
}
|
||||
}
|
||||
|
||||
private func dbColor(for db: Double) -> Color {
|
||||
if db > -3 { return .red }
|
||||
if db > -10 { return .orange }
|
||||
if db > -20 { return .yellow }
|
||||
return .green
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Quick Settings Popover
|
||||
struct QuickSettingsView: View {
|
||||
@EnvironmentObject var audioEngine: AudioEngine
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 15) {
|
||||
Text("Audio Device")
|
||||
.font(.headline)
|
||||
|
||||
Picker("Device", selection: $audioEngine.selectedDeviceID) {
|
||||
ForEach(audioEngine.availableDevices, id: \.id) { device in
|
||||
Text(device.name).tag(device.id)
|
||||
}
|
||||
}
|
||||
.labelsHidden()
|
||||
.frame(width: 250)
|
||||
.onChange(of: audioEngine.selectedDeviceID) { _ in
|
||||
audioEngine.switchDevice()
|
||||
}
|
||||
|
||||
Divider()
|
||||
|
||||
Text("Reference Level")
|
||||
.font(.headline)
|
||||
|
||||
HStack {
|
||||
Text("-60 dB")
|
||||
.font(.caption)
|
||||
Slider(value: $audioEngine.referenceLevel, in: -60...0)
|
||||
Text("0 dB")
|
||||
.font(.caption)
|
||||
}
|
||||
|
||||
Text("Peak Hold Time: \(Int(audioEngine.peakHoldTime))s")
|
||||
.font(.caption)
|
||||
|
||||
Slider(value: $audioEngine.peakHoldTime, in: 0.5...5.0)
|
||||
}
|
||||
.padding()
|
||||
.frame(width: 300)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Control Button Style
|
||||
struct ControlButtonStyle: ButtonStyle {
|
||||
let color: Color
|
||||
|
||||
func makeBody(configuration: Configuration) -> some View {
|
||||
configuration.label
|
||||
.font(.system(size: 12, weight: .semibold))
|
||||
.foregroundColor(.white)
|
||||
.padding(.horizontal, 15)
|
||||
.padding(.vertical, 8)
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: 8)
|
||||
.fill(color.opacity(configuration.isPressed ? 0.6 : 0.8))
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#Preview {
|
||||
ContentView()
|
||||
.environmentObject(AudioEngine())
|
||||
.environmentObject(SystemMonitor())
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIconFile</key>
|
||||
<string></string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>LSMinimumSystemVersion</key>
|
||||
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string>Copyright © 2024. All rights reserved.</string>
|
||||
<key>NSMicrophoneUsageDescription</key>
|
||||
<string>Audio VU Meter needs access to audio input to display audio levels from BlackHole or other audio devices.</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string>NSApplication</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,130 @@
|
||||
//
|
||||
// SettingsView.swift
|
||||
// AudioVUMeter
|
||||
//
|
||||
// Settings window for configuring audio device and preferences
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
|
||||
struct SettingsView: View {
|
||||
@EnvironmentObject var audioEngine: AudioEngine
|
||||
|
||||
@AppStorage("showPeakIndicator") private var showPeakIndicator = true
|
||||
@AppStorage("meterStyle") private var meterStyle = "classic"
|
||||
@AppStorage("updateRate") private var updateRate = 30.0
|
||||
|
||||
var body: some View {
|
||||
TabView {
|
||||
// Audio Settings
|
||||
Form {
|
||||
Section("Audio Device") {
|
||||
Picker("Input Device", selection: $audioEngine.selectedDeviceID) {
|
||||
ForEach(audioEngine.availableDevices, id: \.id) { device in
|
||||
HStack {
|
||||
Text(device.name)
|
||||
Spacer()
|
||||
Text("\(device.inputChannels) ch")
|
||||
.foregroundColor(.secondary)
|
||||
.font(.caption)
|
||||
}
|
||||
.tag(device.id)
|
||||
}
|
||||
}
|
||||
.onChange(of: audioEngine.selectedDeviceID) { _ in
|
||||
audioEngine.switchDevice()
|
||||
}
|
||||
|
||||
Button("Refresh Devices") {
|
||||
audioEngine.refreshDeviceList()
|
||||
}
|
||||
}
|
||||
|
||||
Section("Levels") {
|
||||
HStack {
|
||||
Text("Reference Level")
|
||||
Spacer()
|
||||
Text("\(Int(audioEngine.referenceLevel)) dB")
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
Slider(value: $audioEngine.referenceLevel, in: -60...0, step: 1)
|
||||
|
||||
HStack {
|
||||
Text("Peak Hold Time")
|
||||
Spacer()
|
||||
Text("\(String(format: "%.1f", audioEngine.peakHoldTime)) s")
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
Slider(value: $audioEngine.peakHoldTime, in: 0.5...10, step: 0.5)
|
||||
}
|
||||
}
|
||||
.tabItem {
|
||||
Label("Audio", systemImage: "waveform")
|
||||
}
|
||||
|
||||
// Display Settings
|
||||
Form {
|
||||
Section("Meter Display") {
|
||||
Toggle("Show Peak Indicator", isOn: $showPeakIndicator)
|
||||
|
||||
Picker("Meter Style", selection: $meterStyle) {
|
||||
Text("Classic").tag("classic")
|
||||
Text("Modern").tag("modern")
|
||||
Text("Minimal").tag("minimal")
|
||||
}
|
||||
}
|
||||
|
||||
Section("Performance") {
|
||||
HStack {
|
||||
Text("Update Rate")
|
||||
Spacer()
|
||||
Text("\(Int(updateRate)) fps")
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
Slider(value: $updateRate, in: 10...60, step: 5)
|
||||
}
|
||||
}
|
||||
.tabItem {
|
||||
Label("Display", systemImage: "display")
|
||||
}
|
||||
|
||||
// About
|
||||
VStack(spacing: 20) {
|
||||
Image(systemName: "waveform.circle.fill")
|
||||
.font(.system(size: 64))
|
||||
.foregroundColor(.accentColor)
|
||||
|
||||
Text("Audio VU Meter")
|
||||
.font(.title)
|
||||
.fontWeight(.bold)
|
||||
|
||||
Text("Version 1.0.0")
|
||||
.foregroundColor(.secondary)
|
||||
|
||||
Divider()
|
||||
.frame(width: 200)
|
||||
|
||||
Text("A macOS audio level meter with system monitoring capabilities.")
|
||||
.multilineTextAlignment(.center)
|
||||
.foregroundColor(.secondary)
|
||||
.frame(width: 300)
|
||||
|
||||
Spacer()
|
||||
|
||||
Text("For use with BlackHole virtual audio device")
|
||||
.font(.caption)
|
||||
.foregroundColor(.secondary)
|
||||
}
|
||||
.padding()
|
||||
.tabItem {
|
||||
Label("About", systemImage: "info.circle")
|
||||
}
|
||||
}
|
||||
.frame(width: 450, height: 300)
|
||||
}
|
||||
}
|
||||
|
||||
#Preview {
|
||||
SettingsView()
|
||||
.environmentObject(AudioEngine())
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
//
|
||||
// SystemMonitor.swift
|
||||
// AudioVUMeter
|
||||
//
|
||||
// System resource monitoring for CPU, RAM, Disk, and Network
|
||||
// Uses mach kernel APIs for accurate system statistics
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Darwin
|
||||
|
||||
/// System resource monitor class
|
||||
class SystemMonitor: ObservableObject {
|
||||
// MARK: - Published Properties
|
||||
|
||||
@Published var cpuUsage: Double = 0
|
||||
@Published var memoryUsage: Double = 0
|
||||
@Published var diskActivity: Double = 0
|
||||
@Published var networkActivity: Double = 0
|
||||
|
||||
// Additional details
|
||||
@Published var cpuUserUsage: Double = 0
|
||||
@Published var cpuSystemUsage: Double = 0
|
||||
@Published var memoryUsed: UInt64 = 0
|
||||
@Published var memoryTotal: UInt64 = 0
|
||||
@Published var networkBytesIn: UInt64 = 0
|
||||
@Published var networkBytesOut: UInt64 = 0
|
||||
|
||||
// MARK: - Private Properties
|
||||
|
||||
private var updateTimer: Timer?
|
||||
private var previousCPUInfo: host_cpu_load_info?
|
||||
private var previousNetworkBytes: (in: UInt64, out: UInt64) = (0, 0)
|
||||
private var previousDiskBytes: (read: UInt64, write: UInt64) = (0, 0)
|
||||
|
||||
private let updateInterval: TimeInterval = 0.5
|
||||
|
||||
// MARK: - Public Methods
|
||||
|
||||
/// Start monitoring system resources
|
||||
func startMonitoring() {
|
||||
// Get initial values
|
||||
previousCPUInfo = getCPULoadInfo()
|
||||
previousNetworkBytes = getNetworkBytes()
|
||||
previousDiskBytes = getDiskBytes()
|
||||
|
||||
// Start update timer
|
||||
updateTimer = Timer.scheduledTimer(withTimeInterval: updateInterval, repeats: true) { [weak self] _ in
|
||||
self?.updateMetrics()
|
||||
}
|
||||
|
||||
// Initial update
|
||||
updateMetrics()
|
||||
}
|
||||
|
||||
/// Stop monitoring
|
||||
func stopMonitoring() {
|
||||
updateTimer?.invalidate()
|
||||
updateTimer = nil
|
||||
}
|
||||
|
||||
// MARK: - Private Methods
|
||||
|
||||
private func updateMetrics() {
|
||||
DispatchQueue.global(qos: .background).async { [weak self] in
|
||||
guard let self = self else { return }
|
||||
|
||||
let cpu = self.calculateCPUUsage()
|
||||
let memory = self.calculateMemoryUsage()
|
||||
let disk = self.calculateDiskActivity()
|
||||
let network = self.calculateNetworkActivity()
|
||||
|
||||
DispatchQueue.main.async {
|
||||
self.cpuUsage = cpu.total
|
||||
self.cpuUserUsage = cpu.user
|
||||
self.cpuSystemUsage = cpu.system
|
||||
|
||||
self.memoryUsage = memory.percentage
|
||||
self.memoryUsed = memory.used
|
||||
self.memoryTotal = memory.total
|
||||
|
||||
self.diskActivity = disk
|
||||
self.networkActivity = network.percentage
|
||||
self.networkBytesIn = network.bytesIn
|
||||
self.networkBytesOut = network.bytesOut
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CPU Monitoring
|
||||
|
||||
private func getCPULoadInfo() -> host_cpu_load_info? {
|
||||
var cpuLoadInfo = host_cpu_load_info()
|
||||
var count = mach_msg_type_number_t(MemoryLayout<host_cpu_load_info>.stride / MemoryLayout<integer_t>.stride)
|
||||
|
||||
let result = withUnsafeMutablePointer(to: &cpuLoadInfo) {
|
||||
$0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) {
|
||||
host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, $0, &count)
|
||||
}
|
||||
}
|
||||
|
||||
return result == KERN_SUCCESS ? cpuLoadInfo : nil
|
||||
}
|
||||
|
||||
private func calculateCPUUsage() -> (total: Double, user: Double, system: Double) {
|
||||
guard let currentInfo = getCPULoadInfo(),
|
||||
let previousInfo = previousCPUInfo else {
|
||||
return (0, 0, 0)
|
||||
}
|
||||
|
||||
let userDiff = Double(currentInfo.cpu_ticks.0 - previousInfo.cpu_ticks.0)
|
||||
let systemDiff = Double(currentInfo.cpu_ticks.1 - previousInfo.cpu_ticks.1)
|
||||
let idleDiff = Double(currentInfo.cpu_ticks.2 - previousInfo.cpu_ticks.2)
|
||||
let niceDiff = Double(currentInfo.cpu_ticks.3 - previousInfo.cpu_ticks.3)
|
||||
|
||||
let totalTicks = userDiff + systemDiff + idleDiff + niceDiff
|
||||
|
||||
guard totalTicks > 0 else { return (0, 0, 0) }
|
||||
|
||||
let userPercent = (userDiff / totalTicks) * 100
|
||||
let systemPercent = (systemDiff / totalTicks) * 100
|
||||
let totalPercent = ((userDiff + systemDiff + niceDiff) / totalTicks) * 100
|
||||
|
||||
previousCPUInfo = currentInfo
|
||||
|
||||
return (min(totalPercent, 100), min(userPercent, 100), min(systemPercent, 100))
|
||||
}
|
||||
|
||||
// MARK: - Memory Monitoring
|
||||
|
||||
private func calculateMemoryUsage() -> (percentage: Double, used: UInt64, total: UInt64) {
|
||||
var stats = vm_statistics64()
|
||||
var count = mach_msg_type_number_t(MemoryLayout<vm_statistics64>.stride / MemoryLayout<integer_t>.stride)
|
||||
|
||||
let result = withUnsafeMutablePointer(to: &stats) {
|
||||
$0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) {
|
||||
host_statistics64(mach_host_self(), HOST_VM_INFO64, $0, &count)
|
||||
}
|
||||
}
|
||||
|
||||
guard result == KERN_SUCCESS else {
|
||||
return (0, 0, 0)
|
||||
}
|
||||
|
||||
let pageSize = UInt64(vm_kernel_page_size)
|
||||
let totalMemory = ProcessInfo.processInfo.physicalMemory
|
||||
|
||||
// Calculate used memory
|
||||
let activeMemory = UInt64(stats.active_count) * pageSize
|
||||
let wiredMemory = UInt64(stats.wire_count) * pageSize
|
||||
let compressedMemory = UInt64(stats.compressor_page_count) * pageSize
|
||||
|
||||
let usedMemory = activeMemory + wiredMemory + compressedMemory
|
||||
let percentage = (Double(usedMemory) / Double(totalMemory)) * 100
|
||||
|
||||
return (min(percentage, 100), usedMemory, totalMemory)
|
||||
}
|
||||
|
||||
// MARK: - Disk Monitoring
|
||||
|
||||
private func getDiskBytes() -> (read: UInt64, write: UInt64) {
|
||||
// Use IOKit for disk statistics
|
||||
// Simplified implementation - returns approximate values
|
||||
var readBytes: UInt64 = 0
|
||||
var writeBytes: UInt64 = 0
|
||||
|
||||
// Get disk statistics from system
|
||||
let task = Process()
|
||||
task.launchPath = "/usr/bin/iostat"
|
||||
task.arguments = ["-d", "-c", "1"]
|
||||
|
||||
let pipe = Pipe()
|
||||
task.standardOutput = pipe
|
||||
|
||||
do {
|
||||
try task.run()
|
||||
task.waitUntilExit()
|
||||
|
||||
let data = pipe.fileHandleForReading.readDataToEndOfFile()
|
||||
if let output = String(data: data, encoding: .utf8) {
|
||||
// Parse iostat output
|
||||
let lines = output.components(separatedBy: "\n")
|
||||
if lines.count > 2 {
|
||||
let values = lines[2].split(separator: " ").compactMap { Double($0) }
|
||||
if values.count >= 3 {
|
||||
// KB/t, tps, MB/s
|
||||
readBytes = UInt64(values.last ?? 0 * 1024 * 1024)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Fallback to simulated values
|
||||
}
|
||||
|
||||
return (readBytes, writeBytes)
|
||||
}
|
||||
|
||||
private func calculateDiskActivity() -> Double {
|
||||
let currentBytes = getDiskBytes()
|
||||
let readDiff = currentBytes.read > previousDiskBytes.read ?
|
||||
currentBytes.read - previousDiskBytes.read : 0
|
||||
let writeDiff = currentBytes.write > previousDiskBytes.write ?
|
||||
currentBytes.write - previousDiskBytes.write : 0
|
||||
|
||||
previousDiskBytes = currentBytes
|
||||
|
||||
// Normalize to percentage (assuming 100MB/s as max)
|
||||
let totalBytes = Double(readDiff + writeDiff)
|
||||
let maxBytesPerInterval = 100.0 * 1024 * 1024 * updateInterval
|
||||
let percentage = (totalBytes / maxBytesPerInterval) * 100
|
||||
|
||||
return min(percentage, 100)
|
||||
}
|
||||
|
||||
// MARK: - Network Monitoring
|
||||
|
||||
private func getNetworkBytes() -> (in: UInt64, out: UInt64) {
|
||||
var ifaddr: UnsafeMutablePointer<ifaddrs>?
|
||||
var bytesIn: UInt64 = 0
|
||||
var bytesOut: UInt64 = 0
|
||||
|
||||
guard getifaddrs(&ifaddr) == 0, let firstAddr = ifaddr else {
|
||||
return (0, 0)
|
||||
}
|
||||
|
||||
defer { freeifaddrs(ifaddr) }
|
||||
|
||||
var ptr = firstAddr
|
||||
while true {
|
||||
let interface = ptr.pointee
|
||||
|
||||
// Check for data link layer
|
||||
if interface.ifa_addr.pointee.sa_family == UInt8(AF_LINK) {
|
||||
// Get network interface data
|
||||
if let data = interface.ifa_data {
|
||||
let networkData = data.assumingMemoryBound(to: if_data.self).pointee
|
||||
bytesIn += UInt64(networkData.ifi_ibytes)
|
||||
bytesOut += UInt64(networkData.ifi_obytes)
|
||||
}
|
||||
}
|
||||
|
||||
guard let next = interface.ifa_next else { break }
|
||||
ptr = next
|
||||
}
|
||||
|
||||
return (bytesIn, bytesOut)
|
||||
}
|
||||
|
||||
private func calculateNetworkActivity() -> (percentage: Double, bytesIn: UInt64, bytesOut: UInt64) {
|
||||
let currentBytes = getNetworkBytes()
|
||||
|
||||
let bytesInDiff = currentBytes.in > previousNetworkBytes.in ?
|
||||
currentBytes.in - previousNetworkBytes.in : 0
|
||||
let bytesOutDiff = currentBytes.out > previousNetworkBytes.out ?
|
||||
currentBytes.out - previousNetworkBytes.out : 0
|
||||
|
||||
previousNetworkBytes = currentBytes
|
||||
|
||||
// Calculate rate in bytes per second
|
||||
let totalBytesPerSecond = Double(bytesInDiff + bytesOutDiff) / updateInterval
|
||||
|
||||
// Normalize to percentage (assuming 100 Mbps as reference)
|
||||
let maxBytesPerSecond = 100.0 * 1024 * 1024 / 8 // 100 Mbps in bytes
|
||||
let percentage = (totalBytesPerSecond / maxBytesPerSecond) * 100
|
||||
|
||||
return (min(percentage, 100), bytesInDiff, bytesOutDiff)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Memory Formatter Extension
|
||||
extension SystemMonitor {
|
||||
/// Format bytes to human readable string
|
||||
static func formatBytes(_ bytes: UInt64) -> String {
|
||||
let formatter = ByteCountFormatter()
|
||||
formatter.countStyle = .memory
|
||||
return formatter.string(fromByteCount: Int64(bytes))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
//
|
||||
// VUMeterView.swift
|
||||
// AudioVUMeter
|
||||
//
|
||||
// Classic VU Meter visualization component
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
|
||||
enum MeterColorScheme {
|
||||
case audio
|
||||
case cpu
|
||||
case ram
|
||||
case disk
|
||||
case network
|
||||
|
||||
var gradient: [Color] {
|
||||
switch self {
|
||||
case .audio:
|
||||
return [.green, .yellow, .orange, .red]
|
||||
case .cpu:
|
||||
return [.blue, .cyan, .yellow, .red]
|
||||
case .ram:
|
||||
return [.purple, .pink, .orange, .red]
|
||||
case .disk:
|
||||
return [.teal, .green, .yellow, .orange]
|
||||
case .network:
|
||||
return [.indigo, .blue, .cyan, .green]
|
||||
}
|
||||
}
|
||||
|
||||
var accentColor: Color {
|
||||
switch self {
|
||||
case .audio: return .green
|
||||
case .cpu: return .blue
|
||||
case .ram: return .purple
|
||||
case .disk: return .teal
|
||||
case .network: return .indigo
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Vertical VU Meter (for Audio)
|
||||
struct VUMeterView: View {
|
||||
let level: Double // 0.0 to 1.0
|
||||
let peakLevel: Double
|
||||
let label: String
|
||||
let colorScheme: MeterColorScheme
|
||||
|
||||
@State private var animatedLevel: Double = 0
|
||||
|
||||
private let segmentCount = 20
|
||||
private let meterHeight: CGFloat = 200
|
||||
private let meterWidth: CGFloat = 35
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 8) {
|
||||
// Label
|
||||
Text(label)
|
||||
.font(.system(size: 14, weight: .bold, design: .monospaced))
|
||||
.foregroundColor(.white)
|
||||
|
||||
// Meter
|
||||
ZStack(alignment: .bottom) {
|
||||
// Background
|
||||
RoundedRectangle(cornerRadius: 4)
|
||||
.fill(Color.black.opacity(0.5))
|
||||
.frame(width: meterWidth, height: meterHeight)
|
||||
|
||||
// Segments
|
||||
VStack(spacing: 2) {
|
||||
ForEach((0..<segmentCount).reversed(), id: \.self) { index in
|
||||
let segmentThreshold = Double(index) / Double(segmentCount)
|
||||
let isLit = animatedLevel > segmentThreshold
|
||||
|
||||
RoundedRectangle(cornerRadius: 2)
|
||||
.fill(segmentColor(for: index, isLit: isLit))
|
||||
.frame(width: meterWidth - 6, height: (meterHeight - CGFloat(segmentCount + 1) * 2) / CGFloat(segmentCount))
|
||||
.shadow(color: isLit ? segmentColor(for: index, isLit: true).opacity(0.5) : .clear, radius: 3)
|
||||
}
|
||||
}
|
||||
.padding(3)
|
||||
|
||||
// Peak indicator
|
||||
if peakLevel > 0 {
|
||||
let peakPosition = meterHeight * CGFloat(1 - peakLevel)
|
||||
Rectangle()
|
||||
.fill(Color.red)
|
||||
.frame(width: meterWidth - 2, height: 3)
|
||||
.offset(y: -meterHeight + peakPosition + meterHeight)
|
||||
}
|
||||
|
||||
// dB Scale markers
|
||||
HStack {
|
||||
VStack(alignment: .trailing, spacing: 0) {
|
||||
ForEach([0, -6, -12, -20, -40, -60], id: \.self) { db in
|
||||
Text("\(db)")
|
||||
.font(.system(size: 8, design: .monospaced))
|
||||
.foregroundColor(.gray)
|
||||
if db != -60 {
|
||||
Spacer()
|
||||
}
|
||||
}
|
||||
}
|
||||
.frame(height: meterHeight)
|
||||
.offset(x: -meterWidth/2 - 15)
|
||||
|
||||
Spacer()
|
||||
}
|
||||
}
|
||||
.frame(width: meterWidth + 30, height: meterHeight)
|
||||
}
|
||||
.onChange(of: level) { newValue in
|
||||
withAnimation(.easeOut(duration: 0.05)) {
|
||||
animatedLevel = newValue
|
||||
}
|
||||
}
|
||||
.onAppear {
|
||||
animatedLevel = level
|
||||
}
|
||||
}
|
||||
|
||||
private func segmentColor(for index: Int, isLit: Bool) -> Color {
|
||||
if !isLit {
|
||||
return Color.gray.opacity(0.2)
|
||||
}
|
||||
|
||||
let position = Double(index) / Double(segmentCount)
|
||||
let colors = colorScheme.gradient
|
||||
|
||||
if position > 0.9 { return colors[3] } // Red zone
|
||||
if position > 0.75 { return colors[2] } // Orange zone
|
||||
if position > 0.5 { return colors[1] } // Yellow zone
|
||||
return colors[0] // Green zone
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Circular System Meter
|
||||
struct SystemMeterView: View {
|
||||
let value: Double // 0.0 to 100.0
|
||||
let label: String
|
||||
let unit: String
|
||||
let colorScheme: MeterColorScheme
|
||||
|
||||
@State private var animatedValue: Double = 0
|
||||
|
||||
private let meterSize: CGFloat = 70
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 5) {
|
||||
ZStack {
|
||||
// Background circle
|
||||
Circle()
|
||||
.stroke(Color.gray.opacity(0.2), lineWidth: 8)
|
||||
.frame(width: meterSize, height: meterSize)
|
||||
|
||||
// Progress arc
|
||||
Circle()
|
||||
.trim(from: 0, to: CGFloat(animatedValue / 100))
|
||||
.stroke(
|
||||
AngularGradient(
|
||||
gradient: Gradient(colors: colorScheme.gradient),
|
||||
center: .center,
|
||||
startAngle: .degrees(0),
|
||||
endAngle: .degrees(360)
|
||||
),
|
||||
style: StrokeStyle(lineWidth: 8, lineCap: .round)
|
||||
)
|
||||
.frame(width: meterSize, height: meterSize)
|
||||
.rotationEffect(.degrees(-90))
|
||||
|
||||
// Value display
|
||||
VStack(spacing: 0) {
|
||||
Text(String(format: "%.0f", animatedValue))
|
||||
.font(.system(size: 18, weight: .bold, design: .monospaced))
|
||||
.foregroundColor(.white)
|
||||
Text(unit)
|
||||
.font(.system(size: 10, design: .monospaced))
|
||||
.foregroundColor(.gray)
|
||||
}
|
||||
}
|
||||
|
||||
Text(label)
|
||||
.font(.system(size: 11, weight: .semibold, design: .monospaced))
|
||||
.foregroundColor(colorScheme.accentColor)
|
||||
}
|
||||
.onChange(of: value) { newValue in
|
||||
withAnimation(.easeOut(duration: 0.3)) {
|
||||
animatedValue = newValue
|
||||
}
|
||||
}
|
||||
.onAppear {
|
||||
animatedValue = value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Horizontal Bar Meter
|
||||
struct HorizontalMeterView: View {
|
||||
let value: Double
|
||||
let label: String
|
||||
let colorScheme: MeterColorScheme
|
||||
|
||||
@State private var animatedValue: Double = 0
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
HStack {
|
||||
Text(label)
|
||||
.font(.system(size: 11, weight: .semibold, design: .monospaced))
|
||||
.foregroundColor(.gray)
|
||||
Spacer()
|
||||
Text(String(format: "%.1f%%", animatedValue))
|
||||
.font(.system(size: 11, weight: .bold, design: .monospaced))
|
||||
.foregroundColor(.white)
|
||||
}
|
||||
|
||||
GeometryReader { geometry in
|
||||
ZStack(alignment: .leading) {
|
||||
// Background
|
||||
RoundedRectangle(cornerRadius: 4)
|
||||
.fill(Color.gray.opacity(0.2))
|
||||
|
||||
// Fill
|
||||
RoundedRectangle(cornerRadius: 4)
|
||||
.fill(
|
||||
LinearGradient(
|
||||
gradient: Gradient(colors: colorScheme.gradient),
|
||||
startPoint: .leading,
|
||||
endPoint: .trailing
|
||||
)
|
||||
)
|
||||
.frame(width: geometry.size.width * CGFloat(animatedValue / 100))
|
||||
}
|
||||
}
|
||||
.frame(height: 12)
|
||||
}
|
||||
.onChange(of: value) { newValue in
|
||||
withAnimation(.easeOut(duration: 0.3)) {
|
||||
animatedValue = newValue
|
||||
}
|
||||
}
|
||||
.onAppear {
|
||||
animatedValue = value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#Preview {
|
||||
HStack(spacing: 30) {
|
||||
VUMeterView(level: 0.7, peakLevel: 0.9, label: "L", colorScheme: .audio)
|
||||
VUMeterView(level: 0.5, peakLevel: 0.8, label: "R", colorScheme: .audio)
|
||||
}
|
||||
.padding()
|
||||
.background(Color.black)
|
||||
}
|
||||
Reference in New Issue
Block a user