npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mark-test1-grtc

v1.0.32

Published

`GRTC Web SDK` 是实时音视频通讯解决方案的`Web`端`SDK`,它是通过`HTML`网页加载的`JavaScript`库。开发者可以使用`GRTC Web SDK`提供的`API`建立连接,控制实时音视频通话。

Downloads

39

Readme

GRTC Web SDK

简介

GRTC Web SDK 是实时音视频通讯解决方案的WebSDK,它是通过HTML网页加载的JavaScript库。开发者可以使用GRTC Web SDK提供的API建立连接,控制实时音视频通话。

API 概要

  • GRTC是整个SDK的主入口,提供创建客户端对象Client和创建本地流对象Stream方法。

  • Client客户端对象,提供实时音视频通话的核心能力,包括进房join()及退房leave(),发布本地流publish()及停止发布本地流unpublish(),订阅远端流subscribe()及取消订阅远端流unsubscribe()

  • Stream音视频流对象,包括本地流LocalStream和远端流RemoteStream对象。Stream对象中的方法为本地流及远端流通用方法。

    • 本地流LocalStream通过createStream()创建;
    • 远端流RemoteStream通过监听Client.on()'stream-added'事件获得。

GRTC

GRTCGRTC Web SDK的主入口,通过GRTC方法可以创建一个实时音视频通信的客户端对象(Client)和本地音视频流对象(Stream)GRTC方法还可以检测浏览器的兼容性,是否支持屏幕分享。

Methods

(async) checkSystemRequirements() → {Promise.}

检测GRTC Web SDK是否支持当前浏览器 若GRTC Web SDK不支持当前浏览器,根据用户设备类型建议用户使用SDK可以支持的浏览器。

Example
GRTC.checkSystemRequirements().then((result) => {
  if(!result) {
     console('Your browser is not compatible with GRTC');
     // SDK 不支持当前浏览器,建议用户使用最新版本的 Chrome 浏览器。
  }
});
Returns:

Type Promise.<boolean>

isScreenShareSupported() → {Promise.}

检测浏览器是否支持屏幕分享 在创建屏幕分享流之前请调用该方法检查当前浏览器是否支持屏幕分享。

Example
if (GRTC.isScreenShareSupported()) {
  console.log('当前浏览器支持屏幕分享');
} else {
  console.log('当前浏览器不支持屏幕分享');
}
Returns:

Type Promise.<boolean>

(async) getDevices() → {Promise.<Array.>}

返回媒体输入输出设备列表

Note

  • 该接口不支持在http协议下使用,请使用https协议部署您的网站。Privacy and security
  • 出于安全的考虑,在用户未授权摄像头或麦克风访问权限前,labeldeviceId字段可能都是空的。因此建议在用户授权访问后, 再调用该接口获取设备详情。
Example
GRTC.getDevices()
  .then(deviceList => {
    deviceList.forEach(item => {
      console.log('device: ' + item.kind + ' ' + item.label + ' ' + item.deviceId);
    });
  })
  .catch(error => console.error('getDevices error observed ' + error));
Returns:

Promise 返回 MediaDeviceInfo 数组

Type Promise.<Array.<MediaDeviceInfo>>

(async) getCameras() → {Promise.<Array.>}

返回摄像头设备列表

Note

  • 该接口不支持在 http 协议下使用,请使用 https 协议部署您的网站。Privacy and security
  • 出于安全的考虑,在用户未授权摄像头或麦克风访问权限前,labeldeviceId字段可能都是空的。因此建议在用户授权访问后, 再调用该接口获取设备详情。
Example
GRTC.getCameras()
        .then(cameraList => {
            cameraList.forEach((item) => {
                console.log('camera: ' + item.kind + ' ' + item.label + ' ' + item.deviceId);
            });
        })
        .catch(error => console.error('getCameras error observed ' + error));
Returns:

Promise 返回 MediaDeviceInfo 数组

Type Promise.<Array.<MediaDeviceInfo>>

(async) getMicrophones() → {Promise.<Array.>}

返回麦克风设备列表

Note

  • 该接口不支持在 http 协议下使用,请使用 https 协议部署您的网站。Privacy and security
  • 出于安全的考虑,在用户未授权摄像头或麦克风访问权限前,labeldeviceId字段可能都是空的。因此建议在用户授权访问后, 再调用该接口获取设备详情。
Example
GRTC.getMicrophones()
  .then(microphoneList => {
    microphoneList.forEach(item => {
      console.log('microphone: ' + item.kind + ' ' + item.label + ' ' + item.deviceId);
    });
  })
  .catch(error => console.error('getMicrophones error observed ' + error));
Returns:

Promise 返回 MediaDeviceInfo 数组

Type Promise.<Array.<MediaDeviceInfo>>

createClient(clientConfig) → {Client}

创建一个实时音视频通话的Client对象,用于实现进房、推流、拉流等功能。 一个Client对象相当于一个用户,跟一个userId绑定;同一个页面中可以有多个不同的Client,每个Client对象跟不同userId绑定。 比如,你可以使用一个Client对象负责推送本地音视频流和接收远端流, 同时使用另外一个Client对象负责推送屏幕分享流,但是不接收远端流。

Examples
// 实时通话模式下创建客户端对象
const client = GRTC.createClient({
  sdkAppId: 0,   // 填写您申请的 sdkAppId
  userId: '',    // 填写您业务对应的 userId
  token: '',   // 填写服务器或本地计算的 token
  mode: 'rtc'
});
Parameters:

