Open_Duck_Mini_Interact/volume_module.py
2025-09-29 09:19:40 +08:00

93 lines
3.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import subprocess
import re
import sys
# 原代码4. 音频控制项自动检测与音量控制完整逻辑
def detect_audio_control():
"""自动检测可用的音频播放控制项"""
try:
result = subprocess.run(["amixer", "controls"], capture_output=True, text=True)
playback_controls = []
# 优先查找常见的音频控制项
priority_names = ["Master", "Speaker", "Headphone", "Audio", "Sound"]
for name in priority_names:
if name in result.stdout:
print(f"✅ 自动检测到音频控制项:{name}")
return name
# 如果没有找到优先项,从所有控制项中提取
for line in result.stdout.splitlines():
if "Playback" in line:
match = re.search(r"'([^']+)'", line)
if match:
playback_controls.append(match.group(1))
if playback_controls:
print(f"✅ 找到音频控制项:{playback_controls[0]}")
return playback_controls[0]
else:
print("⚠️ 未检测到音频控制项,将尝试不指定控制项调节音量")
return None
except Exception as e:
print(f"❌ 音频控制检测失败:{str(e)}")
return None
class VolumeController:
def __init__(self, audio_control_name, current_volume, volume_step, min_volume, max_volume):
# 接收调度脚本传入的全局参数,保持原逻辑
self.available = True
self.AUDIO_CONTROL_NAME = audio_control_name
self.CURRENT_VOLUME = current_volume
self.VOLUME_STEP = volume_step
self.MIN_VOLUME = min_volume
self.MAX_VOLUME = max_volume
try:
# 强制取消静音并设置初始音量
self.set_system_volume(self.CURRENT_VOLUME)
current_volume = self.get_system_volume()
if current_volume is not None:
self.CURRENT_VOLUME = current_volume
print(f"🔊 音量控制初始化成功(当前音量:{self.CURRENT_VOLUME}%")
else:
print(f"⚠️ 无法获取当前音量,但已尝试设置为{self.CURRENT_VOLUME}%")
except Exception as e:
self.available = False
print(f"❌ 音量控制失败:{str(e)}")
def get_system_volume(self):
try:
# 根据检测到的控制项获取音量
cmd = ["amixer", "get"]
if self.AUDIO_CONTROL_NAME:
cmd.append(self.AUDIO_CONTROL_NAME)
result = subprocess.run(cmd, capture_output=True, text=True)
volume_match = re.search(r"(\d+)%", result.stdout)
return int(volume_match.group(1)) if volume_match else None
except Exception as e:
print(f"❌ 获取音量失败:{str(e)}")
return None
def set_system_volume(self, target_volume: int):
target_volume = max(self.MIN_VOLUME, min(self.MAX_VOLUME, target_volume))
try:
# 根据检测到的控制项设置音量
cmd = ["amixer", "set"]
if self.AUDIO_CONTROL_NAME:
cmd.append(self.AUDIO_CONTROL_NAME)
cmd.extend([f"{target_volume}%", "unmute"]) # 强制取消静音
subprocess.run(cmd, capture_output=True)
self.CURRENT_VOLUME = target_volume
print(f"🔊 音量已调整至:{self.CURRENT_VOLUME}%")
return True
except Exception as e:
print(f"❌ 调整音量失败:{str(e)}")
return False
def adjust_volume(self, is_increase: bool):
target_volume = self.CURRENT_VOLUME + self.VOLUME_STEP if is_increase else self.CURRENT_VOLUME - self.VOLUME_STEP
return self.set_system_volume(target_volume)