telnyx-webrtc-client-js

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Telnyx WebRTC - JavaScript SDK

Telnyx WebRTC - JavaScript SDK

Build real-time voice communication into browser applications.
Prerequisites: Create WebRTC credentials and generate a login token using the Telnyx server-side SDK. See the
telnyx-webrtc-*
skill in your server language plugin (e.g.,
telnyx-python
,
telnyx-javascript
).
在浏览器应用中构建实时语音通信功能。
前提条件:使用Telnyx服务端SDK创建WebRTC凭证并生成登录令牌。请查看您所用服务端语言插件中的
telnyx-webrtc-*
技能(例如
telnyx-python
telnyx-javascript
)。

Installation

安装

bash
npm install @telnyx/webrtc --save
Import the client:
js
import { TelnyxRTC } from '@telnyx/webrtc';

bash
npm install @telnyx/webrtc --save
导入客户端:
js
import { TelnyxRTC } from '@telnyx/webrtc';

Authentication

身份验证

Option 1: Token-Based (Recommended)

选项1:基于令牌(推荐)

js
const client = new TelnyxRTC({
  login_token: 'your_jwt_token',
});

client.connect();
js
const client = new TelnyxRTC({
  login_token: 'your_jwt_token',
});

client.connect();

Option 2: Credential-Based

选项2:基于凭证

js
const client = new TelnyxRTC({
  login: 'sip_username',
  password: 'sip_password',
});

client.connect();
Important: Never hardcode credentials in frontend code. Use environment variables or prompt users.
js
const client = new TelnyxRTC({
  login: 'sip_username',
  password: 'sip_password',
});

client.connect();
重要提示:切勿在前端代码中硬编码凭证。请使用环境变量或提示用户输入。

Disconnect

断开连接

js
// When done, disconnect and remove listeners
client.disconnect();
client.off('telnyx.ready');
client.off('telnyx.notification');

js
// 使用完毕后,断开连接并移除监听器
client.disconnect();
client.off('telnyx.ready');
client.off('telnyx.notification');

Media Elements

媒体元素

Specify an HTML element to play remote audio:
js
client.remoteElement = 'remoteMedia';
HTML:
html
<audio id="remoteMedia" autoplay="true" />

指定用于播放远程音频的HTML元素:
js
client.remoteElement = 'remoteMedia';
HTML代码:
html
<audio id="remoteMedia" autoplay="true" />

Events

事件

js
let activeCall;

client
  .on('telnyx.ready', () => {
    console.log('Ready to make calls');
  })
  .on('telnyx.error', (error) => {
    console.error('Error:', error);
  })
  .on('telnyx.notification', (notification) => {
    if (notification.type === 'callUpdate') {
      activeCall = notification.call;
      
      // Handle incoming call
      if (activeCall.state === 'ringing') {
        // Show incoming call UI
        // Call activeCall.answer() to accept
      }
    }
  });
js
let activeCall;

client
  .on('telnyx.ready', () => {
    console.log('已准备好发起通话');
  })
  .on('telnyx.error', (error) => {
    console.error('错误:', error);
  })
  .on('telnyx.notification', (notification) => {
    if (notification.type === 'callUpdate') {
      activeCall = notification.call;
      
      // 处理来电
      if (activeCall.state === 'ringing') {
        // 显示来电UI
        // 调用activeCall.answer()接听
      }
    }
  });

Event Types

事件类型

EventDescription
telnyx.ready
Client connected and ready
telnyx.error
Error occurred
telnyx.notification
Call updates, incoming calls
telnyx.stats.frame
In-call quality metrics (when debug enabled)

事件描述
telnyx.ready
客户端已连接并准备就绪
telnyx.error
发生错误
telnyx.notification
通话更新、来电通知
telnyx.stats.frame
通话中质量指标(启用调试时)

Making Calls

发起通话

js
const call = client.newCall({
  destinationNumber: '+18004377950',
  callerNumber: '+15551234567',
});

js
const call = client.newCall({
  destinationNumber: '+18004377950',
  callerNumber: '+15551234567',
});

Receiving Calls

接听通话