clientConfig object 客户端配置项

Properties

| Name | Type | Attributes | Default | Description | | :--------- | :------- | :--------- | :------ | :----------------------------------------------------------- | | sdkAppId | string | | | sdkAppId实时音视频控制台 单击 应用管理 > 创建应用 创建新应用之后,即可在 应用信息 中获取sdkAppId信息。 | | userId | string | | | 用户ID建议限制长度为12字节,只允许包含大小写英文字母(a-zA-Z)、数字(0-9)。 | | token | string | | | token签名计算 token的方式请参考 | | mode | string | | | 应用场景,目前支持以下一种场景:rtc 实时通话模式 |

Returns:

客户端对象

Type Client

createStream(streamConfig) → {Stream}

创建一个本地流Stream对象,本地流Stream对象通过publish()方法发布本地音视频流。

注意:一个音视频流Stream中最多只能包含一个音频track和一个视频track

本地音视频流可以

  • 从摄像头和麦克风采集获得,适用于一般的音视频通话。
  • 从屏幕分享源采集获得,适用于进行屏幕分享。
  • 从开发者通过 audioSource/videoSource 指定的 MediaStreamTrack 获得, 使用这种方式业务层可先对音视频进行前处理,比如,对音频进行混音,或者对视频进行美颜处理,亦或者通过这种方式向远端用户推送一个正在播放的音视频文件。
Examples
// 从麦克风和摄像头采集本地音视频流
const localStream = GRTC.createStream({ userId, audio: true, video: true });
localStream.initialize().then(() => {
  console.log('initialize localStream success');
  // 本地流初始化成功,可通过Client.publish(localStream)发布本地音视频流
}).catch(error => {
  console.error('failed initialize localStream ',error);
});
// 从屏幕分享源采集
// 仅采集屏幕分享视频流
const localStream = GRTC.createStream({ userId, audio: false, screen: true });
// 采集麦克风及屏幕分享视频流
// const localStream = GRTC.createStream({ userId, audio: true, screen: true });
localStream.initialize().then(() => {
  console.log('initialize localStream success');
  // 本地流初始化成功,可通过Client.publish(localStream)发布本地音视频流
}).catch(error => {
  console.error('failed initialize localStream ',error);
});
// 从外部App指定的音视频源创建本地音视频流
navigator.mediaDevices.getUserMedia({ audio: true, video: true }).then(stream => {
  const audioTrack = stream.getAudioTracks()[0];
  const videoTrack = stream.getVideoTracks()[0];
  // 对audioTrack和videoTrack处理之后,
  const localStream = GRTC.createStream({ userId, audioSource: audioTrack, videoSource: videoTrack });
  localStream.initialize().then(() => {
    console.log('initialize localStream success');
    // 本地流初始化成功,可通过Client.publish(localStream)发布本地音视频流
  }).catch(error => {
    console.error('failed initialize localStream ',error);
  });
}
);
Parameters:

| Name | Type | Description | | :------------- | :----- | :---------- | | streamConfig | object | Properties |

Properties

| Name | Type | Attributes | Default | Description | | :------------- | :------ | :--------- | :------ | :----------------------------------------------------------- | | userId | string | | | 用户ID | | audio | boolean | | | 是否从麦克风采集音频 | | microphoneId | string | | | 麦克风设备 deviceId,通过getMicrophones()获取 | | video | boolean | | | 是否从摄像头采集视频 | | cameraId | string | | | 摄像头设备deviceId,通过getCameras()获取 | | facingMode | string | | | 指定使用前置或后置摄像头来采集视频。 在移动设备上,可通过该参数选择使用前置或后置摄像头:'user':前置摄像头'environment':后置摄像头注意请勿同时使用 cameraIdfacingMode 参数。 | | screen | boolean | | | 是否采集屏幕分享流 |

Throws:

RtcError

Returns:

本地音视频流对象

Type Stream

Client

音视频通话客户端对象Client通过GRTC.createClient()创建,代表一次音视频会话。 Client客户端对象提供GRTC Web SDK的核心功能,包括:

  • 进房 join()
  • 退房 leave()
  • 发布本地流 publish()
  • 取消发布本地流 unpublish()
  • 订阅远端流 subscribe()
  • 取消订阅远端流 unsubscribe()

Client生命周期如图所示:

Client生命周期

Methods

(async) join(options) → {Promise}

加入一个音视频通话房间。 进房代表开始一个音视频通话会话,这时候SDK会监听远端用户进房退房情况,若有远端用户进房并且发布流, 本地会收到'stream-added'事件。进房后用户可以通过publish()发布本地流,本地流发布成功后远端用户就会收到相应'stream-added'事件通知从而完成一个双向的音视频通话连接。

Example
const client = GRTC.createClient({ mode: 'rtc', sdkAppId, userId, token });
client.join({ roomId: 8888 }).then(() => {
  // join room success
}).catch(error => {
  console.error('Join room failed: ',error);
});
Parameters:

| Name | Type | Description | | :-------- | :----- | :---------- | | options | object | 进房参数 |

Properties

| Name | Type | Attributes | Description | | :------- | :----- | :--------- | :----------------------------------- | | roomId | number | | 默认是number类型,仅数字,长度1-9位 |

