Files
ai-speaker/audio.py
T
jmj 4ac2e959e0 ai-speaker MCP server 初始提交
- MCP Streamable HTTP (:8765 HTTP / :8766 HTTPS 自签)
- 工具:speak / play_url / play_file / download / stop / set_volume / list_voices / list_music / player_status / status
- 音量:上限 100,默认 30,夜间 22:00-08:30 静默压到 60
- CORS + Origin 白名单(局域网网段 + Android WebView 虚拟域)
- audio.py:PipeWire 蓝牙输出、JBL 绝对音量校验、播放状态/进度/设备信息
- tts.py:edge-tts 合成 + 缓存
- bt-play.sh:命令行播放工具
2026-11-30 02:20:37 +08:00

294 lines
11 KiB
Python

"""
音频播放层:负责找到输出设备、控制音量(带安全上限)、播放文件或 URL。
和 bt-play.sh 逻辑一致,但以 Python 实现,供 MCP server 调用。
"""
from __future__ import annotations
import hashlib
import logging
import os
import re
import shutil
import subprocess
import tempfile
import threading
import time
from pathlib import Path
from typing import Optional
log = logging.getLogger("ai-speaker.audio")
# ---------- 环境常量(与 pipewire-system.sh 一致) ----------
PIPEWIRE_RUNTIME_DIR = "/run/user/0"
DBUS_ADDR_FILE = Path("/run/pipewire-dbus-address")
# 音量安全:绝不允许超过此值(0-100),防止半夜被吓到
VOLUME_HARD_CAP = 100
DEFAULT_VOLUME = 30
# 夜间模式(22:00-08:30):上限静默压到此值,不向 MCP 调用方暴露
NIGHT_CAP = 60
def _env() -> dict[str, str]:
env = dict(os.environ)
env["PATH"] = env.get("PATH", "") + ":/usr/local/bin:/usr/sbin:/sbin:/bin"
env["PIPEWIRE_RUNTIME_DIR"] = PIPEWIRE_RUNTIME_DIR
addr = DBUS_ADDR_FILE.read_text().strip() if DBUS_ADDR_FILE.exists() else ""
if addr:
env["DBUS_SESSION_BUS_ADDRESS"] = addr
return env
def _run(cmd: list[str], timeout: float = 8, stdin=None, stdout=None, stderr=None):
return subprocess.run(cmd, env=_env(), timeout=timeout, stdin=stdin, stdout=stdout, stderr=stderr)
# ---------- 音量 ----------
def _effective_cap() -> int:
"""返回当前时刻的音量上限。夜间 22:00-08:30 强制压到 NIGHT_CAP,不向调用方暴露。"""
h = time.localtime().tm_hour + time.localtime().tm_min / 60.0
night = (h >= 22.0) or (h < 8.5)
return NIGHT_CAP if night else VOLUME_HARD_CAP
def clamp_volume(v: Optional[int]) -> int:
"""把请求音量限制在 [0, 当前时刻的上限]。None 用默认值。"""
cap = _effective_cap()
if v is None:
return min(DEFAULT_VOLUME, cap)
try:
v = int(v)
except (TypeError, ValueError):
return min(DEFAULT_VOLUME, cap)
return max(0, min(cap, v))
_sink_cache: dict[str, tuple[str, float]] = {} # keyword -> (node_id, ts)
def find_sink(keyword: str = "JBL", retries: int = 8) -> Optional[str]:
"""在 wpctl status 的 Sinks 段里按关键字找节点 ID。找不到返回 None。
优化:缓存 60 秒;命中时用 get-volume 校验节点仍存活。"""
now = time.time()
cached = _sink_cache.get(keyword)
if cached and now - cached[1] < 60 and _read_volume(cached[0]) is not None:
return cached[0]
for i in range(retries):
r = _run(["wpctl", "status"], timeout=6, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
text = re.sub(r"\x1b\[[0-9;]*m", "", r.stdout.decode(errors="ignore") if r.stdout else "")
in_sink = False
for line in text.splitlines():
if "Sinks:" in line:
in_sink = True
continue
if in_sink and re.match(r"^[ │]*[├└]─", line):
in_sink = False
if in_sink and keyword.lower() in line.lower():
m = re.search(r"(\d+)\.", line)
if m:
_sink_cache[keyword] = (m.group(1), now)
return m.group(1)
time.sleep(0.3) # 原来是 1 秒,缩短重试间隔
return None
def _read_volume(node: str) -> Optional[float]:
r = _run(["wpctl", "get-volume", node], timeout=5, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
m = re.search(r"([0-9.]+)", r.stdout.decode() if r.stdout else "")
return float(m.group(1)) if m else None
def device_info(node: str) -> dict:
"""从 pw-dump 读输出节点的设备信息:名称、蓝牙地址、编解码器、配置。"""
info = {"node": node, "name": None, "description": None, "address": None,
"codec": None, "profile": None, "transport": None, "volume": None}
try:
r = _run(["pw-dump", node], timeout=6, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
text = r.stdout.decode(errors="ignore") if r.stdout else ""
for key, field in [("node.name", "name"), ("node.description", "description"),
("api.bluez5.address", "address"), ("api.bluez5.codec", "codec"),
("api.bluez5.profile", "profile"), ("api.bluez5.transport", "transport")]:
m = re.search(rf'"{re.escape(key)}":\s*"([^"\n]+)"', text)
if m:
info[field] = m.group(1).strip()
info["volume"] = _read_volume(node)
except Exception:
pass
return info
def set_volume(node: str, vol_pct: int, verify_rounds: int = 3) -> float:
"""设置音量并验证。JBL 等绝对音量音箱会回传覆盖,需复读。返回最终音量(0-1)。
优化:已是目标值则直接返回,避免每次播放都白等 3 秒。"""
target = vol_pct / 100.0
cur = _read_volume(node)
if cur is not None and abs(cur - target) < 0.02:
return cur
time.sleep(0.4) # 若上一次设置刚发生,等 JBL 的 AVRCP 回传先稳定,避免被覆盖
for i in range(verify_rounds):
_run(["wpctl", "set-mute", node, "0"], timeout=5)
_run(["wpctl", "set-volume", node, f"{target:.4f}"], timeout=5)
time.sleep(0.5 if i == 0 else 0.9)
cur = _read_volume(node)
if cur is not None and abs(cur - target) < 0.02:
break
return cur if cur is not None else target
# ---------- 蓝牙连接 ----------
def ensure_bluetooth(mac: str = "43:5A:DC:68:1B:F8") -> bool:
r = _run(["bluetoothctl", "info", mac], timeout=6, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
if r.stdout and b"Connected: yes" in r.stdout:
return True
log.info("蓝牙未连接,尝试连接 %s", mac)
_run(["bluetoothctl", "connect", mac], timeout=30, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
time.sleep(3)
r = _run(["bluetoothctl", "info", mac], timeout=6, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
return bool(r.stdout and b"Connected: yes" in r.stdout)
# ---------- 播放 ----------
_play_lock = threading.Lock()
_current: Optional[subprocess.Popen] = None
_current_lock = threading.Lock()
# 播放状态跟踪(供 player_status 查询)
_now: dict = {"playing": False, "source": None, "started_at": None, "title": None, "duration": None}
def _probe_duration(src: str) -> Optional[float]:
"""用 ffprobe 读音频总时长(秒),读不到返回 None。"""
try:
r = _run(["ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "csv=p=0", src], timeout=8,
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
return float(r.stdout.decode().strip().splitlines()[0]) if r.stdout else None
except Exception:
return None
def player_state() -> dict:
"""返回当前播放状态,含进度。"""
with _current_lock:
p = _current
playing = bool(p and p.poll() is None)
st = dict(_now)
st["playing"] = playing
if playing and st.get("started_at"):
elapsed = max(0.0, time.time() - st["started_at"])
st["elapsed_sec"] = round(elapsed, 1)
if st.get("duration"):
st["progress_pct"] = round(min(100.0, elapsed / st["duration"] * 100), 1)
st["remaining_sec"] = round(max(0.0, st["duration"] - elapsed), 1)
else:
st["progress_pct"] = None
st["remaining_sec"] = None
else:
st["elapsed_sec"] = None
st["progress_pct"] = None
st["remaining_sec"] = None
st["playing"] = False
return st
def stop() -> bool:
"""停止当前播放。"""
with _current_lock:
p = _current
if p and p.poll() is None:
try:
p.terminate()
p.wait(timeout=3)
except Exception:
p.kill()
return True
return False
def play(src: str, node: str, vol_pct: Optional[int] = None, blk: bool = True, timeout: float = 600.0) -> dict:
"""
播放文件或 URL(ffmpeg 能解的任何东西,含 http/https 流)。
返回 {"ok", "node", "volume", "seconds"}。
"""
global _current
vol = clamp_volume(vol_pct)
if not _play_lock.acquire(blocking=False):
stop()
time.sleep(0.5)
if not _play_lock.acquire(timeout=5):
return {"ok": False, "error": "另一个播放正在进行"}
try:
final_vol = set_volume(node, vol)
# 安全检查:最终音量不能超过请求值太多
if final_vol > vol / 100.0 + 0.05:
return {"ok": False, "error": f"音量校验失败: 请求 {vol}%, 实际 {final_vol:.2f}"}
t0 = time.time()
dec = subprocess.Popen(
["ffmpeg", "-v", "error", "-i", src, "-f", "wav", "-ac", "2", "-ar", "44100", "-"],
env=_env(), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
)
pw = subprocess.Popen(
["pw-cat", "--playback", "-", "--target", node],
env=_env(), stdin=dec.stdout, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
dec.stdout.close()
title = None
if src.startswith("http"):
title = src.split("?")[0].rstrip("/").split("/")[-1] or src
else:
title = os.path.basename(src) or src
_now.update({"source": src, "started_at": time.time(), "title": title,
"duration": _probe_duration(src)})
with _current_lock:
_current = pw # global:让 stop() 能找到并终止它
try:
rc = pw.wait(timeout=timeout)
except subprocess.TimeoutExpired:
pw.kill()
rc = -9
finally:
if dec.poll() is None:
dec.kill()
dec.stderr.close()
with _current_lock:
_current = None
_now["playing"] = False
err = ""
if rc != 0:
try:
err = dec.stderr.read().decode(errors="ignore").strip().splitlines()[-1:] or [""]
err = err[0][:200]
except Exception:
err = ""
return {
"ok": rc == 0,
"node": node,
"volume": final_vol,
"seconds": round(time.time() - t0, 2),
**({"error": err} if err else {}),
}
finally:
_play_lock.release()
# ---------- 下载 ----------
def download(url: str, save_dir: str = "/vol1/1000/Music", timeout: float = 600.0) -> dict:
"""用 ffmpeg 下载 URL 到 NAS 目录。返回 {"ok","path","bytes"}。"""
Path(save_dir).mkdir(parents=True, exist_ok=True)
# 从 URL 猜扩展名,猜不到就 .mp3
ext = Path(url.split("?")[0]).suffix.lower()
if ext not in {".mp3", ".m4a", ".flac", ".wav", ".ogg", ".opus", ".aac", ".m4b", ".wma", ".ape"}:
ext = ".mp3"
name = Path(url.split("?")[0]).stem[:60] or "audio"
name = re.sub(r"[\\/:*?\"<>|]", "_", name)
dst = Path(save_dir) / f"{name}{ext}"
if dst.exists():
dst = dst.with_name(f"{name}-{int(time.time())}{ext}")
r = _run(["ffmpeg", "-v", "error", "-y", "-i", url, "-c", "copy", str(dst)], timeout=timeout,
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
if r.returncode != 0:
dst.unlink(missing_ok=True)
err = (r.stderr or b"").decode(errors="ignore").strip().splitlines()[-1:] or ["unknown"]
return {"ok": False, "error": err[0][:200]}
return {"ok": True, "path": str(dst), "bytes": dst.stat().st_size}