KO
apps/winzik / src / Media / Blanks.php · commit 6576d6f
<?phpnamespace App\Media;/** * The silence at the start and at the end of a song, in its sound (a WAV): where the music really begins and ends. * Only its first and last 30 seconds are looked at, by slices of 50 ms (a quiet slice: under -40 dB). Run in a helper * process (App\Work\Worker 'blanks'): the interface never waits for it. */final class Blanks{    private const SLICE = 0.05;    private const LOOK = 30.0;    /** a slice quieter than this (its RMS, 1 = full scale) is silence: -40 dB */    private const QUIET = 0.01;    /** @return array{0: float, 1: float} where the music begins, where it ends (0: it does not end before the file) */    public static function find(string $wavFile): array    {        $wav = Wav::open($wavFile);        if ($wav === null) {            return [0.0, 0.0];        }        $length = $wav->duration();        $n = (int)round(self::SLICE * $wav->rate);        $loud = fn (float $at): bool => self::rms($wav->samples($at, $n)) >= self::QUIET;        $start = 0.0;        for ($t = 0.0; $t < min(self::LOOK, $length); $t += self::SLICE) {            if ($loud($t)) {                $start = max(0.0, $t - self::SLICE);                break;            }        }        $end = 0.0;        for ($t = $length - self::SLICE; $t > max(0.0, $length - self::LOOK); $t -= self::SLICE) {            if ($loud($t)) {                $end = $t + 2 * self::SLICE;                break;            }        }        // a skip worth it only: half a second of silence at least        return [$start >= 0.5 ? round($start, 2) : 0.0, $end > 0 && $length - $end >= 0.5 ? round($end, 2) : 0.0];    }    /** @param list<float> $samples */    private static function rms(array $samples): float    {        if ($samples === []) {            return 0.0;        }        $sum = 0.0;        foreach ($samples as $s) {            $sum += $s * $s;        }        return sqrt($sum / count($samples));    }}