Throws:

RtcError

Returns:

Type Promise

(async) leave() → {Promise}

退出当前音视频通话房间,结束一次音视频通话会话。 退房前请确保已经通过unpublish()取消发布本地流,若未取消发布本地流,SDK 内部会自动取消发布本地流。 同时,退房会关闭所有远端流。

Example
client.leave().then(() => {
  // leaving room success
}).catch(error => {
  console.error('leaving room failed: ',error);
});
Returns:

Type Promise

destroy()

销毁Client实例

调用时机:

  • 在退房之后,若业务侧无需再使用client时,需调用该接口及时销毁client实例,释放相关资源。
  • 当用户网络不好时,client.join可能花费较长时间,可调用该接口中断client.join调用流程。

注意:

  • 销毁后的 client 实例不可再继续使用。
  • 已进房的情况下,需先调用client.leave接口退房成功后,才能调用该接口销毁client
Examples
let client = GRTC.createClient({ sdkAppId, userId, userSig, mode: 'rtc' });
await client.join({ roomId: 123456 });
// 通话结束时
await client.leave();
// 若后续无需再使用该 client,则销毁 client,并释放引用。
client.destroy();
client = null;
let client = GRTC.createClient({ sdkAppId, userId, userSig, mode: 'rtc' });
// 假设业务逻辑需要在5s内完成进房,否则认为进房超时。
const id = setTimeout(() => {
 // 销毁 client 实例,中止 client.join 流程。
 client.destroy();
 client = null;
}, 5000)
try {
 await client.join({ roomId: 123456 });
} catch(error) {}
clearTimeout(id);

(async) publish(stream) → {Promise}

发布本地音视频流。 该方法需要在join()进房后调用,一次音视频会话中只能发布一个本地流。若想发布另外一个本地流,可先通过unpublish()取消发布当前本地流后再发布新的本地流。 在发布本地流后,可通过removeTrack()addTrack()replaceTrack()来更新本地流中的某个音频或视频流。 发布本地流后远端会收到'stream-added'事件通知。

NOTE

  • 请勿在LocalStream.switchDevice接口调用完成前,调用该接口。否则可能导致切换设备异常。
Example
localStream.initialize().then(() => {
  // 本地流初始化成功,发布本地流
  client.publish(localStream).then(() => {
    // 本地流发布成功
  });
});
Parameters:

| Name | Type | Description | | :------- | :----- | :------------------------------------- | | stream | Stream | 本地流,通过 createStream() 创建出来。 |

Throws:

RtcError

Returns:

Type Promise

(async) unpublish(stream) → {Promise}

取消发布本地流。 取消发布本地流后远端会收到'stream-removed'事件通知。 请在leave()退房前取消已经发布的本地流。

Example
client.unpublish(localStream).then(() => {
    // 取消发布本地流成功
}).catch(err => {
    console.log(err);
});
Parameters:

| Name | Type | Description | | :------- | :------- | :---------- | | stream | Stream | 本地流 |

Throws:

RtcError

Returns:

Type Promise

(async) subscribe(stream, optionsopt)

订阅远端流 开发者通过subscribe接口,指明需要订阅音频、视频或者音视频流。

Note:

  • 对于同一远端流,必须得在subscribe/unsubscribe调用完成后,才能开始下一次调用。
Examples
// 监听远端流订阅成功事件
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 }).catch(e => {
    console.error('failed to subscribe remoteStream');
  });
  // 仅订阅音频数据
  // client.subscribe(remoteStream, { audio: true, video: false }).catch(e => {
  //  console.error('failed to subscribe remoteStream');
  // });
});
// 对于同一远端流,必须得在 subscribe/unsubscribe 调用完成后,才能开始下一次调用。
// bad
client.subscribe(remoteStream, { audio: true, video: true });
client.unsubscribe(remoteStream);
// good
await client.subscribe(remoteStream, { audio: true, video: true });
await client.unsubscribe(remoteStream);
Parameters:

| Name | Type | Attributes | Description | | :-------- | :------- | :----------- | :----------------------------------------------------------- | | stream | Stream | | 远端流,通过监听'stream-added'事件获得。 | | options | object | <optional> | 订阅选项。audiovideo不能同时为 false。若无需订阅远端流,请使用unsubscribe()取消订阅。 |

Fires:
  • ClientEvent.event:STREAM_SUBSCRIBED 订阅成功事件通知
Throws:

RtcError

(async) unsubscribe(stream)

取消订阅远端流 当收到远端流增加事件'stream-added'通知后,SDK默认会立刻接收并解码该远端流所包含的音视频数据,如果你想拒绝接收 该远端流的任何音视频数据,请在 'stream-added' 事件处理回调中调用此接口。

Note:

  • 对于同一远端流,必须得在subscribe/unsubscribe调用完成后,才能开始下一次调用。
Examples
client.on('stream-added', event => {
  const remoteStream = event.stream;
  // 拒绝接收该远端流所包含的任何音视频数据
  client.unsubscribe(remoteStream).catch(e => {
    console.error('failed to unsubscribe remoteStream');
  });
});
// 对于同一远端流,必须得在 subscribe/unsubscribe 调用完成后,才能开始下一次调用。
// bad
client.subscribe(remoteStream, { audio: true, video: true });
client.unsubscribe(remoteStream);
// good
await client.subscribe(remoteStream, { audio: true, video: true });
await client.unsubscribe(remoteStream);
Parameters:

