| name | trtc-speech |
| description | Step-by-step guide for integrating TRTC Speech API (ASR/TTS) into any project. Covers credential setup, SDK installation, and three recognition modes (Realtime WebSocket, Sentence HTTP, File Async). Use when a user wants to add speech recognition, transcription, or text-to-speech to their application. |
TRTC Speech API — Integration Guide
Use this skill when the user wants to integrate speech recognition (ASR) or text-to-speech (TTS) from TRTC into their project.
Step 1: Confirm Prerequisites
Before writing any code, ensure the user has these three credentials:
Ask the user: "Do you have your TRTC APPID, SDKAppID, and SecretKey? If not, follow the Getting Started guide at your TRTC console."
Store credentials as environment variables, NEVER hardcode:
TRTC_APPID=13xxxxxxxx
TRTC_SDK_APPID=14xxxxxxxx
TRTC_SECRET_KEY=your-secret-key
Step 2: Choose Recognition Mode
Ask the user which mode they need:
| Mode | Best For | Protocol | Latency |
|---|
| Realtime ASR | Live audio, voice chat, live subtitles | WebSocket | ~200ms |
| Sentence ASR | Short clips ≤60s, voice commands | HTTP POST | ~1s |
| File ASR | Long recordings ≤12h, meeting transcription | Async HTTP | Minutes |
Step 3: Install SDK
Based on the user's language:
Go
go get github.com/hydah/trtc-asr-sdk-go@latest
Requires: Go 1.21+
Python
pip install trtc-asr
Requires: Python 3.8+
Node.js
npm install trtc-asr-sdk
Requires: Node.js 16+
Step 4: Implement
Realtime ASR (WebSocket)
Go:
package main
import (
"io"
"log"
"os"
"time"
"github.com/hydah/trtc-asr-sdk-go/asr"
"github.com/hydah/trtc-asr-sdk-go/common"
)
type MyListener struct{}
func (l *MyListener) OnRecognitionStart(resp *asr.SpeechRecognitionResponse) {
log.Printf("Started, voice_id: %s", resp.VoiceID)
}
func (l *MyListener) OnSentenceBegin(resp *asr.SpeechRecognitionResponse) {}
func (l *MyListener) OnRecognitionResultChange(resp *asr.SpeechRecognitionResponse) {
log.Printf("Interim: %s", resp.Result.VoiceTextStr)
}
func (l *MyListener) OnSentenceEnd(resp *asr.SpeechRecognitionResponse) {
log.Printf("Final: %s", resp.Result.VoiceTextStr)
}
func (l *MyListener) OnRecognitionComplete(resp *asr.SpeechRecognitionResponse) {
log.Printf("Complete")
}
func (l *MyListener) OnFail(resp *asr.SpeechRecognitionResponse, err error) {
log.Printf("Error: %v", err)
}
func main() {
credential := common.NewCredential(
os.Getenv("TRTC_APPID"),
os.Getenv("TRTC_SDK_APPID"),
os.Getenv("TRTC_SECRET_KEY"),
)
recognizer := asr.NewSpeechRecognizer(credential, "16k_zh_en", &MyListener{})
recognizer.SetVadSilenceTime(500)
if err := recognizer.Start(); err != nil {
log.Fatal(err)
}
defer recognizer.Stop()
file, _ := os.Open("audio.pcm")
defer file.Close()
buf := make([]byte, 6400)
for {
n, err := file.Read(buf)
if err == io.EOF { break }
recognizer.Write(buf[:n])
time.Sleep(200 * time.Millisecond)
}
}
Python:
import os, time
from trtc_asr import SpeechRecognizer, Credential
credential = Credential(
int(os.environ["TRTC_APPID"]),
int(os.environ["TRTC_SDK_APPID"]),
os.environ["TRTC_SECRET_KEY"],
)
recognizer = SpeechRecognizer(credential, "16k_zh_en")
recognizer.set_vad_silence_time(500)
@recognizer.on("sentence_end")
def on_sentence_end(result):
print(f"Final: {result.text}")
recognizer.start()
with open("audio.pcm", "rb") as f:
while chunk := f.read(6400):
recognizer.write(chunk)
time.sleep(0.2)
recognizer.stop()
Node.js:
const { SpeechRecognizer, Credential } = require('trtc-asr-sdk');
const fs = require('fs');
const credential = new Credential(
parseInt(process.env.TRTC_APPID),
parseInt(process.env.TRTC_SDK_APPID),
process.env.TRTC_SECRET_KEY,
);
const recognizer = new SpeechRecognizer(credential, '16k_zh_en');
recognizer.setVadSilenceTime(500);
recognizer.on('sentenceEnd', (result) => {
console.log('Final:', result.text);
});
await recognizer.start();
const stream = fs.createReadStream('audio.pcm', { highWaterMark: 6400 });
for await (const chunk of stream) {
recognizer.write(chunk);
await new Promise(r => setTimeout(r, 200));
}
await recognizer.stop();
Sentence ASR (HTTP — short audio ≤60s)
Go:
credential := common.NewCredential(appid, sdkAppId, secretKey)
recognizer := asr.NewSentenceRecognizer(credential)
data, _ := os.ReadFile("audio.wav")
result, err := recognizer.RecognizeData(data, "wav", "16k_zh_en")
fmt.Printf("Text: %s\nDuration: %d ms\n", result.Result, result.AudioDuration)
result, err := recognizer.RecognizeURL("https://example.com/audio.wav", "wav", "16k_zh_en")
File ASR (Async — long audio ≤12h)
Go:
credential := common.NewCredential(appid, sdkAppId, secretKey)
recognizer := asr.NewFileRecognizer(credential)
taskID, err := recognizer.CreateTaskFromURL("https://example.com/meeting.mp3", "16k_zh_en")
status, err := recognizer.WaitForResult(taskID)
fmt.Printf("Text: %s\nDuration: %.1f s\n", status.Result, status.AudioDuration)
for _, s := range status.ResultDetail {
fmt.Printf("[%d-%d ms] %s\n", s.StartMs, s.EndMs, s.FinalSentence)
}
Step 5: Verify
After implementation, verify:
- Credentials load from environment variables (not hardcoded)
- Error handling covers: auth failure, network timeout, quota exceeded
- Audio format matches the engine requirement (PCM 16kHz 16-bit mono for realtime)
- Resources are properly released (recognizer.Stop() / recognizer.stop())
API Reference
- Realtime endpoint:
wss://asr.cloud-rtc.com/asr/v2/{APPID}?engine_model_type=16k_zh_en&voice_id={UUID}&...
- Sentence endpoint:
POST https://asr.cloud-rtc.com/v1/SentenceRecognition
- File create task:
POST https://asr.cloud-rtc.com/v1/CreateRecTask
- File poll result:
POST https://asr.cloud-rtc.com/v1/DescribeTaskStatus
Engine Models
| Model | Description |
|---|
16k_zh | Chinese (recommended) |
16k_zh_en | Chinese + English |
16k_en | English |
8k_zh | Chinese (telephone, 8kHz) |
Auth Headers
| Header | Value |
|---|
X-TRTC-SdkAppId | Your SDKAppID |
X-TRTC-UserSig | Generated from SecretKey (SDK handles this automatically) |
Links