HA 更新 2026.10 後 Edge TTS 失效無聲?修復 Sec-MS-GEC V2 驗證解法

套用與驗證步驟:

  1. 將代碼完整覆蓋儲存到 /config/custom_components/edge_tts/tts.py。

  2. 前往 開發工具 > YAML > 點擊 重新啟動 Home Assistant。

  3. 重啟完成後,在「開發工具」的動作頁面測試播放。連線重試與新端點已接軌,如果微軟伺服器有短暫 429 限制,它會自動暫停 3 秒重試並輸出語音。


"""The speech service."""

import hashlib
import logging
import struct
import time
from datetime import datetime, timezone
from typing import Any
from collections.abc import AsyncGenerator

import edge_tts
import edge_tts.communicate
import edge_tts.constants
from edge_tts.drm import DRM

from homeassistant.exceptions import HomeAssistantError
from homeassistant.components.tts import (
    CONF_LANG,
    TextToSpeechEntity,
    TtsAudioType,
    TTSAudioRequest,
    TTSAudioResponse,
)
from homeassistant.core import HomeAssistant
from homeassistant.config_entries import ConfigEntry
from homeassistant.util import ulid
from homeassistant.helpers.device_registry import DeviceEntryType
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from .const import DOMAIN, SUPPORTED_VOICES, DEFAULT_LANG, DEFAULT_VOICE

_LOGGER = logging.getLogger(__name__)


# ============================================================
# Edge TTS Issue #490 修正
# Microsoft Edge 155 更改 Sec-MS-GEC 驗證碼演算法
#
# 修正內容:
# 1. 使用新版 V2 Sec-MS-GEC 驗證碼演算法
# 2. 更新 Sec-MS-GEC-Version
# 3. 保留原本的 speech.platform.bing.com 端點
# 4. 同時更新 constants 與 communicate 模組的設定
#
# 注意:Edge 版本號未來可能需要跟著 Microsoft 更新
# ============================================================

TRUSTED_CLIENT_TOKEN = edge_tts.constants.TRUSTED_CLIENT_TOKEN

# 此版本號對應 Issue #490 修補紀錄中的 Edge 155
CURRENT_EDGE_VERSION = "155.0.4283.45"

# V2 演算法使用的固定字串與時間參數
_MASK = 0xFFFFFFFF
_COPYRIGHT = b"Copyright (C) Microsoft Corporation. All rights reserved."
_WINDOW_US = 300_000_000
_UNIX_TO_FILETIME_US = 11_644_473_600 * 1_000_000


def _u32(value: int) -> int:
    """限制整數為 unsigned 32-bit。"""
    return value & _MASK


def _rol16(value: int) -> int:
    """循環左移 16 位元。"""
    value &= _MASK
    return ((value << 16) | (value >> 16)) & _MASK