| Name | Type | Description | | :------- | :------- | :---------------------------------------- | | stream | Stream | 远端流,通过监听stream-added'事件获得。 |

Throws:

RtcError

on(eventName, handler)

监听客户端对象事件 详细事件列表请参见:ClientEvent

Example
client.on('stream-added', event => {
  // stream-added event handler
});
Parameters:

| Name | Type | Description | | :---------- | :------- | :----------- | | eventName | string | 事件名称 | | handler | function | 事件处理方法 |

off(eventName, handler)

取消事件绑定 用于移除通过on()绑定的事件。

Example
client.on('peer-join', function peerJoinHandler(event) {
  // peer-join event handler
  console.log('peer joined');
  client.off('peer-join', peerJoinHandler);
});
// 解除所有事件绑定
client.off('*');
Parameters:

| Name | Type | Description | | :---------- | :------- | :-------------------------------------------- | | eventName | string | 事件名称,传入通配符 '*' 会解除所有事件绑定。 | | handler | function | 事件处理方法 |

(async) getMemberList()

获取房间内用户列表

开发者可根据该方法获取当前房间成员列表

Example
client.getMemberList().then((list) => {
    const userList = list.filter(item =>item.display !== constraints.userId).filter(item=>item.type!==1)
    console.log(userList);
})
Returns:

Promise 返回房间成员数组

Type Promise.<Array>

Stream

Stream音视频流,一个Stream中最多只能同时包含一个音频track和一个视频trackStream类是本地流LocalStream和远端流RemoteStream的基类,它包含本地流和远端流通用的方法。

Methods

(async) play(elementId, optionsopt) → {Promise}

播放该音视频流 该方法会自动创建<audio><video>标签并在指定的标签上播放音频和视频,同时该标签会被添加到页面中名为elementId的 div 容器。 换句说,Stream内部会自动创建相应的音频播放器和视频播放器来播放相应的音频和视频。

Example
stream.play('remote').then(() => {
  // autoplay success
}).catch((error) => {
  
});
Parameters:

| Name | Type | Attributes | Description | | :---------- | :----------------------- | :--------- | :----------------------------------------------------------- | | elementId | string | HTMLDivElement | | 在 DOM 中的某个 标签 ID 或者 HTMLDivElement 对象,该方法会在指定的 elementId 元素中创建音视频标签来播放音视频流。 注意:当传入 string 类型的 elementId 时,需要确保 elementId 在 DOM 中,否则调用接口会报错。 业务侧可自行调整该 DOM 元素的 css 宽高来控制 video 标签显示的宽高。 | | options | object | | 播放选项Properties |

Properties

| Name | Type | Description | | :---------- | :------ | :----------------------------------------------------------- | | objectFit | string | 视频画面显示模式,参考 CSS object-fit 属性contain 优先保证视频内容全部显示。视频尺寸等比缩放,直至视频窗口的一边与视窗边框对齐。如果视频尺寸与显示视窗尺寸不一致,在保持长宽比的前提下,将视频进行缩放后填满视窗,缩放后的视频四周会有一圈黑边。cover 优先保证视窗被填满。视频尺寸等比缩放,直至整个视窗被视频填满。如果视频长宽与显示窗口不同,则视频流会按照显示视窗的比例进行周边裁剪或图像拉伸后填满视窗。fill 保证视窗被填满的同时保证视频内容全部显示,但是不保证视频尺寸比例不变。视频的宽高会被拉伸至和视窗尺寸一致。播放视频流默认使用 cover 模式。 | | muted | boolean | 是否需要 mute 声音。 对于本地流,muted 默认为 true,防止播放从麦克风采集的声音。 | | mirror | boolean | 是否开启视频镜像预览。 注意对于本地音视频流,默认开启镜像预览。建议在使用前置摄像头时开启镜像,使用后置摄像头时关闭镜像。对于远端音视频流,默认关闭镜像预览。对于屏幕分享流,不支持开启镜像预览。该参数只对本地预览有效,推流是没有镜像效果的。 |

Throws:

RtcError

Returns:

Type Promise

stop()

停止播放音视频流 该方法还会将由play()创建的音视频标签从HTML页面中删除。

close()

关闭音视频流 使用场景:

  • 本地流LocalStream调用该方法会停止播放及停止采集。因此若您想停止采集摄像头及麦克风,可以调用该方法。
  • 远端流RemoteStream一般无需调用该方法。该方法会停止播放并关闭音视频track。若您不想继续订阅远端流,请使用Client.unsubscribe

muteAudio() → {boolean}

禁用音频轨道,且保留音频轨道,通常用于本地流临时静音。

  • 本地流LocalStream调用该方法会停止发送音频,远端会触发 Client.on('mute-audio') 事件。
  • 远端流RemoteStream调用该方法会停止解码播放音频,但是仍然接收音频数据,若您不想接收视频数据,请使用Client.unsubscribe取消订阅,或者 Client.subscribe只订阅视频。
Returns:
  • true 禁用音频轨道成功。
  • false 禁用音频轨道失败,因为没有音频轨道。

Type boolean

muteVideo() → {boolean}

