Test iOS Audio Spectra on a Cloud Mac
A client’s recording analysis page already displayed a spectrum, but acceptance testing revealed a factor-of-two difference between two versions analyzing the same audio. The capture hardware is not necessarily to blame: converting a two-sided spectrum to a one-sided spectrum, normalizing the transform, or passing along the sample rate can all produce a plot that looks right but reports the wrong values. A studio can first establish deterministic signal tests on a cloud Mac, then validate hardware capture on the target device.
Agree on What Acceptance Testing Measures
This article validates the one-sided peak amplitude spectrum of real-valued input—not a power spectrum, power spectral density, or sound pressure level. Input samples use normalized values: a sine wave with a peak amplitude of 0.75 should produce a reading of 0.75 at its frequency bin. If the product displays RMS values, it needs a separate conversion contract.
With the sample count N fixed at 1024 and the sample rate at 8192 Hz, the bin spacing is 8 Hz. Use bin 128 to generate a 1024 Hz sine wave. The full sequence contains an integer number of cycles, so the initial test can omit windowing and keep spectral leakage separate from normalization issues.
Start with inputs whose results can be explained precisely. Do not use microphone recordings as an algorithm reference, and do not treat a passing cloud test as proof that real acoustic measurements are correct.
Also record the toolchain version and commit ID. Keep fixtures and thresholds specific to each client project; do not loosen a global tolerance just to make another project pass.
Build a Fixture That Needs No Audio Device
On a cloud Mac with the Xcode command-line tools configured, save the following code as SpectrumCheck.swift. It uses Accelerate’s complex DFT with zero-valued imaginary input, deliberately avoiding the packed layout of real transforms so that the normalization rules are easier to inspect.
import Foundation
import Accelerate
enum SpectrumError: Error {
case invalidInput
case setupFailed
}
func amplitudes(_ samples: [Double]) throws -> [Double] {
let n = samples.count
guard n >= 2,
n & (n - 1) == 0,
samples.allSatisfy({ $0.isFinite }) else {
throw SpectrumError.invalidInput
}
guard let setup = vDSP_DFT_zop_CreateSetupD(
nil, vDSP_Length(n), .FORWARD
) else {
throw SpectrumError.setupFailed
}
defer { vDSP_DFT_DestroySetupD(setup) }
let imaginary = [Double](repeating: 0, count: n)
var realOutput = imaginary
var imaginaryOutput = imaginary
samples.withUnsafeBufferPointer { input in
imaginary.withUnsafeBufferPointer { zero in
realOutput.withUnsafeMutableBufferPointer { real in
imaginaryOutput.withUnsafeMutableBufferPointer { imag in
vDSP_DFT_ExecuteD(
setup,
input.baseAddress!,
zero.baseAddress!,
real.baseAddress!,
imag.baseAddress!
)
}
}
}
}
return (0...n / 2).map { k in
let scale = (k == 0 || k == n / 2) ? 1.0 : 2.0
return hypot(realOutput[k], imaginaryOutput[k])
* scale / Double(n)
}
}
let n = 1024
let bin = 128
let tone = (0..<n).map { index in
0.75 * sin(2 * Double.pi * Double(bin * index) / Double(n))
}
let spectrum = try amplitudes(tone)
let peak = spectrum.indices.max {
spectrum[$0] < spectrum[$1]
}!
precondition(spectrum.count == n / 2 + 1)
precondition(peak == bin)
precondition(abs(spectrum[bin] - 0.75) < 1e-9)
precondition(spectrum.enumerated().allSatisfy {
$0.offset == bin || $0.element < 1e-9
})
let dc = try amplitudes([Double](repeating: 0.25, count: n))
precondition(abs(dc[0] - 0.25) < 1e-9)
let alternating = (0..<n).map { $0.isMultiple(of: 2) ? 0.5 : -0.5 }
let nyquist = try amplitudes(alternating)
precondition(abs(nyquist[n / 2] - 0.5) < 1e-9)
Run it with:
xcrun swift SpectrumCheck.swift
A successful run produces no output. A failed assertion or invalid input causes the process to exit with a nonzero status. Do not compile this fixture with optimization options that remove precondition checks. In the production project, move the assertions into a test target and call the spectrum function the product actually uses. Running the example alone does not establish that the production implementation is correct.
Use Three Signals to Check Normalization Boundaries
For a sine wave aligned with an ordinary frequency bin, an unnormalized forward complex DFT produces a magnitude of approximately N × amplitude ÷ 2 on each side of the spectrum, at the positive and negative frequencies. A one-sided spectrum retains the positive-frequency side, so ordinary bins must be divided by N and then multiplied by two.
The DC and Nyquist bins are exceptions. Neither has a separate counterpart on the other side, so they are divided only by N. The constant signal and alternating positive/negative signal above are designed to catch the common mistake of doubling every bin.
Calculate frequency labels from the actual sample rate carried by the audio buffer: frequency = bin index × sample rate ÷ N. Changing the fixture’s sample rate should leave amplitudes unchanged while scaling the frequency labels proportionally. Do not hard-code 8192 into the product algorithm; it is only a test input.
Add Windowing and Invalid-Input Tests
Once the bin-aligned tests pass, add a sine wave with a non-integer number of cycles. Energy spreading into neighboring bins is then a normal consequence of finite-length truncation. You can no longer assert that all other bins are zero or require the largest bin to reproduce the original amplitude exactly.
If the product uses a window function, retain the actual window array and specify whether amplitude compensation uses the mean of the window coefficients. Compensation can correct coherent gain, but it cannot eliminate amplitude loss caused by a signal that does not align with a bin. Power analysis must also account for window energy; the peak amplitude formula cannot simply be reused.
Add four sets of failure cases: an empty array, an unsupported length, input containing NaN, and input containing infinity. Each should explicitly return an error rather than produce a screenful of invalid values. Also test all-zero input and require every amplitude to be zero. When converting to a logarithmic display, apply an explicit display floor so that negative infinity does not propagate into the UI layout.
Integrate with the Client Project and Keep Acceptance Evidence
Split the processing chain into six steps: channel selection, framing, windowing, transform, amplitude conversion, and UI mapping. Test each channel first. Do not assume that averaging stereo channels is always correct: if the left and right channels are opposite in phase, averaging cancels the signal outright.
For every acceptance run, save N, the sample rate, window type, amplitude definition, tolerance, and test exit status. Do not apply the Double fixture’s threshold directly to a Float-based product implementation. Establish the threshold again using the calculation precision and fixed inputs, and check silence and boundary signals.
Finally, verify the actual buffer format, channel order, and sample rate after audio session changes on the target device. The cloud Mac makes the numerical algorithm reproducible; device testing establishes that the input chain still meets the contract. Archive the two sets of results separately so that every spectrum value the client sees can be explained.
Frequently asked questions
Why not double every bin in a one-sided amplitude spectrum?
Ordinary positive-frequency bins have matching negative-frequency components. DC and the Nyquist bin of an even-length transform have no separate partners, so divide them by the sample count without doubling.
Does passing on a cloud Mac validate microphone capture?
No. These tests validate calculations for known input samples. Actual sample rate, channel layout, audio-session behavior and hardware capture still need checks on the target device.
Set up a Mac for your next client project
Rent a dedicated physical Mac mini by the day, week, month or quarter. Your Mac is ready on the day you order. Track progress in the console, and submit a support ticket there if you need help.
Rent a cloud Mac