Voxley / app · voxley.si / Sources / Voxley / RecorderWave.swift
| 1 | import AVFoundation |
| 2 | import SwiftUI |
| 3 | |
| 4 | struct WaveformPeak: Equatable, Sendable { |
| 5 | var low: Float = 0 |
| 6 | var high: Float = 0 |
| 7 | } |
| 8 | |
| 9 | struct WaveformFrame: Sendable { |
| 10 | let peaks: [WaveformPeak] |
| 11 | let newestTime: TimeInterval? |
| 12 | let columnDuration: TimeInterval |
| 13 | |
| 14 | static let silence = WaveformFrame(peaks: MicrophoneWaveform.silence, newestTime: nil, columnDuration: 0.014) |
| 15 | |
| 16 | static var hostTime: TimeInterval { AVAudioTime.seconds(forHostTime: mach_absolute_time()) } |
| 17 | |
| 18 | func rightEdge(at hostTime: TimeInterval) -> Double { |
| 19 | let lastIndex = Double(peaks.count - 1) |
| 20 | guard let newestTime else { return lastIndex } |
| 21 | // Leave time for the next audio buffer to arrive before its peaks reach the visible edge. |
| 22 | let displayTime = hostTime - 0.125 |
| 23 | let position = lastIndex + (displayTime - newestTime) / columnDuration |
| 24 | return min(lastIndex, max(Double(MicrophoneWaveform.columnCount - 1), position)) |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | struct MicrophoneWaveform { |
| 29 | static let columnCount = 96 |
| 30 | private static let historyCount = columnCount + 20 |
| 31 | static let silence = Array(repeating: WaveformPeak(), count: historyCount) |
| 32 | private let framesPerColumn: Int |
| 33 | private let columnDuration: TimeInterval |
| 34 | private var columns = Self.silence |
| 35 | private var nextColumn = 0 |
| 36 | private var currentPeak = WaveformPeak() |
| 37 | private var framesInColumn = 0 |
| 38 | private var columnsSinceUpdate = 0 |
| 39 | private var columnsWritten = 0 |
| 40 | private var firstSampleTime: TimeInterval? |
| 41 | |
| 42 | init(sampleRate: Double) { |
| 43 | framesPerColumn = max(1, Int((sampleRate * 0.014).rounded())) |
| 44 | columnDuration = Double(framesPerColumn) / sampleRate |
| 45 | } |
| 46 | |
| 47 | // Keep 1.34 seconds on screen plus enough history to scroll between audio callbacks. |
| 48 | mutating func append(_ samples: UnsafePointer<Float>, count: Int, stride: Int, |
| 49 | bufferStart: TimeInterval) -> WaveformFrame? { |
| 50 | let start = firstSampleTime ?? bufferStart |
| 51 | firstSampleTime = start |
| 52 | for frame in 0..<count { |
| 53 | let sample = samples[frame * stride] |
| 54 | currentPeak.low = min(currentPeak.low, sample) |
| 55 | currentPeak.high = max(currentPeak.high, sample) |
| 56 | framesInColumn += 1 |
| 57 | if framesInColumn == framesPerColumn { |
| 58 | columns[nextColumn] = currentPeak |
| 59 | nextColumn = (nextColumn + 1) % Self.historyCount |
| 60 | framesInColumn = 0 |
| 61 | currentPeak = WaveformPeak() |
| 62 | columnsSinceUpdate += 1 |
| 63 | columnsWritten += 1 |
| 64 | } |
| 65 | } |
| 66 | guard columnsSinceUpdate >= 3 else { return nil } |
| 67 | columnsSinceUpdate = 0 |
| 68 | return WaveformFrame(peaks: Array(columns[nextColumn...] + columns[..<nextColumn]), |
| 69 | newestTime: start + (Double(columnsWritten) - 0.5) * columnDuration, |
| 70 | columnDuration: columnDuration) |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | struct RecorderWave: View { |
| 75 | let frame: WaveformFrame |
| 76 | private static let smoothingWeights: [Float] = [1, 2, 3, 2, 1] |
| 77 | |
| 78 | var body: some View { |
| 79 | let envelope = frame.peaks.indices.map { smoothedPeak(at: $0) } |
| 80 | TimelineView(.animation(minimumInterval: 1.0 / 60, paused: frame.newestTime == nil)) { _ in |
| 81 | trace(envelope, rightEdge: frame.rightEdge(at: WaveformFrame.hostTime)) |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | private func trace(_ envelope: [WaveformPeak], rightEdge: Double) -> some View { |
| 86 | Canvas { context, size in |
| 87 | let center = size.height / 2 |
| 88 | let spacing = size.width / CGFloat(MicrophoneWaveform.columnCount - 1) |
| 89 | let maxHeight = max(0, center - 1) |
| 90 | context.clip(to: Path(CGRect(origin: .zero, size: size))) |
| 91 | let baseline = Path { path in |
| 92 | path.move(to: CGPoint(x: 0, y: center)) |
| 93 | path.addLine(to: CGPoint(x: size.width, y: center)) |
| 94 | } |
| 95 | context.stroke(baseline, with: .color(.white.opacity(0.18)), lineWidth: 0.5) |
| 96 | |
| 97 | let upper = envelope.enumerated().map { index, peak in |
| 98 | CGPoint(x: size.width + (CGFloat(index) - rightEdge) * spacing, |
| 99 | y: center - Self.height(for: peak.high) * maxHeight) |
| 100 | } |
| 101 | let lower = envelope.enumerated().reversed().map { index, peak in |
| 102 | CGPoint(x: size.width + (CGFloat(index) - rightEdge) * spacing, |
| 103 | y: center + Self.height(for: -peak.low) * maxHeight) |
| 104 | } |
| 105 | let trace = Path { path in |
| 106 | path.move(to: upper[0]) |
| 107 | Self.addCurve(through: upper, to: &path) |
| 108 | path.addLine(to: lower[0]) |
| 109 | Self.addCurve(through: lower, to: &path) |
| 110 | path.closeSubpath() |
| 111 | } |
| 112 | context.fill(trace, with: .color(.white.opacity(0.20))) |
| 113 | let edges = Path { path in |
| 114 | path.move(to: upper[0]) |
| 115 | Self.addCurve(through: upper, to: &path) |
| 116 | path.move(to: lower[0]) |
| 117 | Self.addCurve(through: lower, to: &path) |
| 118 | } |
| 119 | context.drawLayer { layer in |
| 120 | layer.clip(to: trace) |
| 121 | layer.stroke(edges, with: .color(.white.opacity(0.92)), lineWidth: 1.8) |
| 122 | } |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | private func smoothedPeak(at index: Int) -> WaveformPeak { |
| 127 | let peaks = frame.peaks |
| 128 | var weighted = WaveformPeak() |
| 129 | var totalWeight: Float = 0 |
| 130 | let radius = Self.smoothingWeights.count / 2 |
| 131 | for offset in -radius...radius where peaks.indices.contains(index + offset) { |
| 132 | let peak = peaks[index + offset] |
| 133 | let weight = Self.smoothingWeights[offset + radius] |
| 134 | weighted.low += peak.low * weight |
| 135 | weighted.high += peak.high * weight |
| 136 | totalWeight += weight |
| 137 | } |
| 138 | return WaveformPeak(low: weighted.low / totalWeight, high: weighted.high / totalWeight) |
| 139 | } |
| 140 | |
| 141 | private static func addCurve(through points: [CGPoint], to path: inout Path) { |
| 142 | for (point, next) in zip(points, points.dropFirst()) { |
| 143 | let midpoint = CGPoint(x: (point.x + next.x) / 2, y: (point.y + next.y) / 2) |
| 144 | path.addQuadCurve(to: midpoint, control: point) |
| 145 | } |
| 146 | if let last = points.last { path.addQuadCurve(to: last, control: last) } |
| 147 | } |
| 148 | |
| 149 | private static func height(for amplitude: Float) -> CGFloat { |
| 150 | let audible = min(1, max(0, amplitude - 0.0025)) |
| 151 | return CGFloat(1 - exp(-2.52 * pow(audible, 0.58))) |
| 152 | } |
| 153 | } |