js
client.on('telnyx.notification', (notification) => {
  const call = notification.call;
  
  if (notification.type === 'callUpdate' && call.state === 'ringing') {
    // Incoming call - show UI and answer
    call.answer();
  }
});

js
client.on('telnyx.notification', (notification) => {
  const call = notification.call;
  
  if (notification.type === 'callUpdate' && call.state === 'ringing') {
    // 来电 - 显示UI并接听
    call.answer();
  }
});

Call Controls

通话控制

js
// End call
call.hangup();

// Send DTMF tones
call.dtmf('1234');

// Mute audio
call.muteAudio();
call.unmuteAudio();

// Hold
call.hold();
call.unhold();

js
// 结束通话
call.hangup();

// 发送DTMF音调
call.dtmf('1234');

// 静音
call.muteAudio();
call.unmuteAudio();

// 保持通话
call.hold();
call.unhold();

Debugging & Call Quality

调试与通话质量

Enable Debug Logging

启用调试日志

js
const call = client.newCall({
  destinationNumber: '+18004377950',
  debug: true,
  debugOutput: 'socket',  // 'socket' (send to Telnyx) or 'file' (save locally)
});
js
const call = client.newCall({
  destinationNumber: '+18004377950',
  debug: true,
  debugOutput: 'socket',  // 'socket'(发送至Telnyx)或 'file'(本地保存)
});

In-Call Quality Metrics

通话中质量指标

js
const call = client.newCall({
  destinationNumber: '+18004377950',
  debug: true,  // Required for metrics
});

client.on('telnyx.stats.frame', (stats) => {
  console.log('Quality stats:', stats);
  // Contains jitter, RTT, packet loss, etc.
});

js
const call = client.newCall({
  destinationNumber: '+18004377950',
  debug: true,  // 获取指标需启用此项
});

client.on('telnyx.stats.frame', (stats) => {
  console.log('质量统计:', stats);
  // 包含抖动、RTT、丢包率等数据
});

Pre-Call Diagnosis

通话前诊断

Test connectivity before making calls:
js
import { PreCallDiagnosis } from '@telnyx/webrtc';

PreCallDiagnosis.run({
  credentials: {
    login: 'sip_username',
    password: 'sip_password',
    // or: loginToken: 'jwt_token'
  },
  texMLApplicationNumber: '+12407758982',
})
  .then((report) => {
    console.log('Diagnosis report:', report);
  })
  .catch((error) => {
    console.error('Diagnosis failed:', error);
  });

发起通话前测试连接性:
js
import { PreCallDiagnosis } from '@telnyx/webrtc';

PreCallDiagnosis.run({
  credentials: {
    login: 'sip_username',
    password: 'sip_password',
    // 或: loginToken: 'jwt_token'
  },
  texMLApplicationNumber: '+12407758982',
})
  .then((report) => {
    console.log('诊断报告:', report);
  })
  .catch((error) => {
    console.error('诊断失败:', error);
  });

Preferred Codecs

首选编解码器

Set codec preference for calls:
js
const allCodecs = RTCRtpReceiver.getCapabilities('audio').codecs;

// Prefer Opus for AI/high quality
const opusCodec = allCodecs.find(c => 
  c.mimeType.toLowerCase().includes('opus')
);

// Or PCMA for telephony compatibility
const pcmaCodec = allCodecs.find(c => 
  c.mimeType.toLowerCase().includes('pcma')
);

client.newCall({
  destinationNumber: '+18004377950',
  preferred_codecs: [opusCodec],
});

设置通话的编解码器偏好:
js
const allCodecs = RTCRtpReceiver.getCapabilities('audio').codecs;

// 优先选择Opus以适配AI/高质量需求
const opusCodec = allCodecs.find(c => 
  c.mimeType.toLowerCase().includes('opus')
);

// 或选择PCMA以适配电话系统兼容性
const pcmaCodec = allCodecs.find(c => 
  c.mimeType.toLowerCase().includes('pcma')
);

client.newCall({
  destinationNumber: '+18004377950',
  preferred_codecs: [opusCodec],
});

Registration State

注册状态

Check if client is registered:
js
const isRegistered = await client.getIsRegistered();
console.log('Registered:', isRegistered);

检查客户端是否已注册:
js
const isRegistered = await client.getIsRegistered();
console.log('已注册:', isRegistered);

AI Agent Integration

AI Agent集成

Anonymous Login

匿名登录

Connect to an AI assistant without SIP credentials:
js
const client = new TelnyxRTC({
  anonymous_login: {
    target_id: 'your-ai-assistant-id',
    target_type: 'ai_assistant',
  },
});

client.connect();
Note: The AI assistant must have
telephony_settings.supports_unauthenticated_web_calls
set to
true
.
无需SIP凭证即可连接AI助手:
js
const client = new TelnyxRTC({
  anonymous_login: {
    target_id: 'your-ai-assistant-id',
    target_type: 'ai_assistant',
  },
});

client.connect();
注意:AI助手必须将
telephony_settings.supports_unauthenticated_web_calls
设置为
true

Make Call to AI Assistant

呼叫AI助手

js
// After anonymous login, destinationNumber is ignored
const call = client.newCall({
  destinationNumber: '',  // Can be empty
  remoteElement: 'remoteMedia',
});
js
// 匿名登录后,destinationNumber将被忽略
const call = client.newCall({
  destinationNumber: '',  // 可以为空
  remoteElement: 'remoteMedia',
});

Recommended Codec for AI

AI推荐编解码器

js
const allCodecs = RTCRtpReceiver.getCapabilities('audio').codecs;
const opusCodec = allCodecs.find(c => 
  c.mimeType.toLowerCase().includes('opus')
);

client.newCall({
  destinationNumber: '',
  preferred_codecs: [opusCodec],  // Opus recommended for AI
});

js
const allCodecs = RTCRtpReceiver.getCapabilities('audio').codecs;
const opusCodec = allCodecs.find(c => 
  c.mimeType.toLowerCase().includes('opus')
);

client.newCall({
  destinationNumber: '',
  preferred_codecs: [opusCodec],  // AI场景推荐使用Opus
});

Browser Support

浏览器支持

PlatformChromeFirefoxSafariEdge
Android--
iOS---
Linux--
macOS
Windows-
平台ChromeFirefoxSafariEdge
Android--
iOS---
Linux--
macOS
Windows-

Check Browser Support

检查浏览器支持

js
const webRTCInfo = TelnyxRTC.webRTCInfo;
console.log('WebRTC supported:', webRTCInfo.supportWebRTC);

js
const webRTCInfo = TelnyxRTC.webRTCInfo;
console.log('WebRTC支持情况:', webRTCInfo.supportWebRTC);

Troubleshooting

故障排除

IssueSolution
No audioCheck microphone permissions in browser
Echo/feedbackUse headphones or enable echo cancellation
Connection failsCheck network, firewall, or use TURN relay
Quality issuesEnable
debug: true
and check
telnyx.stats.frame
events

<!-- BEGIN AUTO-GENERATED API REFERENCE -- do not edit below this line -->
references/webrtc-server-api.md has the server-side WebRTC API — credential creation, token generation, and push notification setup. You MUST read it when setting up authentication or push notifications.
问题解决方案
无音频检查浏览器中的麦克风权限
回声/反馈使用耳机或启用回声消除功能
连接失败检查网络、防火墙,或使用TURN中继
通话质量问题启用
debug: true
并查看
telnyx.stats.frame
事件

<!-- BEGIN AUTO-GENERATED API REFERENCE -- do not edit below this line -->
references/webrtc-server-api.md包含服务端WebRTC API——凭证创建、令牌生成和推送通知设置。设置身份验证或推送通知时必须阅读此文档。

API Reference

API参考

TelnyxRTC

TelnyxRTC

The
TelnyxRTC
client connects your application to the Telnyx backend, enabling you to make outgoing calls and handle incoming calls.
js
// Initialize the client
const client = new TelnyxRTC({
  // Use a JWT to authenticate (recommended)
  login_token: login_token,
  // or use your Connection credentials
  //  login: username,
  //  password: password,
});

// Attach event listeners
client
  .on('telnyx.ready', () => console.log('ready to call'))
  .on('telnyx.notification', (notification) => {
    console.log('notification:', notification);
  });

// Connect and login
client.connect();

// You can call client.disconnect() when you're done.
// Note: When you call `client.disconnect()` you need to remove all ON event methods you've had attached before.

// Disconnecting and Removing listeners.
client.disconnect();
client.off('telnyx.ready');
client.off('telnyx.notification');
TelnyxRTC
客户端将您的应用连接至Telnyx后端, 使您能够发起呼出通话并处理呼入通话。
js
// 初始化客户端
const client = new TelnyxRTC({
  // 使用JWT进行身份验证(推荐)
  login_token: login_token,
  // 或使用您的Connection凭证
  //  login: username,
  //  password: password,
});

// 添加事件监听器
client
  .on('telnyx.ready', () => console.log('可发起通话'))
  .on('telnyx.notification', (notification) => {
    console.log('通知:', notification);
  });

// 连接并登录
client.connect();

// 使用完毕后可调用client.disconnect()。
// 注意:调用`client.disconnect()`时,需要移除所有已添加的ON事件方法。

// 断开连接并移除监听器
client.disconnect();
client.off('telnyx.ready');
client.off('telnyx.notification');

Methods

方法

checkPermissions

checkPermissions

checkPermissions(
audio?
,
video?
):
Promise
<
boolean
>
Params:
audio
(boolean),
video
(boolean)
Returns:
Promise
js
const client = new TelnyxRTC(options);

client.checkPermissions();
checkPermissions(
audio?
,
video?
):
Promise
<
boolean
>
参数:
audio
(布尔值),
video
(布尔值)
返回值:
Promise
js
const client = new TelnyxRTC(options);

client.checkPermissions();

disableMicrophone

disableMicrophone

disableMicrophone():
void
Returns:
void
js
const client = new TelnyxRTC(options);

client.disableMicrophone();
disableMicrophone():
void
返回值:
void
js
const client = new TelnyxRTC(options);

client.disableMicrophone();

enableMicrophone

enableMicrophone

enableMicrophone():
void
Returns:
void
js
const client = new TelnyxRTC(options);

client.enableMicrophone();
enableMicrophone():
void
返回值:
void
js
const client = new TelnyxRTC(options);

client.enableMicrophone();

getAudioInDevices

getAudioInDevices

getAudioInDevices():
Promise
<
MediaDeviceInfo
[]>
Returns:
Promise
getAudioInDevices():
Promise
<
MediaDeviceInfo
[]>
返回值:
Promise

getAudioOutDevices

getAudioOutDevices

getAudioOutDevices():
Promise
<
MediaDeviceInfo
[]>
Returns:
Promise
getAudioOutDevices():
Promise
<
MediaDeviceInfo
[]>
返回值:
Promise

getDeviceResolutions

getDeviceResolutions

getDeviceResolutions(
deviceId
):
Promise
<
any
[]>
Params:
deviceId
(string)
Returns:
Promise
js
async function() {
  const client = new TelnyxRTC(options);
  let result = await client.getDeviceResolutions();
  console.log(result);
}
getDeviceResolutions(
deviceId
):
Promise
<
any
[]>
参数:
deviceId
(字符串)
返回值:
Promise
js
async function() {
  const client = new TelnyxRTC(options);
  let result = await client.getDeviceResolutions();
  console.log(result);
}

getDevices

getDevices

getDevices():
Promise
<
MediaDeviceInfo
[]>
Returns:
Promise
js
async function() {
  const client = new TelnyxRTC(options);
  let result = await client.getDevices();
  console.log(result);
}
getDevices():
Promise
<
MediaDeviceInfo
[]>
返回值:
Promise
js
async function() {
  const client = new TelnyxRTC(options);
  let result = await client.getDevices();
  console.log(result);
}

getVideoDevices

getVideoDevices

getVideoDevices():
Promise
<
MediaDeviceInfo
[]>
Returns:
Promise
js
async function() {
  const client = new TelnyxRTC(options);
  let result = await client.getVideoDevices();
  console.log(result);
}
getVideoDevices():
Promise
<
MediaDeviceInfo
[]>
返回值:
Promise
js
async function() {
  const client = new TelnyxRTC(options);
  let result = await client.getVideoDevices();
  console.log(result);
}

