Add definition for trtc-js-sdk (#43979)

* Add definition for trtc-js-sdk

* style(trtc-js-sdk): use prettier rewrite

* [trtc-js-sdk]: support off all events

* style(trtc-js-sdk): remove unneed comment

* chore(trtc-js-sdk): enable esModuleInterop in tsconfig

* fix(trtc-js-sdk): fix dts lint export just namespace
This commit is contained in:
yokots 2020-04-23 07:34:28 +08:00 committed by GitHub
parent 5eb4f5ca46
commit cf013cff00
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 815 additions and 0 deletions

760
types/trtc-js-sdk/index.d.ts vendored Normal file
View File

@ -0,0 +1,760 @@
// Type definitions for trtc-js-sdk 4.3
// Project: https://github.com/tencentyun/TRTCSDK#readme
// Definitions by: yokots <https://github.com/yokots>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export as namespace TRTC;
// utils types
export type Nullable<T> = T | null;
export type Callback<T = any> = (event: T) => void;
export type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
/** 提供日志设置方法,包括设置日志输出等级、打开或关闭日志上传。 */
export namespace Logger {
const LogLevel: LogLevel;
/** 日志输出等级 */
interface LogLevel {
/** 输出所有日志 */
TRACE: 0;
/** 输出 DEBUG、INFO、WARN、ERROR 等级日志 */
DEBUG: 1;
/** 输出 INFO、WARN、ERROR 等级日志 */
INFO: 2;
/** 输出 WARN、ERROR 等级日志 */
WARN: 3;
/** 输出 ERROR 等级日志 */
ERROR: 4;
/**
*
* ** 线 WARN **
*/
NONE: 5;
}
/**
*
* @example
* ```javascript
* // 输出INFO以上日志等级
* TRTC.Logger.setLogLevel(TRTC.Logger.LogLevel.INFO);
* ```
*/
function setLogLevel(level: 0 | 1 | 2 | 3 | 4 | 5 | 6): void;
/** 打开日志上传 */
function enableUploadLog(): void;
/** 关闭日志上传 */
function disableUploadLog(): void;
}
/** TRTC Web SDK 版本号 */
export const VERSION: string;
/** 检测浏览器是否兼容 TRTC Web SDK */
export function checkSystemRequirements(): Promise<boolean>;
/** 检测浏览器是否支持屏幕分享 */
export function isScreenShareSupported(): boolean;
/**
*
*
* 访label deviceId 访 initialize()
*/
export function getDevices(): Promise<MediaDeviceInfo[]>;
/** 返回摄像头设备列表 */
export function getCameras(): Promise<MediaDeviceInfo[]>;
/** 返回麦克风设备列表 */
export function getMicrophones(): Promise<MediaDeviceInfo[]>;
/** 返回扬声器设备列表 */
export function getSpeakers(): Promise<MediaDeviceInfo[]>;
/**
*
*
* ID(userId) ID绑定使 使
*/
export function createClient(config: ClientConfig): Client;
/**
* Stream Stream `publish()`
*
* **:** * Stream track *track
*
* :
* -
* -
* - audioSource/videoSource MediaStreamTrack 使
*
* @example
* ```javascript
* // 从麦克风和摄像头采集本地音视频流
* const localStream = TRTC.createStream({ audio: true, video: true });
* localStream.initialize().catch(error => {
* console.error('failed initialize localStream ' + error);
* }).then(() => {
* console.log('initialize localStream success');
* // 本地流初始化成功可通过Client.publish(localStream)发布本地音视频流
* });
* ```
*
* @example
* ```javascript
* // 从屏幕分享源采集,仅采集屏幕分享视频流
* const localStream = TRTC.createStream({ audio: false, screen: true });
*
* // 采集麦克风及屏幕分享视频流
* // const localStream = TRTC.createStream({ audio: true, screen: true });
*
* localStream.initialize().catch(error => {
* console.error('failed initialize localStream ' + error);
* }).then(() => {
* console.log('initialize localStream success');
* // 本地流初始化成功可通过Client.publish(localStream)发布本地音视频流
* });
* ```
* @example
* ```javascript
* // 从外部App指定的音视频源创建本地音视频流
* navigator.mediaDevices.getUserMedia({ audio: true, video: true }).then(stream => {
* const audioTrack = stream.getAudioTracks()[0];
* const videoTrack = stream.getVideoTracks()[0];
*
* // 对audioTrack和videoTrack处理之后
*
* const localStream = TRTC.createStream({ audioSource: audioTrack, videoSource: videoTrack });
* localStream.initialize().catch(error => {
* console.error('failed initialize localStream ' + error);
* }).then(() => {
* console.log('initialize localStream success');
* // 本地流初始化成功可通过Client.publish(localStream)发布本地音视频流
* });
* });
* ```
*/
export function createStream(config: StreamConfig): LocalStream;
export interface RtcError extends Error {
/** 获取错误码, 详细错误码列表参见 [ErrorCode](https://trtc-1252463788.file.myqcloud.com/web/docs/module-ErrorCode.html) */
getCode(): string;
}
/** 音视频通话客户端对象 */
export interface Client {
/**
* ngnix+coturn
*
* **** join()
*/
setProxyServer(url: string): void;
/**
* TURN setProxyServer() 使 TURN
*
* **** join()
*/
setTurnServer(config: TurnServerConfig): void;
/**
*
*
* SDK 退 'stream-added'
*
* publish() 'stream-added'
*/
join(options: JoinOptions): Promise<void>;
/** 退出当前音视频通话房间,结束一次音视频通话会话。 */
leave(): Promise<void>;
/**
*
* - join() unpublish()
* - removeTrack()addTrack() replaceTrack()
* - stream-added
*/
publish(stream: LocalStream): Promise<void>;
/** 取消发布本地流。 取消发布本地流后远端会收到 'stream-removed' 事件通知。 */
unpublish(stream: LocalStream): Promise<void>;
/**
*
* @param stream 'stream-added'
*
* @example
* ```javascript
* // 监听远端流订阅成功事件
* client.on('stream-subscribed', event => {
* const remoteStream = event.stream;
* // 远端流订阅成功,播放远端音视频流
* remoteStream.play('remote_stream');
* });
* // 监听远端流增加事件
* client.on('stream-added', event => {
* const remoteStream = event.stream;
* // 订阅远端音频和视频流
* client.subscribe(remoteStream, { audio: true, video: true });
*
* // 仅订阅音频数据
* // client.subscribe(remoteStream, { audio: true, video: false });
* });
* ```
*/
subscribe(stream: RemoteStream, options?: { audio?: boolean; video?: boolean }): void;
/**
*
* @param stream 'stream-added'
*/
unsubscribe(stream: RemoteStream): void;
/** 切换用户角色 */
switchRole(role: Role): Promise<void>;
/** 监听客户端对象事件 */
on<K extends keyof ClientEventMap>(event: K, handler: Callback<ClientEventMap[K]>): void;
/** 取消事件绑定 */
off<K extends keyof ClientEventMap>(event: K, handler: Callback<ClientEventMap[K]>): void;
/** 取消所有事件绑定 */
off(event: '*'): void;
/** 获取当前房间内远端用户音视频 mute 状态列表。 */
getRemoteMutedState(): RemoteMutedState[];
/**
* join() 使
* @param muted 是否默认不接收远端流: true true false
*/
setDefaultMuteRemoteStreams(muted: boolean): void;
/** 获取当前网络传输状况统计数据, 该方法需要在 `publish()` 后调用 */
getTransportStats(): Promise<TransportStats>;
/** 获取当前已发布本地流的音频统计数据 */
getLocalAudioStats(): Promise<LocalAudioStatsMap>;
/** 获取当前已发布本地流的视频统计数据 */
getLocalVideoStats(): Promise<LocalVideoStatsMap>;
/** 获取当前所有远端流的音频统计数据 */
getRemoteAudioStats(): Promise<RemoteAudioStatsMap>;
/** 获取当前所有远端流的视频统计数据 */
getRemoteVideoStats(): Promise<RemoteVideoStatsMap>;
}
/** 客户端配置项 */
export interface ClientConfig {
/** 应用的 sdkAppId */
sdkAppId: number;
/** 用户ID */
userId: string;
/** 用户签名 */
userSig: string;
/**
* ,:
* - `videoCall`
* - `live`
*/
mode: 'videoCall' | 'live';
/** 绑定腾讯云直播 CDN 流 ID设置之后您就可以在腾讯云直播 CDN 上通过标准直播方案FLV|HLS播放该用户的音视频流。 */
streamId?: string;
/** 设置云端录制完成后的回调消息中的 "userdefinerecordid" 字段内容,便于您更方便的识别录制回调。 */
userDefineRecordId?: string;
/** 自动录制时业务自定义ID(32位整型),将在录制完成后通过直播录制回调接口通知业务方 */
recordId?: number;
/**
* ,:
* - 1 MP3
* - 2 MP3
*/
pureAudioPushMode?: 1 | 2;
}
/** 客户端事件 */
export interface ClientEventMap {
/** 远端流添加事件,当远端用户发布流后会收到该通知。 */
'stream-added': RemoteStreamInfo;
/** 远端流移除事件,当远端用户取消发布流后会收到该通知。 */
'stream-removed': RemoteStreamInfo;
/** 远端流更新事件,当远端用户添加、移除或更换音视频轨道后会收到该通知。 */
'stream-updated': RemoteStreamInfo;
/** 远端流订阅成功事件,调用 subscribe() 成功后会触发该事件。 */
'stream-subscribed': RemoteStreamInfo;
/** 信令通道连接状态变化事件 */
'connection-state-changed': {
prevState: ConnectionState;
curState: ConnectionState;
};
/** 远端用户进房通知,只有主动推流的远端用户进房才会收到该通知。 */
'peer-join': RemoteUserInfo;
/** 远端用户退房通知,只有主动推流的远端用户退房才会收到该通知。 */
'peer-leave': RemoteUserInfo;
/** 远端用户禁用音频通知。 */
'mute-audio': RemoteUserInfo;
/** 远端用户禁用视频通知。 */
'mute-video': RemoteUserInfo;
/** 远端用户启用音频通知。 */
'unmute-audio': RemoteUserInfo;
/** 远端用户启用视频通知。 */
'unmute-video': RemoteUserInfo;
/** 用户被踢出房间通知,被踢原因有 */
'client-banned': RtcError;
/** 客户端错误事件 */
error: RtcError;
}
/**
* Stream Stream track track
*
* Stream LocalStream RemoteStream
*/
export interface Stream {
/**
*
* @param elementId HTML <div> ID
* @param options
*/
play(elementId: HTMLDivElement['id'] | HTMLDivElement, options?: PlayOptions): Promise<void>;
/** 停止播放音视频流,该方法还会将由 `play()` 创建的音视频标签从 HTML 页面中删除。 */
stop(): void;
/**
*
* **** `play()` div `PAUSED`
* @example
* ```javascript
* stream.on('player-state-changed', event => {
* if (event.state === 'PAUSED') {
* // resume audio/video playback
* stream.resume();
* }
* });
* ```
*/
resume(): void;
/** 关闭音视频流,对于本地流,该方法会关闭摄像头并释放摄像头和麦克风访问权限。 */
close(): void;
/**
*
* - `Client.on('mute-audio')`
* -
* @returns `true` ; `false`
*/
muteAudio(): boolean;
/**
*
* - `Client.on('mute-video')` ()使 `removeTrack()` `MediaStreamTrack.stop()`
* -
* @returns `true` ; `false`
*/
muteVideo(): boolean;
/**
*
* - `Client.on('unmute-audio')`
* - `muteAudio()`
* @returns `true` ; `false`
*/
unmuteAudio(): boolean;
/**
*
* - `Client.on('unmute-video')`
* - `muteVideo()`
* @returns `true` ; `false`
*/
unmuteVideo(): boolean;
/** 获取 Stream 唯一标识ID */
getId(): string;
/** 获取该流所属的用户ID */
getUserId(): string;
/**
*
* @param deviceId `getSpeakers()`
*/
setAudioOutput(deviceId: string): Promise<void>;
/**
* ,
* @param volume `0.0 (静音) 到 1.0 (最大音量)`
*/
setAudioVolume(volume: number): void;
/**
* ,
* @returns ,`(0.0, 1.0)``0.1`
*/
getAudioLevel(): number;
/** 是否包含音频轨道 */
hasAudio(): boolean;
/** 是否包含视频轨道 */
hasVideo(): boolean;
/** 获取音频轨道 */
getAudioTrack(): Nullable<MediaStreamTrack>;
/** 获取视频轨道 */
getVideoTrack(): Nullable<MediaStreamTrack>;
/**
*
* **** play() Stream
* @example
* ```javascript
* // 截取当前视频帧
* const frame = stream.getVideoFrame();
* if (frame) {
* const img = document.createElement('img');
* img.src = frame;
* }
* ```
*/
getVideoFrame(): Nullable<string>;
/** 监听Stream事件 */
on<K extends keyof StreamEventMap>(event: K, handler: Callback<StreamEventMap[K]>): void;
}
export interface LocalStream extends Stream {
/** 初始化本地音视频流对象, 初始化失败的错误信息请参考 [getUserMedia异常](https://developer.mozilla.org/zh-CN/docs/Web/API/MediaDevices/getUserMedia#%E8%AF%AD%E6%B3%95)。 */
initialize(): Promise<void>;
/**
* Profile, `initialize()`
* @param profile Profile, `standard`
* - `standard` 4800040kbps
* - `high` 48000128kbps
*/
setAudioProfile(profile: 'standard' | 'high'): void;
/**
* Profile, `initialize()`
* @example
* ```javascript
* // 使用预定义Profile设置
* localStream.setVideoProfile('480p');
* localStream.initialize().then(() => {
* // local stream was initialized successfully.
* });
*
* // 使用自定义视频Profile设置
* localStream.setVideoProfile({
* width: 360, // 视频宽度
* height: 360, // 视频高度
* frameRate: 10, // 帧率
* bitrate: 400 // 比特率 kbps
* });
* localStream.initialize().then(() => {
* // local stream was initialized successfully.
* });
* ```
*/
setVideoProfile(profile: VideoProfileString | Profile): void;
/** 设置屏幕分享 Profile,该方法需要在调用 `initialize()` 之前调用。 */
setScreenProfile(profile: ScreenProfileString | Profile): void;
/**
* `initialize()`
* @param hint [MediaStreamTrack.contentHint](https://www.w3.org/TR/mst-content-hint/)
* - `motion`
* - `detail` ppt线使
* - `text` ppt
*/
setVideoContentHint(hint: 'motion' | 'detail' | 'text'): void;
/**
* ,
*
* `Client.on('stream-updated')`
* @param type
* - `audio`
* - `video`
* @param deviceId
* - getCameras() deviceId 'user' 'environment'
* - getMicrophones()
*/
switchDevice(type: 'audio' | 'video', deviceId: string): Promise<void>;
/**
*
*
* `Client.on('stream-updated')`
*
* `createStream()` | `getAudioTrack()` | `getVideoTrack()`
* [getUserMedia()](https://developer.mozilla.org/zh-CN/docs/Web/API/MediaDevices/getUserMedia)、
* [captureStream()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/captureStream) 获取。
*
* ****
* - Stream 使 `replaceTrack()`
* - `setVideoProfile()`
*
* @example
* ```javascript
* const localStream = TRTC.createStream({ userId, audio: true, video: false });
* localStream.initialize().then(() => {
* // 分布本地流(只有从麦克风采集的音频流)
* client.publish(localStream);
* });
*
* // ...
*
* // 开启视频通话
* const videoStream = TRTC.createStream({ userId, audio: false, video: true });
* videoStream.initialize().then(() => {
* const videoTrack = videoStream.getVideoTrack();
* // 将从摄像头采集的视频轨道插入当前已发布的本地流对象LocalStream
* localStream.addTrack(videoTrack).then(() => {
* // 视频通话开启成功远端流将会收到stream-updated通知
* });
* });
* ```
*/
addTrack(track: MediaStreamTrack): Promise<void>;
/**
*
*
* `Client.on('stream-updated')`
*
* ****
* - Stream对象中至少要有一个媒体轨道 `unpublish()` `close()`
* - `muteAudio()`
*
* @example
* ```javascript
* // 关闭视频通话示例对应addTrack接口的开启视频通话示例
* const videoTrack = localStream.getVideoTrack();
* if (videoTrack) {
* localStream.removeTrack(videoTrack).then(() => {
* // 关闭视频通话成功停止videoTrack并释放摄像头资源
* videoTrack.stop();
* });
* }
* ```
*/
removeTrack(track: MediaStreamTrack): Promise<void>;
/**
*
*
* `Client.on('stream-updated')`
*
* `createStream()` | `getAudioTrack()` | `getVideoTrack()`
* [getUserMedia()](https://developer.mozilla.org/zh-CN/docs/Web/API/MediaDevices/getUserMedia)、
* [captureStream()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/captureStream) 获取。
*
* ****
* - 使 `switchDevice()`
* - `setVideoProfile()`
* - Chrome 65+Safari
*/
replaceTrack(track: MediaStreamTrack): Promise<void>;
}
export interface RemoteStream extends Stream {
/**
* ,
* @returns
* - `main`
* - `auxiliary`
*/
getType(): 'main' | 'auxiliary';
}
export interface StreamConfig {
/** 是否从麦克风采集音频 */
audio: boolean;
/** 是否从摄像头采集视频 */
video: boolean;
/** 音频源 */
audioSource?: MediaStreamTrack;
/** 视频源 */
videoSource?: MediaStreamTrack;
/** 麦克风设备 deviceId通过 getMicrophones() 获取 */
microphoneId?: string;
/** 摄像头设备 deviceId通过 getCameras() 获取 */
cameraId?: string;
/**
* 使
* - `user`
* - `environment`
*
* **** 使 cameraId facingMode
*/
facingMode?: 'user' | 'environment';
/** 是否采集屏幕分享流 */
screen?: boolean;
/** 视频显示是否为镜像,默认为 true。建议在使用前置摄像头时开启使用后置摄像头时关闭。镜像设置不适用于屏幕分享。 */
mirror?: boolean;
}
export interface StreamEventMap {
/** Audio/Video Player 状态变化事件 App 可根据状态变化来更新 UI比如通过监听 video player 状态变化来关闭或打开遮板。 */
'player-state-changed': {
type: string;
state: 'PLAYING' | 'PAUSED' | 'STOPPED';
};
/** 本地屏幕分享停止事件通知,仅对本地屏幕分享流有效。 */
'screen-sharing-stopped': undefined;
}
export interface TurnServerConfig extends Omit<RTCIceServer, 'urls'> {
/** TURN 服务器 url */
url: string;
}
/**
* `live`
* - `anchor`
* - `audience`
*
* **** live switchRole() anchor
*/
export type Role = 'anchor' | 'audience';
export interface JoinOptions {
/** 房间号 */
roomId: number;
/** 用户角色 */
role?: Role;
/**
* @deprecated 使
*/
privateMapKey?: string;
}
export interface RemoteMutedState {
/** 远端用户ID */
userId: string;
/** 是否有视频 */
hasAudio: boolean;
/** 是否有音频 */
hasVideo: boolean;
/** 是否静音 */
audioMuted: boolean;
/** 是否关闭摄像头 */
videoMuted: boolean;
}
export interface TransportStats {
/** SDK 到腾讯视频云的 RTT (Round-Trip Time),单位 ms */
rtt: number;
}
export interface VideoStats {
/** 视频宽度 */
framesWidth: number;
/** 视频高度 */
framesHeight: number;
}
export interface SentMediaStats {
/** 已发送字节数 */
bytesSent: number;
/** 已发送包数 */
packetsSent: number;
}
/** 本地流音频统计数据 */
export type LocalAudioStats = SentMediaStats;
/** 本地流视频统计数据 */
export interface LocalVideoStats extends SentMediaStats, VideoStats {
/** 已编码帧数 */
framesEncoded: number;
/** 已发送帧数 */
framesSent: number;
}
export interface ReceivedMediaStats {
/** 已接收字节数 */
bytesReceived: number;
/** 已接收包数 */
packetsReceived: number;
/** 丢包数 */
packetsLost: number;
}
/** 远端流音频统计数据 */
export type RemoteAudioStats = ReceivedMediaStats;
/** 远端流视频统计数据 */
export interface RemoteVideoStats extends ReceivedMediaStats, VideoStats {
/** 已解码帧数 */
framesDecoded: number;
}
export interface LocalAudioStatsMap {
[userId: string]: LocalAudioStats;
}
export interface LocalVideoStatsMap {
[userId: string]: LocalVideoStats;
}
export interface RemoteAudioStatsMap {
[userId: string]: RemoteAudioStats;
}
export interface RemoteVideoStatsMap {
[userId: string]: RemoteVideoStats;
}
export interface RemoteStreamInfo {
stream: RemoteStream;
}
export interface RemoteUserInfo {
userId: string;
}
/**
*
* - `DISCONNECTED`:
* - `CONNECTING`:
* - `RECONNECTING`:
* - `CONNECTED`:
*/
export type ConnectionState = 'DISCONNECTED' | 'CONNECTING' | 'RECONNECTING' | 'CONNECTED';
/** 播放选项 */
export interface PlayOptions {
/** 视频画面显示模式,参考 [CSS object-fit 属性](https://developer.mozilla.org/zh-CN/docs/Web/CSS/object-fit) */
objectFit: 'contain' | 'cover' | 'fill' | 'none' | 'scale-down';
/** 是否需要 mute 声音,对于本地流通常需要 mute 声音以防止播放从麦克风采集回来的声音。 */
muted: boolean;
}
export interface Profile {
/** 视频宽度 */
width: number;
/** 视频高度 */
height: number;
/** 帧率 */
frameRate: number;
/** 比特率 kbs */
bitrate: number;
}
export type VideoProfileString = '120p' | '180p' | '240p' | '360p' | '480p' | '720p' | '1080p' | '1440p' | '4K';
export type ScreenProfileString = '480p' | '480p_2' | '720p' | '720p_2' | '1080p' | '1080p_2';

View File

@ -0,0 +1,29 @@
TRTC.Logger.setLogLevel(TRTC.Logger.LogLevel.INFO);
TRTC.getDevices().then(devices => {
devices.forEach(device => {
console.log(device.deviceId, device.kind);
});
});
const client = TRTC.createClient({
sdkAppId: 123,
userId: '123',
userSig: 'userSig',
mode: 'live',
});
const stream = TRTC.createStream({
audio: true,
video: true,
});
stream.initialize().then(() => {
client.publish(stream);
});
client.on('stream-subscribed', ({ stream }) => {
stream.play('element-id');
});
client.off('*');

View File

@ -0,0 +1,25 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"dom",
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictFunctionTypes": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",
"trtc-js-sdk-tests.ts"
]
}

View File

@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }