MassageRobot_Dobot/UI_next/tools/volume_control.py
2025-05-27 15:46:31 +08:00

66 lines
2.5 KiB
Python
Raw Permalink 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
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}")