handleLoginError

handleLoginError

handleLoginError(
error
):
void
Params:
error
(any)
Returns:
void
handleLoginError(
error
):
void
参数:
error
(任意类型)
返回值:
void

Error handling

错误处理

An error will be thrown if
destinationNumber
is not specified.
js
const call = client.newCall().catch(console.error);
// => `destinationNumber is required`
如果未指定
destinationNumber
,将抛出错误。
js
const call = client.newCall().catch(console.error);
// => `destinationNumber is required`

Setting Custom Headers

设置自定义请求头

client.newCall({
client.newCall({

Setting Preferred Codec

设置首选编解码器

You can pass
preferred_codecs
to the
newCall
method to set codec preference during the call.
您可以在
newCall
方法中传入
preferred_codecs
来设置通话期间的编解码器偏好。

ICE Candidate Prefetching

ICE候选预获取

ICE candidate prefetching is enabled by default. This pre-gathers ICE candidates when the
js
client.newCall({
  destinationNumber: 'xxx',
  prefetchIceCandidates: false,
});
ICE候选预获取默认启用。这会在
js
client.newCall({
  destinationNumber: 'xxx',
  prefetchIceCandidates: false,
});

Trickle ICE

Trickle ICE

Trickle ICE can be enabled by passing
trickleIce
to the
newCall
method.
js
client.newCall({
  destinationNumber: 'xxx',
  trickleIce: true,
});
可通过在
newCall
方法中传入
trickleIce
来启用Trickle ICE。
js
client.newCall({
  destinationNumber: 'xxx',
  trickleIce: true,
});

Call Recovery and
recoveredCallId

通话恢复与
recoveredCallId

When a call is recovered after a network reconnection (reattach), the SDK
当网络重新连接后通话恢复(重新附加)时,SDK

Voice Isolation

语音隔离

Voice isolation options can be set by passing an
audio
object to the
newCall
method. This property controls the settings of a MediaStreamTrack object. For reference on available audio constraints, see MediaTrackConstraints.
可通过在
newCall
方法中传入
audio
对象来设置语音隔离选项。此属性控制MediaStreamTrack对象的设置。有关可用音频约束的参考,请查看MediaTrackConstraints

Events

事件

Params:
eventName
(string),
callback
(Function)
参数:
eventName
(字符串),
callback
(函数)

setAudioSettings

setAudioSettings

setAudioSettings(
settings
):
Promise
<
MediaTrackConstraints
>
Params:
settings
(IAudioSettings)
Returns:
Promise
js
// within an async function
const constraints = await client.setAudioSettings({
  micId: '772e94959e12e589b1cc71133d32edf543d3315cfd1d0a4076a60601d4ff4df8',
  micLabel: 'Internal Microphone (Built-in)',
  echoCancellation: false,
});
setAudioSettings(
settings
):
Promise
<
MediaTrackConstraints
>
参数:
settings
(IAudioSettings)
返回值:
Promise
js
// 在异步函数中
const constraints = await client.setAudioSettings({
  micId: '772e94959e12e589b1cc71133d32edf543d3315cfd1d0a4076a60601d4ff4df8',
  micLabel: 'Internal Microphone (Built-in)',
  echoCancellation: false,
});

webRTCInfo

webRTCInfo

Static
webRTCInfo():
string
|
IWebRTCInfo
Returns:
string
js
const info = TelnyxRTC.webRTCInfo();
const isWebRTCSupported = info.supportWebRTC;
console.log(isWebRTCSupported); // => true
静态方法
webRTCInfo():
string
|
IWebRTCInfo
返回值:
string
js
const info = TelnyxRTC.webRTCInfo();
const isWebRTCSupported = info.supportWebRTC;
console.log(isWebRTCSupported); // => true

webRTCSupportedBrowserList

webRTCSupportedBrowserList

Static
webRTCSupportedBrowserList():
IWebRTCSupportedBrowser
[]
Returns:
IWebRTCSupportedBrowser
js
const browserList = TelnyxRTC.webRTCSupportedBrowserList();
console.log(browserList); // => [{"operationSystem": "Android", "supported": [{"browserName": "Chrome", "features": ["video", "audio"], "supported": "full"},{...}]
静态方法
webRTCSupportedBrowserList():
IWebRTCSupportedBrowser
[]
返回值:
IWebRTCSupportedBrowser
js
const browserList = TelnyxRTC.webRTCSupportedBrowserList();
console.log(browserList); // => [{"operationSystem": "Android", "supported": [{"browserName": "Chrome", "features": ["video", "audio"], "supported": "full"},{...}]

Call

Call

A
Call
is the representation of an audio or video call between two browsers, SIP clients or phone numbers. The
call
object is created whenever a new call is initiated, either by you or the remote caller. You can access and act upon calls initiated by a remote caller in a
telnyx.notification
event handler.
To create a new call, i.e. dial:
js
const call = client.newCall({
  // Destination is required and can be a phone number or SIP URI
  destinationNumber: '18004377950',
  callerNumber: '‬155531234567',
});
To answer an incoming call:
js
client.on('telnyx.notification', (notification) => {
  const call = notification.call;

  if (notification.type === 'callUpdate' && call.state === 'ringing') {
    call.answer();
  }
});
Both the outgoing and incoming call has methods that can be hooked up to your UI.
js
// Hangup or reject an incoming call
call.hangup();

// Send digits and keypresses
call.dtmf('1234');

// Call states that can be toggled
call.hold();
call.muteAudio();
Call
代表两个浏览器、SIP客户端或电话号码之间的音频或视频通话。每当发起新通话时(无论由您还是远程呼叫者发起),都会创建
call
对象。您可以在
telnyx.notification
事件处理程序中访问并处理远程呼叫者发起的通话。
创建新通话(拨号):
js
const call = client.newCall({
  // 目标号码为必填项,可以是电话号码或SIP URI
  destinationNumber: '18004377950',
  callerNumber: '‬155531234567',
});
接听来电:
js
client.on('telnyx.notification', (notification) => {
  const call = notification.call;

  if (notification.type === 'callUpdate' && call.state === 'ringing') {
    call.answer();
  }
});
呼出和呼入通话都有可关联到UI的方法。
js
// 挂断或拒接来电
call.hangup();

// 发送按键音
call.dtmf('1234');

// 可切换的通话状态
call.hold();
call.muteAudio();

Properties

属性

Accessors

访问器

Methods

方法

getStats

getStats

getStats(
callback
,
constraints
):
void
Params:
callback
(Function),
constraints
(any)
Returns:
void
getStats(
callback
,
constraints
):
void
参数:
callback
(函数),
constraints
(任意类型)
返回值:
void

setAudioInDevice

setAudioInDevice

setAudioInDevice(
deviceId
,
muted?
):
Promise
<
void
>
Params:
deviceId
(string),
muted
(boolean)
Returns:
Promise
js
await call.setAudioInDevice('abc123');
setAudioInDevice(
deviceId
,
muted?
):
Promise
<
void
>
参数:
deviceId
(字符串),
muted
(布尔值)
返回值:
Promise
js
await call.setAudioInDevice('abc123');

setAudioOutDevice

setAudioOutDevice

setAudioOutDevice(
deviceId
):
Promise
<
boolean
>
Params:
deviceId
(string)
Returns:
Promise
js
await call.setAudioOutDevice('abc123');
setAudioOutDevice(
deviceId
):
Promise
<
boolean
>
参数:
deviceId
(字符串)
返回值:
Promise
js
await call.setAudioOutDevice('abc123');

setVideoDevice

setVideoDevice

setVideoDevice(
deviceId
):
Promise
<
void
>
Params:
deviceId
(string)
Returns:
Promise
js
await call.setVideoDevice('abc123');
setVideoDevice(
deviceId
):
Promise
<
void
>
参数:
deviceId
(字符串)
返回值:
Promise
js
await call.setVideoDevice('abc123');

ICallOptions

ICallOptions

ICallOptions ICallOptions
ICallOptions ICallOptions

Properties

属性

IClientOptions

IClientOptions

IClientOptions IClientOptions
IClientOptions IClientOptions

Properties

属性

<!-- END AUTO-GENERATED API REFERENCE -->
<!-- END AUTO-GENERATED API REFERENCE -->