禁用视频轨道,且保留视频轨道,通常用于本地流临时禁画。

  • 本地流LocalStream调用该方法会停止发送视频,远端会触发 Client.on('mute-video') 事件。 如果视频是从摄像头采集,此时摄像头灯仍然是亮着的。
  • 远端流RemoteStream调用该方法会停止解码播放视频,但是仍然接收视频数据,若您不想接收视频数据,请使用 Client.unsubscribe 取消订阅。
Returns:
  • true 禁用视频轨道成功
  • false 禁用视频轨道失败,因为没有视频轨道。

Type boolean

unmuteAudio() → {boolean}

启用音频轨道

  • 存在音频轨道的情况下,本地流LocalStream在调用muteAudio()后,用该方法重新启用音频,这时远端会触发 Client.on('unmute-audio') 事件。
  • 远端流RemoteStream在调用muteAudio()后,用该方法恢复解码播放音频。
Returns:
  • true 启用音频轨道成功。
  • false 没有音频轨道,启用失败。

Type boolean

unmuteVideo() → {boolean}

启用视频轨道

  • 存在视频轨道的情况下,本地流LocalStream在调用muteVideo()后,用该方法重新启用视频轨道,这时远端会触发 Client.on('unmute-video') 事件。
  • 远端流RemoteStream在调用muteVideo()后,用该方法恢复解码播放视频。
Returns:
  • true 启用视频轨道成功。
  • false 没有视频轨道,启用失败。

Type boolean

getId() → {string}

获取 Stream 唯一标识ID

Returns:

Id 流唯一标识

Type string

getUserId() → {string}

获取该流所属的用户ID

Returns:

userId 用户ID

Type string

getAudioLevel() → {number}

获取当前音量大小 只有当本地流或远端流中有音频数据才有效,在获取音量前需要先播放该音视频流。

Example
setInterval(() => {
  const level = stream.getAudioLevel();
  if (level >= 0.1) {
    console.log(`user ${stream.getUserId()} is speaking`);
  }
}, 200);
Returns:

audioLevel 音量大小

  • 返回值在(0.0, 1.0)之间,通常认为值大于0.1为用户正在说话。

Type number

hasAudio() → {boolean}

是否包含音频轨道

  • 如果需要获取Stream mute状态,需要监听Client.on('mute-audio')事件做进一步处理。
Returns:

Type boolean

hasVideo() → {boolean}

是否包含视频轨道

  • 如果需要获取Stream mute状态,需要监听Client.on('mute-video')事件做进一步处理。
Returns:

Type boolean

getAudioTrack() → (nullable) {MediaStreamTrack}

获取音频轨道

Returns:

音频轨道

Type MediaStreamTrack

getVideoTrack() → (nullable) {MediaStreamTrack}

获取视频轨道

Returns:

视频轨道

Type MediaStreamTrack

LocalStream

LocalStream本地音视频流,通过createStream()创建。

Extends

  • Stream

Methods

initialize() → {Promise}

初始化本地音视频流对象

Note

  • 该接口不支持在http协议下使用,请使用https协议部署您的网站。Privacy and security

错误信息:

| | | | | :----------------------- | :----------------------------------------------------------- | :----------------------------------------------------------- | | 错误名 | 描述 | 处理建议 | | NotFoundError | 找不到满足请求参数的媒体类型(包括:音频、视频、屏幕分享)。例如:PC 没有摄像头,但是请求浏览器获取视频流,则会报此错误。 | 建议在通话开始前引导用户检查通话所需的摄像头或麦克风等外设,若没有摄像头且需要进行语音通话,可在 GRTC.createStream({ audio: true, video: false }) 指明仅采集麦克风。 | | NotAllowedError | 用户拒绝了当前的浏览器实例的访问音频、视频、屏幕分享请求。 | 提示用户不授权摄像头/麦克风访问无法进行音视频通话 | | NotReadableError | 尽管用户已经授权使用相应的设备,但是由于操作系统上某个硬件、浏览器或者网页层面发生的错误导致设备无法被访问。 | 根据浏览器的报错信息处理,并提示用户: “暂时无法访问摄像头/麦克风,请确保当前没有其他应用请求访问摄像头/麦克风,并重试” | | OverconstrainedError | cameraId/microphoneId 参数的值无效 | 确保 cameraId/microphoneId 传值正确且有效 | | AbortError | 由于某些未知原因导致设备无法被使用 | |

Example
// 例如:处理 NotReadableError 错误
localStream.initialize().then(() => {
  // 本地流初始化成功,发布本地流
  client.publish(localStream).then(() => {
  // 本地流发布成功
  })
})catch(error => {
    console.error('failed initialize localStream ', error);
});
Returns:

Type Promise

setAudioProfile(profile)

设置音频 Profile 该方法需要在调用initialize()之前。

Example
localStream.setAudioProfile('high');
localStream.initialize().then(() => {
  // localStream was initialized success
});
Parameters:

| Name | Type | Description | | :-------- | :----- | :----------- | | profile | string | 音频 Profile |

| 音频 Profile | 采样率 | 声道 | 样本量 | | :----------- | :----- | :----- | :----- | | standard | 48000 | 单声道 | 8 | | high | 48000 | 单声道 | 16 |

(async) setVideoProfile(profile) → {Promise}

