$id, 'size' => $size] = (array)unpack('a4id/Vsize', $chunk); if ($id === 'fmt ') { $fmt = (string)fread($f, (int)$size); ['format' => $format, 'channels' => $w->channels, 'rate' => $w->rate] = (array)unpack('vformat/vchannels/Vrate', $fmt); $bits = (int)(unpack('v', substr($fmt, 14, 2))[1] ?? 0); } elseif ($id === 'data') { $w->dataStart = (int)ftell($f); // ffmpeg writing to a file it cannot rewind puts 0 or -1 here: the rest of the file is the data $w->dataSize = (int)$size > 0 && (int)$size < 0x7FFFFFFF ? (int)$size : PHP_INT_MAX; break; } else { fseek($f, (int)$size + ((int)$size & 1), SEEK_CUR); } } if ($format !== 1 || $bits !== 16 || $w->dataSize === 0 || $w->channels < 1 || $w->rate < 1) { fclose($f); return null; } $w->f = $f; $w->path = $file; return $w; } private string $path = ''; /** Its length in seconds (a WAV still being written: what is there now). */ public function duration(): float { $size = $this->dataSize < PHP_INT_MAX ? $this->dataSize : max(0, (int)@filesize($this->path) - $this->dataStart); return $size / max(1, $this->rate * 2 * $this->channels); } /** @return list $count mono samples from $seconds on (fewer near the end, none past it) */ public function samples(float $seconds, int $count): array { if ($this->f === null) { return []; } $frame = 2 * $this->channels; $offset = (int)floor(max(0.0, $seconds) * $this->rate) * $frame; if ($offset >= $this->dataSize) { return []; } fseek($this->f, $this->dataStart + $offset); $bytes = (string)fread($this->f, $count * $frame); $all = $bytes === '' ? [] : array_values((array)unpack('s*', $bytes)); $out = []; $ch = $this->channels; for ($i = 0, $n = intdiv(count($all), $ch); $i < $n; $i++) { $sum = 0; for ($c = 0; $c < $ch; $c++) { $sum += $all[$i * $ch + $c]; } $out[] = $sum / ($ch * 32768); } return $out; } public function __destruct() { if ($this->f !== null) { fclose($this->f); } } }