High-performance Microsoft Edge TTS API Gateway
Built with Go · Gin · gorilla/websocket · Valkey
Available languages:
edge-tts is a Go API gateway that proxies Microsoft Edge's online TTS service. It ports the full WebSocket protocol from rany2/edge-tts — including Sec-MS-GEC token generation, SSML formatting, binary frame parsing, and real-time audio streaming.
Key features:
- 🎙 300+ Microsoft Neural voices across 100+ locales
- ⚡ Real-time streaming — bytes flushed as each WebSocket frame arrives
- 📝 SRT subtitle generation with word-level timestamps
- 🔄 Automatic clock skew correction on 403 responses
- 🗂 Voice list caching via Valkey (Redis-compatible)
- 📊 Prometheus metrics + structured logging
- 🛡 Valkey-backed per-IP rate limiting shared by every Kubernetes pod
- ⏱ Request timeout, body size limit, graceful drain, liveness/readiness probes
- 🌐 Proxy support (per-request or
HTTP_PROXYenv)
- Quick start
- Docker
- API
- Configuration
- Development
- Project structure
- Protocol notes
- Contributing
- License
git clone https://github.com/thangvv-tech/edge-tts.git
cd edge-tts
make runWithout
VALKEY_ADDRset, a warning is printed at startup and voice list caching is disabled. The service still works normally — voices are fetched from Microsoft on every request.
# Start with Valkey sidecar
make docker-up
# Stop
make docker-downdocker-compose.yml includes a Valkey service. The app waits for Valkey to be healthy before starting.
http://localhost:8080/swagger/index.html
http://localhost:8080/metrics
curl http://localhost:8080/health
# {"status":"ok"}Returns 300+ Microsoft Neural voices. All query params are optional and case-insensitive.
| Param | Example | Description |
|---|---|---|
locale |
en-US |
Exact locale match |
language |
en |
Language code (first segment of locale) |
gender |
Female |
Male or Female |
category |
General |
Content category from VoiceTag |
personality |
Friendly |
Voice personality from VoiceTag |
# All voices
curl http://localhost:8080/v1/voices | jq '.[0:3] | .[].ShortName'
# Vietnamese female voices
curl "http://localhost:8080/v1/voices?locale=vi-VN&gender=Female"
# English news voices
curl "http://localhost:8080/v1/voices?language=en&category=News"Results are normalized and deduplicated by ShortName, then cached in Valkey for 10 minutes.
Converts text to MP3 audio.
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
text |
string | ✓ | Text to synthesize | |
voice |
string | en-US-EmmaMultilingualNeural |
Voice ShortName from /v1/voices |
|
rate |
string | +0% |
Speed: +20%, -10%, etc. |
|
pitch |
string | +0Hz |
Pitch: +5Hz, -2Hz, etc. |
|
volume |
string | +0% |
Volume: +50%, -20%, etc. |
|
format |
string | audio-24khz-48kbitrate-mono-mp3 |
Output format | |
boundary |
string | SentenceBoundary |
WordBoundary or SentenceBoundary |
|
stream |
bool | false |
Flush MP3 chunks as they arrive | |
metadata |
bool | false |
Return NDJSON with boundary events + audio | |
proxy |
string | HTTP proxy URL, e.g. http://host:3128 |
Non-streaming (default) — full MP3 returned after synthesis completes:
curl -X POST http://localhost:8080/v1/synthesize \
-H "Content-Type: application/json" \
-d '{
"text": "Hello, this is a test.",
"voice": "en-US-EmmaMultilingualNeural"
}' \
-o output.mp3Streaming — bytes flushed per WebSocket frame:
curl -X POST http://localhost:8080/v1/synthesize \
-H "Content-Type: application/json" \
-d '{"text": "Hello world", "stream": true}' \
--no-buffer -o output.mp3Metadata mode — NDJSON stream with word boundary timestamps interleaved with audio:
curl -X POST http://localhost:8080/v1/synthesize \
-H "Content-Type: application/json" \
-d '{"text": "Hello world", "metadata": true, "boundary": "WordBoundary"}'{"type":"WordBoundary","offset":1750000,"duration":4250000,"text":"Hello"}
{"type":"audio","data":"<base64 mp3>"}
{"type":"WordBoundary","offset":6500000,"duration":3800000,"text":"world"}
{"type":"audio","data":"<base64 mp3>"}Synthesizes text and returns MP3 + SRT subtitles in a single NDJSON stream. Audio chunks are sent first; the final line contains the complete SRT file.
curl -X POST http://localhost:8080/v1/synthesize/srt \
-H "Content-Type: application/json" \
-d '{"text": "Hello world", "voice": "en-US-EmmaMultilingualNeural"}' \
| tee response.ndjson
# Extract SRT only
jq -r 'select(.type=="srt") | .data' response.ndjson > output.srt
# Extract audio only
jq -r 'select(.type=="audio") | .data' response.ndjson | base64 -d > output.mp3Response format:
{"type":"audio","data":"<base64 mp3>"}
{"type":"srt","data":"1\n00:00:00,175 --> 00:00:00,600\nHello\n\n2\n00:00:00,650 --> 00:00:00,950\nworld\n\n"}Prometheus metrics endpoint.
curl http://localhost:8080/metricsKey metrics:
| Metric | Description |
|---|---|
edge_tts_http_requests_total |
Total requests by method / path / status |
edge_tts_http_duration_seconds |
Request latency histogram |
edge_tts_synthesize_errors_total |
Synthesis error count |
edge_tts_voice_cache_hits_total |
Voice list served from Valkey |
edge_tts_voice_cache_misses_total |
Voice list fetched from Microsoft |
All configuration is via environment variables.
| Variable | Default | Description |
|---|---|---|
PORT |
8080 |
HTTP listen port |
VALKEY_ADDR |
(unset) | host:port for shared cache and rate limiting |
VALKEY_REQUIRED |
true in release |
Fail startup and return readiness 503 when Valkey is unavailable; use false only for local development |
TRUSTED_PROXIES |
(unset) | Comma-separated ingress/LB CIDRs. Keep unset unless a trusted proxy supplies client IP headers |
REQUEST_TIMEOUT |
60s |
Per-request synthesize timeout |
MAX_BODY_BYTES |
1048576 |
Max request body (1 MB) |
RATE_LIMIT |
10 |
Valkey token-bucket refill rate, per canonical client IP, shared across pods |
RATE_BURST |
20 |
Valkey token-bucket capacity per client IP |
MAX_CONCURRENT_WS |
20 |
Maximum Microsoft WebSocket sessions per pod |
MAX_GLOBAL_CONCURRENT_WS |
0 |
Shared Valkey lease ceiling across all pods; set a positive production limit |
GIN_MODE |
debug |
Set release for JSON structured logs and mandatory Valkey by default |
HTTP_PROXY |
(unset) | Proxy for all outbound connections (WS + HTTP) |
| Tool | Install |
|---|---|
| Go ≥ 1.22 | https://go.dev/dl |
| swag | go install github.com/swaggo/swag/cmd/swag@latest |
| golangci-lint | https://golangci-lint.run/usage/install/ |
| goimports | go install golang.org/x/tools/cmd/goimports@latest |
| Docker ≥ 24 | https://docs.docker.com/get-docker/ |
make swagger # regenerate docs/ after editing Swagger annotations
make test # run all tests with race detector + coverage report
make lint # golangci-lint
make fmt # gofmt + goimports
make build # compile binary
make clean # remove build artifactsedge-tts/
├── main.go # Entry point, graceful shutdown, slog setup
├── config.go # Config from env vars, Valkey init + startup warning
├── server.go # Gin router, middleware, all handlers
├── server_test.go # Handler integration tests (httptest)
├── cache/
│ └── cache.go # Valkey client (voice list, TTL 10 min)
├── tts/
│ ├── drm.go # Sec-MS-GEC token + clock skew auto-correction
│ ├── constants.go # WSS URL, voice list URL, request headers
│ ├── ssml.go # TTSConfig, Chunk types, SSML/config message builders
│ ├── splitter.go # Text splitting (byte limit, UTF-8, XML entity safe)
│ ├── srt.go # SubMaker, Subtitle, SRT composer
│ ├── errors.go # Typed errors: ErrNoAudioReceived, ErrWebSocket, etc.
│ ├── client.go # Stream(), Synthesize(), ListVoices(), proxy support
│ ├── drm_test.go
│ ├── ssml_test.go
│ ├── splitter_test.go
│ ├── srt_test.go
│ └── client_test.go
├── docs/ # Auto-generated by swag init
├── Dockerfile # Multi-stage: golang:1.25-alpine → alpine:3.21
├── docker-compose.yml # edge-tts + Valkey sidecar
├── Makefile
├── .golangci.yml
├── .editorconfig
├── .gitignore
└── .vscode/
├── settings.json
├── extensions.json
└── launch.json
| Concern | Detail |
|---|---|
| Sec-MS-GEC token | SHA256("{ticks rounded to 5 min}{TrustedClientToken}").upper() — Windows file time format |
| Binary frame layout | [2B big-endian header len][header bytes][audio payload] |
| Turn lifecycle | speech.config → ssml → binary audio frames → text turn.end |
| Connection scope | Microsoft closes every session at turn.end; one fresh WebSocket per text chunk is required |
| TLS optimization | Shared TLS session cache enables session resumption; WebSocket/TCP sessions are not pooled or reused |
| Capacity gates | Local semaphore limits each pod (MAX_CONCURRENT_WS); optional Valkey leases cap all pods (MAX_GLOBAL_CONCURRENT_WS) and honor cancellation |
| Text splitting | Splits at newline > space > UTF-8 boundary; never splits inside XML entities |
| Offset compensation | CBR: bytes × 8 × 10_000_000 / 48_000 ticks — exact, no drift |
| Clock skew | 403 → parse server Date header → atomically adjust skew → retry once |
| Proxy | Per-request proxy field → HTTP_PROXY/HTTPS_PROXY env (WS + HTTP) |
| Voice normalization | Duplicate Microsoft records are removed using ShortName as canonical identity |
| Distributed rate limit | Valkey atomic token bucket keyed by canonical client IP; 429 means limit exceeded, 503 means mandatory Valkey is unavailable |
| Client IP safety | TRUSTED_PROXIES controls whether forwarded client-IP headers are trusted; default is socket peer IP only |
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
- Fork the repository
- Create a feature branch (
git checkout -b feat/my-feature) - Commit your changes (
git commit -m 'feat: add my feature') - Push to the branch (
git push origin feat/my-feature) - Open a Pull Request
Please make sure tests pass before submitting:
make test
make lintMIT © thangvv