66 lines
2.5 KiB
Python
66 lines
2.5 KiB
Python
import subprocess
|
||
import re
|
||
|
||
def get_current_volume():
|
||
"""
|
||
获取当前音量
|
||
:return: 当前音量百分比(0 到 100)
|
||
"""
|
||
try:
|
||
# 使用 amixer 命令获取音量信息
|
||
print("运行 amixer 命令以获取音量信息...") # 先确保能看到此信息
|
||
result = subprocess.run(
|
||
["/usr/bin/amixer", "-D", "pulse", "get", "Master"],
|
||
stdout=subprocess.PIPE,
|
||
stderr=subprocess.PIPE,
|
||
text=True
|
||
)
|
||
|
||
print(f"amixer 命令返回的退出码: {result.returncode}")
|
||
print(f"amixer 命令输出: {result.stdout}")
|
||
print(f"amixer 错误输出: {result.stderr}")
|
||
|
||
if result.returncode == 0:
|
||
# 解析返回的音量信息
|
||
output = result.stdout
|
||
match = re.search(r"(\d+)%", output)
|
||
if match:
|
||
volume = int(match.group(1)) # 返回音量百分比
|
||
print(f"当前音量: {volume}%")
|
||
return volume
|
||
else:
|
||
print("没有找到音量信息")
|
||
return None # 如果未找到音量信息
|
||
else:
|
||
print(f"amixer 执行失败,错误输出: {result.stderr}")
|
||
return None
|
||
except Exception as e:
|
||
print(f"发生错误: {e}")
|
||
return None
|
||
|
||
|
||
def adjust_volume(adjust_volumn_result):
|
||
"""
|
||
调整音量(增加、减少或设置)
|
||
:param adjust_volumn_result: 包含音量调整指令的字符串,格式可以是 '+10'、'-10' 或 '=50'
|
||
"""
|
||
try:
|
||
print(f"收到的音量调整指令: {adjust_volumn_result}")
|
||
if "+" in adjust_volumn_result:
|
||
volume_change = int(re.search(r'\+(\d+)', adjust_volumn_result).group(1))
|
||
print(f"增加音量: {volume_change}%")
|
||
subprocess.run(["/usr/bin/amixer", "-D", "pulse", "sset", "Master", f"{volume_change}%+"])
|
||
elif "-" in adjust_volumn_result:
|
||
volume_change = int(re.search(r'-(\d+)', adjust_volumn_result).group(1))
|
||
print(f"减少音量: {volume_change}%")
|
||
subprocess.run(["/usr/bin/amixer", "-D", "pulse", "sset", "Master", f"{volume_change}%-"])
|
||
elif "=" in adjust_volumn_result:
|
||
volume_set = int(re.search(r'=(\d+)', adjust_volumn_result).group(1))
|
||
print(f"设置音量为: {volume_set}%")
|
||
subprocess.run(["/usr/bin/amixer", "-D", "pulse", "sset", "Master", f"{volume_set}%"])
|
||
else:
|
||
print("无效的音量指令!")
|
||
except Exception as e:
|
||
print(f"调整音量时出错: {e}")
|
||
|