// Windows Audio с использованием разных сессий для музыки и баркера const { spawn } = require('child_process'); const path = require('path'); const fs = require('fs'); class WindowsSessionAudio { constructor(sessionName = 'music') { this.sessionName = sessionName; this.process = null; this.volume = 70; this.isPlaying = false; } play(filePath, volume = null) { this.stop(); if (!fs.existsSync(filePath)) { console.error(`[SESSION-AUDIO-${this.sessionName}] Файл не найден:`, filePath); return false; } const effectiveVolume = volume !== null ? volume : this.volume; const volumeDecimal = effectiveVolume / 100; console.log(`[SESSION-AUDIO-${this.sessionName}] Воспроизведение:`, path.basename(filePath)); console.log(`[SESSION-AUDIO-${this.sessionName}] Громкость:`, effectiveVolume + '%'); // PowerShell скрипт с использованием Windows.Media.Playback const script = ` # Используем Windows Runtime API для лучшего контроля Add-Type -AssemblyName System.Runtime.WindowsRuntime Add-Type -AssemblyName presentationcore # Создаем MediaPlayer $player = New-Object System.Windows.Media.MediaPlayer $player.Volume = ${volumeDecimal} # Устанавливаем тег для идентификации сессии $player.CommandManager.IsEnabled = $false # Открываем файл $player.Open("${filePath.replace(/\\/g, '\\\\')}") # Ждем загрузки $timeout = 0 while ($player.NaturalDuration.HasTimeSpan -eq $false -and $timeout -lt 50) { Start-Sleep -Milliseconds 100 $timeout++ } if ($player.NaturalDuration.HasTimeSpan -eq $false) { Write-Host "ERROR:Failed to load file" exit 1 } # Информация о сессии Write-Host "SESSION:${this.sessionName}" Write-Host "VOLUME:${effectiveVolume}" Write-Host "PID:$PID" # Запускаем воспроизведение $player.Play() Write-Host "STATUS:PLAYING" # Главный цикл $running = $true while ($running) { # Проверяем завершение if ($player.Position -ge $player.NaturalDuration.TimeSpan) { Write-Host "STATUS:FINISHED" $running = $false } # Проверяем состояние плеера if ($player.Source -eq $null) { Write-Host "STATUS:STOPPED" $running = $false } Start-Sleep -Milliseconds 100 } $player.Stop() $player.Close() `; this.process = spawn('powershell', [ '-NoProfile', '-WindowStyle', 'Hidden', '-Command', script ], { windowsHide: true }); this.isPlaying = true; this.volume = effectiveVolume; // Обработчики событий this.process.stdout.on('data', (data) => { const output = data.toString().trim(); if (output) { console.log(`[SESSION-AUDIO-${this.sessionName}]`, output); } }); this.process.stderr.on('data', (data) => { console.error(`[SESSION-AUDIO-${this.sessionName}] Ошибка:`, data.toString()); }); this.process.on('close', (code) => { console.log(`[SESSION-AUDIO-${this.sessionName}] Процесс завершен:`, code); this.process = null; this.isPlaying = false; }); return true; } stop() { if (this.process) { console.log(`[SESSION-AUDIO-${this.sessionName}] Остановка`); try { this.process.kill('SIGTERM'); } catch (e) { try { spawn('taskkill', ['/F', '/T', '/PID', this.process.pid.toString()], { stdio: 'ignore', windowsHide: true }); } catch (e2) {} } this.process = null; this.isPlaying = false; } } setVolume(volume) { this.volume = volume; // Для применения новой громкости нужно перезапустить console.log(`[SESSION-AUDIO-${this.sessionName}] Громкость изменена на:`, volume); } } module.exports = WindowsSessionAudio;