设置视频 Profile

  • 该方法需要在 initialize()之前或者调用。
  • 动态调用支持 Chrome 68+, Safari 12.1+, Firefox 64+
  • 请勿在client.publish接口未调用结束(Promise处于pending状态)时调用该接口,否则设置可能会不生效。
  • 动态调用时,若设置了摄像头不支持的 profile,浏览器有可能会停止采集并抛出错误。 建议在用户进房前,检测当前摄像头支持的分辨率,避免传入摄像头不支持的 profile。
Examples
// 使用预定义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.
});
// 动态设置 profile
localStream.setVideoProfile('480p');
await localStream.initialize();
await client.publish(localStream);
try {
   await localStream.setVideoProfile('1080p');
} catch(error) {
  if (error.name === 'OverconstrainedError') {
     console.error('当前摄像头不支持该 profile');
     // 设置失败,当前摄像头已停止采集,需要恢复采集
     const stream = GRTC.createStream({ video: true, audio: false });
     await stream.initialize();
     localStream.replaceTrack(stream.getVideoTrack());
  } else {
     console.error('当前浏览器不支持动态调用该接口');
  }
}
// 推流后更新码率
client.publish(localStream).then(() => {
   localStream.setVideoProfile("480p_15");
})
// 获取实际采集的分辨率和帧率
const videoTrack = localStream.getVideoTrack();
if (videoTrack) {
   const settings = videoTrack.getSettings();
   console.log(`分辨率:${settings.width} * ${settings.height}, 帧率:${settings.frameRate}`)
}
Parameters:

| Name | Type | Description | | :-------- | :--------------- | :----------- | | profile | string | object | 视频 Profile |

视频 Profile

| 视频 Profile | 分辨率(宽 x 高) | 帧率(fps) | 备注 | | :----------- | :---------------- | :---------- | :--- | | 360p_15 | 640 x 360 | 15 | | | 360p_24 | 640 x 360 | 24 | | | 480p_15 | 640 x 480 | 15 | | | 480p_24 | 640 x 480 | 24 | | | 720p_15 | 1280 x 720 | 15 | | | 720p_24 | 1280 x 720 | 24 | | | 1080p_15 | 1920 x 1080 | 15 | | | 1080p_24 | 1920 x 1080 | 24 | |

Returns:

Type Promise

setScreenProfile(profile)

设置屏幕分享 Profile

该方法需要在调用initialize()之前调用。

Example
// 指定 Profile
localStream.setScreenProfile('1080p_15');
localStream.initialize().then(() => {
  // local stream was initialized successfully
});
// 指定自定义分辨率、帧率和码率
localStream.setScreenProfile({ width: 1920, height: 1080, frameRate: 24,});
localStream.initialize().then(() => {
  // local stream was initialized successfully
});
Parameters:

| Name | Type | Description | | :-------- | :----- | :------------- | | profile | string | screen profile |

screen profile

| 屏幕 Profile | 分辨率(宽 x 高) | 帧率(fps) | 备注 | | :--------------- | :---------------- | :---------- | :--- | | 360p_15 | 640 x 360 | 15 | | | 360p_24 | 640 x 360 | 24 | | | 480p_15 | 640 x 480 | 15 | | | 480p_24 | 640 x 480 | 24 | | | 720p_15 | 1280 x 720 | 15 | | | 720p_24 | 1280 x 720 | 24 | | | 1080p_15 | 1920 x 1080 | 15 | | | 1080p_24 | 1920 x 1080 | 24 | |

  • 屏幕分享默认使用 1080p
  • 若以上 Profile 不能满足您的业务需求,您也可以指定自定义的分辨率、帧率和码率。

(async) switchDevice(type, deviceId) → {Promise}

切换媒体输入设备

调用该方法可以更换本地流的媒体输入设备:

  • 音频输入设备,例如更换本地流的麦克风。
  • 视频输入设备,例如更换本地流的摄像头。

Note:

  • 该方法仅适用于采集了摄像头和麦克风的本地流,以及采集了麦克风的本地屏幕分享流。即:自定义采集流不支持调用该接口,开启系统音频采集的屏幕分享流不支持调用该接口。
  • 若该本地流已经被发布,该方法会自动更新发往远端的音视频流,此时,远端会收到 Client.on('stream-updated') 事件通知。
  • 请勿在publish接口调用完成前,调用该接口。否则可能导致接口调用异常。
Example
// 切换本地流的摄像头
const localStream = GRTC.createStream({ userId, audio: true, video: true });
await localStream.initialize()
await client.publish(localStream);
const cameras = await GRTC.getCameras();
await localStream.switchDevice('video', cameras[0].deviceId)

// 切换本地屏幕分享流的麦克风,前提需要初始属性 audio 为 true
const localStream = GRTC.createStream({ userId, audio: true, screen: true });
await localStream.initialize()
client.publish(localStream);
const microphones = await GRTC.getMicrophones();
await localStream.switchDevice('video', microphones[0].deviceId)
Parameters:

| Name | Type | Description | | :--------- | :----- | :----------------------------------------------------------- | | type | string | 媒体类型'audio' 音频'video' 视频 | | deviceId | string | 设备标识摄像头设备标识通过 getCameras() 获取。 在移动设备上,可以通过设置 deviceId 为 'user' 和 'environment' 来切换前置和后置摄像头。麦克风设备标识通过 getMicrophones() 获取。 |

Returns:

Type Promise

(async) addTrack(track)

添加音频或视频轨道

