!7 cmodule ListenOnNoise > DynPrintLogAndEnabled { switchable double threshold = 50; // volume percentage switchable double minDurationAfterNoise = 1.5; // seconds switchable double maxDuration = 10.0; // seconds transient float lastVolume; transient long lastNoise; // in sysNow time start { dm_addAudioListener(voidfunc(short[] data) { if (!enabled) ret; // Quickly calculate the volume float vol = shortSamplesToPercentVolume(data); short[] clonedBuf = vol >= threshold && lastVolume < threshold ? cloneShortArray(data) : null; q.add(r { S recorder = dm_requireQuickAudioRecord(); long recordingSince = cast dm_call(recorder, 'recordingSince); bool noise = vol >= threshold; bool isRecording = recordingSince != 0; if (noise) lastNoise = sysNow(); if (isRecording) { // stop if max duration reached or no recent noise if (elapsedSeconds(recordingSince) >= maxDuration || elapsedSeconds(lastNoise) > minDurationAfterNoise) dm_call(recorder, 'stopRecording); } else { // start recording if (noise) { sleep(10); // avoid audio listener race condition dm_call(recorder, 'startRecording, clonedBuf); } } }); }); } }