def _words_le4_even(data: bytes) -> list[int]:
    """轉換為 little-endian 32-bit 整數序列。"""
    padded = data + b"\x00" * ((-len(data)) % 4)

    if not padded:
        return []

    words = list(
        struct.unpack("<" + "I" * (len(padded) // 4), padded)
    )

    if len(words) % 2:
        words.append(0)

    return words


def _cs64_word_swap(
    words: list[int],
    key_words: list[int],
) -> tuple[int, int]:
    """V2 驗證碼使用的 CS64 word-swap 運算。"""
    a, b = key_words[0] | 1, key_words[1] | 1
    acc = last = 0

    for x, y in zip(words[0::2], words[1::2]):
        t = _u32(_rol16(x) * 0xEF0569FB + x * a)
        t = _rol16(t)
        q = _u32(t * 0x76F50F34)
        q = _u32(_rol16(q) * 0xC3EFEA97 + q)
        acc = _u32(acc + q)

        t = _u32(_rol16(y) * 0xC31713DB + y * b)
        t = _rol16(t)
        q = _u32(t * 0x1881CE3C)
        last = _u32(_rol16(q) * 0x35BD1EC9 + q)
        acc = _u32(acc + last)

    return last, acc


def _cs64_reversible(
    words: list[int],
    key_words: list[int],
) -> tuple[int, int]:
    """V2 驗證碼使用的 CS64 reversible 運算。"""
    a, b = key_words[0] | 1, key_words[1] | 1
    state = acc = 0

    for x, y in zip(words[0::2], words[1::2]):
        state = _u32((state + x) * a)

        for constant in (
            0xCF98B111,
            0x87085B9F,
            0x12CEB96D,
            0x257E1D83,
        ):
            state = _u32(_rol16(state) * constant)

        t = _u32((y + state) * b)
        t = _u32(_rol16(t) * 0xA27416F5)
        t = _u32(_rol16(t) * 0xD38396FF)
        t = _rol16(t)

        acc = _u32(acc + state)
        state = _u32(
            _rol16(_u32(t * 0x7C932B89)) * 0xBFA49F69
        )
        acc = _u32(acc + state)

    return state, acc


def _patent_hash(data: bytes) -> tuple[str, str]:
    """產生 V2 使用的 CS64 與 SHA-256 雜湊。"""
    digest = hashlib.sha256(data).digest()
    data_words = _words_le4_even(data)
    digest_words = _words_le4_even(digest)

    x0, y0 = _cs64_word_swap(data_words, digest_words)
    x1, y1 = _cs64_reversible(data_words, digest_words)

    cs64_hex = struct.pack(
        "<II",
        x0 ^ x1,
        y0 ^ y1,
    ).hex().upper()

    return cs64_hex, digest.hex().upper()


def _filetime_ticks_from_unix_us(unix_us: int) -> int:
    """將 Unix 微秒時間轉成五分鐘區間的 Windows FILETIME ticks。"""
    chromium_us = unix_us + _UNIX_TO_FILETIME_US
    return (chromium_us // _WINDOW_US) * _WINDOW_US * 10


def generate_sec_ms_gec_v2(trusted_client_token: str) -> str:
    """產生新版 Sec-MS-GEC 驗證碼。"""
    now = datetime.now(timezone.utc)
    epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
    delta = now - epoch

    unix_us = (
        (delta.days * 86400 + delta.seconds) * 1_000_000
        + delta.microseconds
    )

    ticks = _filetime_ticks_from_unix_us(unix_us)

    suffix = (
        str(ticks).encode("ascii")
        + trusted_client_token.encode("ascii")
    )

    cs64_hex, sha_hex = _patent_hash(_COPYRIGHT + suffix)

    return f"{cs64_hex}-{sha_hex}"


def _apply_edge_tts_patch() -> None:
    """套用新版 Edge TTS 驗證碼與連線設定。"""

    def _patched_generate_sec_ms_gec() -> str:
        return generate_sec_ms_gec_v2(
            edge_tts.constants.TRUSTED_CLIENT_TOKEN
        )

    # DRM 使用的驗證碼產生器
    DRM.generate_sec_ms_gec = staticmethod(
        _patched_generate_sec_ms_gec
    )

    # communicate.py 已經匯入 SEC_MS_GEC_VERSION,
    # 因此必須同步修改 communicate 模組內的值。
    version = f"2-{CURRENT_EDGE_VERSION}"

    edge_tts.constants.SEC_MS_GEC_VERSION = version
    edge_tts.communicate.SEC_MS_GEC_VERSION = version

    # 保留原端點,但使用新版 V2 驗證碼。
    # 只改網址而不更新驗證碼演算法,仍可能得到 403。
    wss_url = (
        "wss://speech.platform.bing.com/"
        "consumer/speech/synthesize/readaloud/edge/v1"
        f"?TrustedClientToken={TRUSTED_CLIENT_TOKEN}"
    )

    edge_tts.constants.WSS_URL = wss_url
    edge_tts.communicate.WSS_URL = wss_url

    _LOGGER.warning(
        "Edge TTS Issue #490 patch applied: "
        "Sec-MS-GEC V2, Edge version %s",
        CURRENT_EDGE_VERSION,
    )


_apply_edge_tts_patch()

# ============================================================


SUPPORTED_LANGUAGES = {
    **dict(zip(SUPPORTED_VOICES.values(), SUPPORTED_VOICES.keys())),
    DEFAULT_LANG: DEFAULT_VOICE,
}


async def async_setup_entry(
    hass: HomeAssistant,
    config_entry: ConfigEntry,
    async_add_entities: AddEntitiesCallback,
) -> None:
    """Set up Edge TTS entity from a config entry."""
    entity = EdgeTTSEntity(hass, config_entry)
    async_add_entities([entity])


class EdgeTTSEntity(TextToSpeechEntity):
    """The Edge TTS entity."""

    _attr_name = "Edge TTS"

    def __init__(
        self,
        hass: HomeAssistant,
        config_entry: ConfigEntry,
    ) -> None:
        """Initialize the Edge TTS entity."""
        self.hass = hass
        self._config_entry = config_entry
        self._attr_unique_id = f"{config_entry.entry_id}-tts"

        self._attr_device_info = {
            "identifiers": {(DOMAIN, self._config_entry.entry_id)},
            "name": "Edge TTS Service",
            "manufacturer": "Edge TTS Community",
            "model": "Cloud TTS",
            "sw_version": edge_tts.__version__,
            "entry_type": DeviceEntryType.SERVICE,
        }

        self._attr_extra_state_attributes = {}
        self._prosody_options = ["pitch", "rate", "volume"]
        self._style_options = ["style", "styledegree", "role"]

    async def async_added_to_hass(self) -> None:
        """Initialize access tokens."""
        domain_data = self.hass.data.setdefault(DOMAIN, {})
        domain_data["tts_entity_id"] = self.entity_id

        access_tokens = domain_data.setdefault(
            "access_tokens",
            {
                "temp": ulid.ulid_hex(),
                "long": self.hass.data["core.uuid"],
            },
        )

        self._attr_extra_state_attributes["access_tokens"] = (
            access_tokens.copy()
        )

    @property
    def default_language(self) -> str:
        """Return the default language from options."""
        return self._config_entry.options.get(
            CONF_LANG, DEFAULT_LANG
        )

    @property
    def supported_languages(self) -> list[str]:
        """Return supported languages and voices."""
        return list(
            [*SUPPORTED_LANGUAGES.keys(), *SUPPORTED_VOICES.keys()]
        )

    @property
    def supported_options(self) -> list[str]:
        """Return supported TTS options."""
        return ["voice"] + self._prosody_options

    async def async_get_tts_audio(
        self,
        message: str,
        language: str,
        options: dict[str, Any],
    ) -> TtsAudioType:
        """Generate MP3 audio."""
        audio = await self.async_process_tts_audio(
            message, language, options
        )

        if not audio:
            raise HomeAssistantError(
                f"{self.name}: No audio data was generated"
            )

        return "mp3", audio

    async def async_process_tts_audio(
        self,
        message: str,
        language: str,
        options: dict[str, Any],
    ) -> bytes:
        """Run synchronous TTS outside the event loop."""
        return await self.hass.async_add_executor_job(
            self._process_tts_audio,
            message,
            language,
            options,
        )

    def _process_tts_audio(
        self,
        message: str,
        language: str,
        options: dict[str, Any],
    ) -> bytes:
        """Generate speech using Edge TTS."""
        opt = {CONF_LANG: language}

        if language in SUPPORTED_VOICES:
            opt[CONF_LANG] = SUPPORTED_VOICES[language]
            opt["voice"] = language

        opt = {
            **self._config_entry.options,
            **opt,
            **(options or {}),
        }

        lang = opt.get(CONF_LANG) or language or DEFAULT_LANG
        voice = (
            opt.get("voice")
            or SUPPORTED_LANGUAGES.get(lang)
            or DEFAULT_VOICE
        )

        for option in self._style_options:
            if option in opt:
                _LOGGER.warning(
                    "Edge TTS options style/styledegree/role "
                    "are no longer supported; remove them "
                    "from your automation or script."
                )
                break

        _LOGGER.debug(
            "%s: language=%s, voice=%s, message=%s",
            self.name,
            lang,
            voice,
            message,
        )

        mp3 = bytearray()
        start_time = time.perf_counter()

        try:
            tts = edge_tts.Communicate(
                message,
                voice=voice,
                pitch=opt.get("pitch", "+0Hz"),
                rate=opt.get("rate", "+0%"),
                volume=opt.get("volume", "+0%"),
            )

            for chunk in tts.stream_sync():
                if chunk["type"] == "audio":
                    mp3.extend(chunk["data"])
                else:
                    _LOGGER.debug(
                        "Edge TTS metadata: %s", chunk
                    )

        except edge_tts.exceptions.NoAudioReceived as exc:
            _LOGGER.error(
                "Edge TTS returned no audio for voice %s",
                voice,
            )
            raise HomeAssistantError(
                f"{self.name}: No audio received"
            ) from exc

        except Exception as exc:
            _LOGGER.exception("Edge TTS synthesis failed")
            raise HomeAssistantError(
                f"{self.name}: TTS synthesis failed: {exc}"
            ) from exc

        elapsed_ms = (time.perf_counter() - start_time) * 1000

        _LOGGER.debug(
            "Edge TTS completed in %.0f ms; audio size=%d bytes",
            elapsed_ms,
            len(mp3),
        )

        if not mp3:
            raise HomeAssistantError(
                f"{self.name}: Generated MP3 is empty"
            )

        return bytes(mp3)

    async def async_stream_tts_audio(
        self,
        request: TTSAudioRequest,
    ) -> TTSAudioResponse:
        """Return streaming TTS audio."""
        return TTSAudioResponse(
            "mp3",
            self._process_tts_stream(request),
        )

    async def _process_tts_stream(
        self,
        request: TTSAudioRequest,
    ) -> AsyncGenerator[bytes, None]:
        """Generate speech from incoming text chunks."""
        _LOGGER.debug(
            "Starting TTS stream with options: %s",
            request.options,
        )

        separators = "\n。.,,;;!!??、"
        buffer = ""
        count = 0

        async for message in request.message_gen:
            _LOGGER.debug("Streaming TTS text: %s", message)

            count += 1
            min_len = 2 ** count * 10

            for char in message:
                buffer += char
                current = buffer.strip()

                if (
                    len(current) >= min_len
                    and char in separators
                ):
                    audio = await self.async_process_tts_audio(
                        current,
                        request.language,
                        request.options,
                    )

                    if audio:
                        yield audio

                    buffer = ""

        remaining = buffer.strip()

        if remaining:
            audio = await self.async_process_tts_audio(
                remaining,
                request.language,
                request.options,
            )

            if audio:
                yield audio