调用该方法将音频或视频轨道添加到本地流,若该本地流已经被发布,则会自动更新发往远端的音视频流,此时远端会收到 Client.on('stream-updated') 事件通知。

新的音视频轨道可以通过 createStream()/getAudioTrack()|getVideoTrack()获取, 或者直接通过 getUserMedia()captureStream() 获取。

Note

  • 一个 Stream 对象中最多只能同时包含一路音频轨道和一路视频轨道。如果你想要更换同类型的轨道,请使用replaceTrack()
  • 在增加视频轨道时,要求视频分辨率跟setVideoProfile()设置保持一致,否则会抛出异常。
  • 请勿在removeTrackpublish接口调用完成前,调用该接口。否则可能导致接口调用异常。
Example
const localStream = GRTC.createStream({ userId, audio: true, video: false });
localStream.initialize().then(() => {
  // 分布本地流(只有从麦克风采集的音频流)
  client.publish(localStream);
});
// ...
// 开启视频通话
const videoStream = GRTC.createStream({ userId, audio: false, video: true });
videoStream.initialize().then(() => {
  const videoTrack = videoStream.getVideoTrack();
  // 将从摄像头采集的视频轨道插入当前已发布的本地流对象LocalStream
  localStream.addTrack(videoTrack).then(() => {
    // 视频通话开启成功,远端流将会收到‘stream-updated’通知
  });
});
Parameters:

| Name | Type | Description | | :------ | :--------------- | :------------- | | track | MediaStreamTrack | 音频或视频轨道 |

Throws:

RtcError

(async) removeTrack(track)

移除视频轨道 调用该方法会移除本地流中的视频轨道,若本地流已经被发布,则会自动更新发往远端的视频流,此时远端会收到 Client.on('stream-updated') 事件通知。 请注意,一个已经发布的Stream对象中至少要有一个媒体轨道,如果你想完全删除本地流中的音视频轨道,请直接通过unpublish()取消发布, 然后再通过close()关闭本地流。 NOTE

  • 目前尚不支持移除音频轨道,若想禁用音频,可通过调用muteAudio()实现。
  • 请勿在addTrackpublish接口调用完成前,调用该接口。否则可能导致接口调用异常。
  • 视频轨道移除后,hasVideo()将返回 false
Example
// 关闭视频通话示例,对应addTrack接口的开启视频通话示例
const videoTrack = localStream.getVideoTrack();
if (videoTrack) {
  localStream.removeTrack(videoTrack).then(() => {
    // 关闭视频通话成功,停止videoTrack并释放摄像头资源
    videoTrack.stop();
  });
}
Parameters:

| Name | Type | Description | | :------ | :--------------- | :----------------------------------------------------------- | | track | MediaStreamTrack | 视频轨道,track 通过 getVideoTrack()获取。 |

Throws:

RtcError

(async) replaceTrack(track)

更换音频或视频轨道 调用该方法更换本地流中的同类型轨道,若本地流已经被发布,该方法会自动更新发往远端的音视频流,此时远端会收到 Client.on('stream-updated') 事件通知。 新的音视频轨道可以通过 createStream()/getAudioTrack()|getVideoTrack()获取, 或者直接通过getUserMedia()captureStream()获取。 Note:

  • 如果需要更换媒体输入设备,推荐使用switchDevice()
  • 在更换视频轨道时,要求视频分辨率跟setVideoProfile()设置保持一致,否则会抛出异常。
  • 支持 Chrome 65+、Safari 11+、Firefox 56+、Edge 80+ 浏览器。
  • 请勿在publish接口调用完成前,调用该接口。否则可能导致接口调用异常。
Parameters:

| Name | Type | Description | | :------ | :--------------- | :------------- | | track | MediaStreamTrack | 音频或视频轨道 |

Throws:

RtcError

RemoteStream

远端音视频流,通过监听 Client.on('stream-added') 事件获得。

远端流的生命周期在事件 Client.on('stream-added') 到事件 Client.on('stream-removed') 之间,在这两个事件之间,远端流可能会通过 Client.on('stream-updated') 进行更新,比如远端用户通过addTrack()removeTrack()增加或删除track后本地就会收到此通知。

Example
// 远端流生命周期内的操作示例
// 通过监听‘stream-added’事件获得远端流对象
const client = GRTC.createClient({ sdkAppId, userId, userSig, mode: 'live'});
client.on('stream-added', event => {
  const remoteStream = event.stream;
  const remoteUserId = remoteStream.getUserId();
  console.log('received a remoteStream ID: ' + remoteStream.getId() + ' from user: ' + remoteUserId);
  // 若需要观看该远端流,则需要订阅它
  client.subscribe(remoteStream);
  // 若不需要观看该远端流,请取消订阅它,否则SDK会接收远端流数据。
  // client.unsubscribe(remoteStream);
});
// 监听‘stream-removed’事件
client.on('stream-removed', event => {
  const remoteStream = event.stream;
  console.log('remoteStream ID: ' + remoteStream.getId() + ' has been removed');
  // 停止播放并删除相应<video>标签
});
// 监听‘stream-updated’事件
client.on('stream-updated', event => {
  const remoteStream = event.stream;
  console.log('remoteStream ID: ' + remoteStream.getId());
});
// 监听‘stream-subscribed’事件
client.on('stream-subscribed', event => {
  const remoteStream = event.stream;
  // 远端流订阅成功,在HTML页面中创建一个<video>标签,假设该标签ID为‘remote-video-view’
  // 播放该远端流
  remoteStream.play('remote-video-view');
});

