scripts/bin/toggle-audio.ts

96 lines
3.2 KiB
JavaScript
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env node
import { execSync } from 'child_process';
const HDMI_OUTPUT = 'alsa_output.pci-0000_01_00.1.hdmi-stereo';
const ANALOG_OUTPUT = 'alsa_output.pci-0000_08_00.6.analog-stereo';
interface AudioDevice {
id: string;
name: string;
}
function getCurrentActiveSink(): AudioDevice | null {
try {
const output = execSync('wpctl status -n', { encoding: 'utf8' });
const lines = output.split('\n');
for (const line of lines) {
if (line.includes('*') && (line.includes(HDMI_OUTPUT) || line.includes(ANALOG_OUTPUT))) {
// Извлекаем ID (число после звездочки и точки)
const match = line.match(/\*\s+(\d+)\./);
if (match) {
const id = match[1];
if (line.includes(HDMI_OUTPUT)) {
return { id, name: HDMI_OUTPUT };
} else if (line.includes(ANALOG_OUTPUT)) {
return { id, name: ANALOG_OUTPUT };
}
}
}
}
return null;
} catch (error) {
console.error('Ошибка при получении текущего аудио устройства:', error);
return null;
}
}
function getDeviceId(deviceName: string): string | null {
try {
const output = execSync('wpctl status -n', { encoding: 'utf8' });
const lines = output.split('\n');
for (const line of lines) {
if (line.includes(deviceName)) {
// Извлекаем ID (число после пробелов и точки)
const match = line.match(/\s+(\d+)\./);
if (match) {
return match[1];
}
}
}
return null;
} catch (error) {
console.error('Ошибка при поиске ID устройства:', error);
return null;
}
}
function setDefaultSink(deviceName: string): void {
const deviceId = getDeviceId(deviceName);
if (!deviceId) {
console.error(`Не удалось найти ID для устройства: ${deviceName}`);
return;
}
try {
execSync(`wpctl set-default ${deviceId}`, { stdio: 'inherit' });
console.log(`Переключен аудио выход на: ${deviceName} (ID: ${deviceId})`);
} catch (error) {
console.error('Ошибка при переключении аудио устройства:', error);
}
}
function main(): void {
const currentSink = getCurrentActiveSink();
if (!currentSink) {
// Если ни один из целевых sink'ов не активен, выбираем аналоговый
console.log('Ни один из целевых аудио выходов не активен. Переключаемся на аналоговый.');
setDefaultSink(ANALOG_OUTPUT);
} else if (currentSink.name === HDMI_OUTPUT) {
// Если активен HDMI, переключаемся на аналоговый
console.log('Активен HDMI выход. Переключаемся на аналоговый.');
setDefaultSink(ANALOG_OUTPUT);
} else if (currentSink.name === ANALOG_OUTPUT) {
// Если активен аналоговый, переключаемся на HDMI
console.log('Активен аналоговый выход. Переключаемся на HDMI.');
setDefaultSink(HDMI_OUTPUT);
}
}
main();