ZH
apps/winzik / src / Media / SystemVolume.php · commit 6576d6f
<?phpnamespace App\Media;/** * The volume of the computer (not only WinZik's): Linux through PulseAudio / PipeWire (pactl), else ALSA (amixer); * Windows through its audio API (PowerShell, IAudioEndpointVolume). Read once when asked, written in the background * (the last value only: a slider dragged sends many). */final class SystemVolume{    public int $volume = 50;    public bool $known = false;    private ?Process $job = null;    private ?int $pending = null;    public function __construct(private string $logDir)    {    }    public static function supported(): bool    {        return PHP_OS_FAMILY === 'Windows' || Tools::onPath('pactl') !== null || Tools::onPath('amixer') !== null;    }    /** Asks the computer its volume now (it comes back a moment later in $volume). */    public function read(): void    {        $this->job?->kill();        $this->job = Process::start(self::readCommand(), $this->logDir);        $this->pending = null;    }    public function set(int $volume): void    {        $this->volume = max(0, min(100, $volume));        $this->pending = $this->volume;    }    /** Each frame. */    public function poll(): void    {        if ($this->job !== null) {            $this->job->poll();            if (!$this->job->done()) {                return;            }            if (!$this->known && preg_match('/(\d{1,3})\s*%|^\s*(\d{1,3})\s*$/m', $this->job->output(), $m)) {                $this->volume = (int)($m[1] !== '' ? $m[1] : $m[2]);                $this->known = true;            }            $this->job->cleanup();            $this->job = null;        }        if ($this->pending !== null) {            $this->job = Process::start(self::writeCommand($this->pending), $this->logDir);            $this->pending = null;            $this->known = true;        }    }    /** Quitting: pactl / amixer / PowerShell ended now, the value not yet written forgotten; again: nothing. */    public function stop(): void    {        $this->job?->stop();        $this->job?->cleanup();        $this->job = null;        $this->pending = null;    }    /** @return list<string> */    private static function readCommand(): array    {        if (PHP_OS_FAMILY === 'Windows') {            return ['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', self::windows() . ' [int]([Audio]::Volume * 100)'];        }        return Tools::onPath('pactl') !== null ? ['pactl', 'get-sink-volume', '@DEFAULT_SINK@'] : ['amixer', 'get', 'Master'];    }    /** @return list<string> */    private static function writeCommand(int $v): array    {        if (PHP_OS_FAMILY === 'Windows') {            return ['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', self::windows() . sprintf(' [Audio]::Volume = %.2f', $v / 100)];        }        return Tools::onPath('pactl') !== null ? ['pactl', 'set-sink-volume', '@DEFAULT_SINK@', "$v%"] : ['amixer', 'set', 'Master', "$v%"];    }    /** The audio endpoint of Windows (COM), as PowerShell code: [Audio]::Volume (0..1). */    private static function windows(): string    {        return <<<'PS'Add-Type -TypeDefinition @'using System.Runtime.InteropServices;[Guid("5CDF2C82-841E-4546-9722-0CF74078229A"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]interface IAudioEndpointVolume { int f(); int g(); int h(); int i(); int SetMasterVolumeLevelScalar(float fLevel, System.Guid pguidEventContext); int j(); int GetMasterVolumeLevelScalar(out float pfLevel); }[Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]interface IMMDevice { int Activate(ref System.Guid id, int clsCtx, int activationParams, out IAudioEndpointVolume aev); }[Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]interface IMMDeviceEnumerator { int f(); int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice endpoint); }[ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")] class MMDeviceEnumeratorComObject { }public class Audio {  static IAudioEndpointVolume Vol() { var enumerator = new MMDeviceEnumeratorComObject() as IMMDeviceEnumerator; IMMDevice dev = null;    Marshal.ThrowExceptionForHR(enumerator.GetDefaultAudioEndpoint(0, 1, out dev)); IAudioEndpointVolume epv = null; var epvid = typeof(IAudioEndpointVolume).GUID;    Marshal.ThrowExceptionForHR(dev.Activate(ref epvid, 23, 0, out epv)); return epv; }  public static float Volume { get { float v = -1; Marshal.ThrowExceptionForHR(Vol().GetMasterVolumeLevelScalar(out v)); return v; }    set { Marshal.ThrowExceptionForHR(Vol().SetMasterVolumeLevelScalar(value, System.Guid.Empty)); } }}'@;PS;    }}