Extends

  • Stream

RtcError

new RtcError()

RtcError 错误对象

Extends

  • Error

Methods

getCode()

获取错误码

ClientEvent

客户端事件列表

Client.on('eventName') 事件监听中的事件名称。

Members

(static) STREAM_ADDED

Default Value:

  • 'stream-added'

远端流添加事件,当远端用户发布流后会收到该通知

Example
client.on('stream-added', event => {
  const remoteStream = event.stream;
});

(static) STREAM_REMOVED

Default Value:

  • 'stream-removed'

远端流移除事件,当远端用户取消发布流后会收到该通知。

Example
client.on('stream-removed', event => {
  const remoteStream = event.stream;
});

(static) STREAM_UPDATED

Default Value:

  • 'stream-updated'

远端流更新事件,当远端用户添加、移除或更换音视频轨道后会收到该通知。

Example
client.on('stream-updated', event => {
  const remoteStream = event.stream;
});

(static) STREAM_SUBSCRIBED

Default Value:

  • 'stream-subscribed'

远端流订阅成功事件,调用subscribe()成功后会触发该事件。

Example
client.on('stream-subscribed', event => {
  const remoteStream = event.stream;
});

(static) STREAM_RECONNECT

Default Value:

  • 'stream-reconnect'

远端流重连事件,当远端流因为网络波动等原因导致重连后,会收到该通知。该通知会返回之前中断的远端流ID和新的远端流对象。重连之后需要替换之前remoteStream.play()时创建的远端流播放标签的id;也可以删除remoteStream.play()时创建的远端流播放标签后再次执行remoteStream.play()方法播放远端流

Parameters:

| Name | Type | Attributes | Description | | :------------------ | :----------- | :--------- | :------------- | | stream | RemoteStream | | 远端流对象 | | interruptStreamId | string | | 中断的远端流ID |

Example
client.on('stream-reconnect', event => {
    const remoteStream = event?.stream;
    const oldStreamBox = event?.oldStreamId;
    const remoteBox = document.querySelector(`#remote-${oldStreamBox}`)
    remoteBox?.setAttribute("id", `remote-${event.stream.getId()}`);
    const userIdBox = remoteBox?.parentNode
    userIdBox?.setAttribute("id", `userId-${event.stream.getId()}`);
});

(static) PEER_JOIN

Default Value:

  • 'peer-join'

远端用户进房通知

注意:远端用户进房,就能收到进房通知,不需要推流后

Example
client.on('peer-join', event => {
  const userId = event.userId;
});

(static) PEER_LEAVE

Default Value:

  • 'peer-leave'

远端用户退房通知

注意:

  • 只有远端用户退房时,才会通知退房,取消推流不通知
Example
client.on('peer-leave', event => {
  const userId = event.userId;
});

(static) MUTE_AUDIO

Default Value:

  • 'mute-audio'

远端用户禁用音频通知。

Example
client.on('mute-audio', event => {
  const userId = event.userId;
});

(static) MUTE_VIDEO

Default Value:

  • 'mute-video'

远端用户禁用视频通知。

Example
client.on('mute-video', event => {
  const userId = event.userId;
});

(static) UNMUTE_AUDIO

Default Value:

  • 'unmute-audio'

远端用户启用音频通知。

Example
client.on('unmute-audio', event => {
  const userId = event.userId;
});

(static) UNMUTE_VIDEO

Default Value:

  • 'unmute-video'

远端用户启用视频通知。

Example
client.on('unmute-video', event => {
  const userId = event.userId;
});

(static) AUDIO_VOLUME

Default Value:

  • 'audio-volume'

音量大小事件

调用enableAudioVolumeEvaluation接口开启音量大小回调后,SDK会定时抛出该事件,通知每个userId的音量大小。

Note

  • 回调中包含推流的本地流及已订阅的远端流的音量大小,无论是否有人说话,都会触发该回调。
  • audioVolume 取值为0-100的正整数,通常认为 audioVolume > 10 的用户正在说话
Example
client.on('audio-volume', event => {
    event.result.forEach(({ userId, audioVolume, stream }) => {
        if (audioVolume > 10) {
           console.log(`user: ${userId} is speaking, audioVolume: ${audioVolume}`);
        }
    })
})
// 开启音量回调,并设置每 1000ms 触发一次事件
client.enableAudioVolumeEvaluation(1000);

Parameters:

| Name | Type | Attributes | Default | Description | | :------------------- | :------ | :--------- | :------ | :----------------------------------------------------------- | | interval | number | | 2000 | 用于设置音量回调事件定时触发的时间间隔。默认为 2000(ms),最小值为16(ms)。若设置小于等于0时,则关闭音量大小回调。 | | enableInBackground | boolean | | false | 出于性能的考虑,当页面切换到后台时,SDK 不会抛出音量回调事件。如需在页面切后台时接收音量回调事件,可设置该参数为 true。 |

(static) ERROR

Default Value:

  • 'error'

错误事件,当出现不可恢复错误后,会抛出此事件

Example
client.on('error', error => {
  console.error('client error observed: ',error);
  const errorCode = error.getCode();
  // 当出现客户端错误后,请调用 Client.leave() 退房并尝试通过 Client.join() 重新进房恢复通话。
});