To automatically remove long pauses from iOS recordings, start with measurement rather than repeated listening over a remote desktop. Upload the same mono audio file to a cloud Mac, calculate its energy in fixed windows, and verify when sound becomes active and when silence is confirmed. This keeps playback latency caused by your local network out of the detection results. This article tests energy-based silence detection, not speech recognition.
Define the sampling and detection contract first
Before running the checks on LoopMac, make sure a working command-line toolchain is available, and record the compiler version with xcrun swift --version. Accept only decodable mono audio. Set the window length to the integer number of frames closest to twenty milliseconds, and read the sample rate from the file rather than assuming it is the same for every input.
For each window, calculate sqrt(sum(x*x)/N), then convert it to dBFS with 20*log10(RMS). Digital zero corresponds to negative infinity; do not silently substitute a finite floor. For these tests, the threshold for entering the active state is −35 dBFS, and the threshold for leaving it is −42 dBFS. These are test parameters, not recommended settings for every microphone.
Low energy does not mean speech is absent, and high energy does not mean someone is speaking. Background music, air conditioning, and softly spoken word endings can all cross the same threshold. Acceptance conclusions must stay within the scope of the input fixtures and threshold settings.
Carry analysis windows across read boundaries
Save the following as rms.swift. The script uses the audio framework to decode audio into non-interleaved floating-point samples and accepts mono input only. It fails immediately on any non-finite sample. Read blocks are units of data transfer; analysis windows are units of the algorithm. Do not treat them as interchangeable.
import Foundation
import AVFoundation
enum InputError: Error {
case arguments, format, sample
}
guard CommandLine.arguments.count == 2 else {
throw InputError.arguments
}
let url = URL(fileURLWithPath: CommandLine.arguments[1])
let file = try AVAudioFile(
forReading: url,
commonFormat: .pcmFormatFloat32,
interleaved: false
)
let format = file.processingFormat
guard format.channelCount == 1,
format.sampleRate.isFinite,
format.sampleRate > 0,
let buffer = AVAudioPCMBuffer(
pcmFormat: format,
frameCapacity: 4096
) else {
throw InputError.format
}
let width = max(1, Int((format.sampleRate * 0.02).rounded()))
var total: Int64 = 0
var count = 0
var squareSum = 0.0
func emit() {
let rms = sqrt(squareSum / Double(count))
let db = rms == 0 ? -Double.infinity : 20 * log10(rms)
let start = total - Int64(count)
print("\(start),\(count),\(db)")
count = 0
squareSum = 0
}
print("start_frame,frame_count,dbfs")
while true {
try file.read(into: buffer)
if buffer.frameLength == 0 { break }
guard let samples = buffer.floatChannelData?[0] else {
throw InputError.format
}
for index in 0..<Int(buffer.frameLength) {
let value = Double(samples[index])
guard value.isFinite else { throw InputError.sample }
squareSum += value * value
count += 1
total += 1
if count == width { emit() }
}
}
if count > 0 { emit() }
Run xcrun swift rms.swift fixture.wav > windows.csv, and retain both the input file's checksum and the output. The script neither normalizes the volume nor resamples the audio. Either operation would make the same threshold correspond to a different input energy, invalidating the basis for comparison.
The final row may represent less than a full window. Calculate its mean using the actual frame count. Do not pad it with zeros and still divide by the full window length; that would artificially reduce the energy of audio at the end. An empty file should produce only the header, not a row representing “silence.”
Confirm cut points with hysteresis and duration requirements
Start in the silent state. When a window meets or exceeds the entry threshold, begin accumulating candidate active frames. Confirm the active state only after the candidate has lasted at least sixty milliseconds. If a window falls below the entry threshold before confirmation, reset the candidate count. Once confirmed, backdate the start to the first candidate frame, not the moment of confirmation.
While active, accumulate candidate silent frames only when a window is strictly below the exit threshold. Confirm the exit after at least two hundred milliseconds. Cancel the candidate whenever a window meets or exceeds the exit threshold. Between the two thresholds, retain the current state rather than switching back and forth.
Implement duration tracking with frame counts, rounding each duration requirement up to a whole number of frames. A short final window contributes only its actual frame count. If the state is still active at the end of the file, the interval ends at the total frame count. Do not append an imaginary stretch of silence.
Keep detection boundaries separate from trim boundaries
If you need to preserve consonant onsets or breaths, add padding before and after the detected intervals. First confirm the intervals, then extend them with padding, clamp them to the file boundaries, and finally merge any overlaps. Padding is part of the trimming policy; it must not feed back into the detection state. Otherwise, test failures become difficult to trace.
Target boundary conditions with synthetic fixtures
Validate the math with constant-valued samples before testing the use case with recordings. A window with a constant amplitude of 0.01 should be close to −40 dBFS. Compare within a tolerance rather than matching floating-point strings. For each fixture below, save the expected frame intervals, not just a “pass” result.
- All-zero and empty inputs: neither should produce active intervals, but their window counts should differ.
- Alternating across a threshold: no transition should be confirmed before the continuous-duration requirement is met.
- Durations one frame apart: a duration just short of the requirement and one that exactly meets it should produce different results.
- Active audio ending at the end of the file: the endpoint must not exceed the total frame count.
- Non-finite samples: report an explicit error rather than silently treating them as silence.
For exact-threshold tests, inject dBFS values directly into the state machine so that audio-encoding quantization cannot shift samples away from the boundary. Use real files to test the entire path from decoding through the state machine. Evidence from these two test layers is not interchangeable.
Verify chunk-size invariance before integration
Set the read capacity to two hundred fifty-seven frames and then to four thousand ninety-six frames, and compare the output start frames, frame counts, and dBFS values. The results should match. A mismatch usually means the energy accumulator was incorrectly cleared at the end of a read loop, or a partial window was processed independently for each block.
Finally, record the input checksum, sample rate, window size in frames, both thresholds, duration requirements, and detected intervals. Multichannel input needs a separately defined rule for combining energy; directly summing waveforms can cause cancellation when channels are out of phase. For acceptance testing with real recordings, also include quiet speech, sustained background noise, and short pauses to check whether false cuts and missed cuts meet product requirements. An energy-only algorithm cannot promise to “keep only the human voice.”
Frequently asked questions
Should one quiet RMS window trigger an audio cut?
No. Require a defined duration below the exit threshold and retain the candidate silence start. Confirm the cut only after that duration is reached.
Why does the sample reject multichannel audio?
It fixes the input to mono so mixing cannot change the result. For multiple channels, calculate energy separately and explicitly choose maximum or mean channel energy.
Choose a cloud Mac for your next project
Need a macOS GUI or command line? Start by choosing a model, location, and billing period that fit your project. After payment, provisioning begins. Check the console for real-time availability.
Choose a cloud Mac plan