Polyv Help Center

Help Center

Mic Connection Integration

Updated: 2023-08-10 09:36:06

Brief Description

  • After using the Live JS-SDK, if you need to integrate a mic connection service similar to the POYLV live streaming viewing page, you can enable the mic connection feature in the Live JS-SDK to quickly implement web-side Polyv multi-person video and audio calls. This is applicable in both low-latency and standard live streaming scenarios.
  • If you are already using the polyv mic connection SDK: https://player.polyv.net/resp/rtc-sdk/latest/polyv-rtc.min.js, you can also refer to this document to update to the current usage. The usage is essentially the same as the mic connection SDK, allowing for a quick replacement.

Prerequisites

  • Ensure the mic connection feature is enabled.
  • The browser must be Chrome 58 or above, or mainstream browsers like Firefox, Safari.
  • The page must be accessed via HTTPS protocol or localhost.

Mic Connection Process Overview

  1. The instructor clicks to enable student video connection / enable student audio connection on the client.
  2. The OPEN_MICROPHONE event is triggered.
  3. The student can use the joinChannel method of the SDK instance to send a mic connection request to the instructor.
  4. The instructor sees the application and clicks to allow the mic connection. At this point, the ALLOW_MICROPHONE event listened to by the page SDK is triggered.
  5. The student automatically joins the mic connection, starts pushing the stream, the INIT_LOCAL_STREAM_READY event is triggered, sets the corresponding parameters, and pushes the stream.
  6. After successful stream pushing, if the instructor hangs up or the student actively clicks to hang up, the mic connection is exited.

Reference Code

Example Code

Subscribing to Other Streams in the Channel

  1. After a student successfully joins the mic connection, they will receive the streams of existing users (including the instructor) and students who join after them in the channel via the USER_STREAM_ADDED event.
  2. The USER_STREAM_ADDED event triggers the call to the evt.subscribe method in the callback to subscribe to the stream.
  3. If a user exits the channel during this time, the USER_PEER_LEAVE event is triggered.

Quick Start

// 初始化SDK
var liveSdk = new PolyvLiveSdk({
  channelId: channelId,
  sign: sign, // 频道验证签名
  timestamp: timestamp, // 毫秒级时间戳
  appId: appId, // polyv 后台的appId
  user: {
    userId: userId,
    userName: 'polyv-test',
    pic: 'https://livestatic.videocc.net/assets/wimages/missing_face.png'
  }
});

// 监听频道信息并初始化播放器,并加入rtc参数开启连麦,如果开启了无延迟播放则默认开启连麦
liveSdk.on(PolyvLiveSdk.EVENTS.CHANNEL_DATA_INIT, (event, data) => {
  liveSdk.setupPlayer({
    pptEl: '#ppt',
    el: '#player',
    type: 'live',
    rtc: true
  });
});

// 连麦实例初始化完成,可以进行连麦相关代码调用,无延迟,普通直播并支持连麦的情况下会回调
liveSdk.player.on('rtcInitialized', function(rtc){
  // 也可以这样获取实例 liveSdk.player.rtcInstance
  console.log('连麦sdk实例', rtc);
  // 连麦sdk加载后调用相关代码
  initRTC(rtc);
});

// 监听相关事件,进行申请连麦、推流、订阅频道其他用户等操作
function initRTC() {
  rtc.on('OPEN_MICROPHONE', (evt) => {
    console.log('讲师开启连麦, 可发起申请加入连麦');
  });

  rtc.on('CLOSE_MICROPHONE', (evt) => {
    console.log('讲师关闭连麦,可禁止发起连麦申请');
  });

  rtc.on('ALLOW_MICROPHONE', (evt) => {
    console.log('连麦申请通过, 开始连麦');
  });

  rtc.on('INIT_LOCAL_STREAM_READY', (evt) => {
    console.log('准备开始推流,设置推流参数');
    evt.init({
      element: document.getElementById('local') // 选择需要显示本地流的节点
    });
  });
}

Mic Connection Instance

Instance Methods

rtc.on(event: string, eventHandler: Function): void

Used to listen for events such as enabling/disabling mic connection, subscription, and push stream status.

joinChannel(callback?: Function): void

After the client enables mic connection, this method can be called to apply for joining. Example Code

rtc.on('OPEN_MICROPHONE', (evt) => {
  // 也可以通过页面点击申请
  rtc.joinChannel(() => {
    console.log('申请成功');
  });
});

Parameters

  • callback?: Function Callback function for failed application.

cancelJoinChannel(callback?: Function): void

After applying to join the mic connection, if the permission message has not been received yet, this can be called to cancel the application.

Parameters

  • callback?: Function Callback function for failed cancellation.

disableVideo(): void

Used to disable the local video track after pushing the stream.

enableVideo(): void

Used to restore the video track after disabling the local video track.

disableAudio(): void

Used to disable the local audio track after pushing the stream.

enableAudio(): void

Used to restore the audio track after disabling the local video track.

leaveChannel(): void

Used to hang up the mic connection, exit the mic connection channel, and stop pushing the stream.

openDeviceSetting(): void

Opens the device settings panel, which can be used for device debugging and device replacement.

closeDeviceSetting(): void

Closes the device settings panel.

openInviting(): void

Opens the invite to speak panel.

closeInviting(): void

Closes the invite to speak panel.

destroy(): void

Destroys the instance. If currently in a mic connection, it will exit the mic connection.

Events

rtc.on('OPEN_MICROPHONE', callback: Function): void

The client enables mic connection. At this point, you can apply to join the mic connection. Example Code:

rtc.on('OPEN_MICROPHONE', (evt) => {
  console.log(evt.type); // video/audio (视频/音频通话)
});

rtc.on('CLOSE_MICROPHONE', callback: Function): void

The client disables mic connection. At this point, you cannot apply to join the mic connection. Example Code:

rtc.on('CLOSE_MICROPHONE', (evt) => {
  // 若页面有申请连麦的按钮可以 disable
});

rtc.on('JOIN_CHANNEL_TIMEOUT', callback: Function): void

Application for mic connection timed out. Example Code:

rtc.on('JOIN_CHANNEL_TIMEOUT', (evt) => {
  alert('申请连麦超时,请重新申请');
});

rtc.on('ALLOW_MICROPHONE', callback: Function): void

The client approves the mic connection application. At this point, the local stream will be automatically initialized and the mic connection channel will be joined. Example Code:

rtc.on('ALLOW_MICROPHONE', (evt) => {
  console.log(`开始加入连麦,频道为 ${evt.roomId}`);
});

rtc.on('INIT_LOCAL_STREAM_READY', callback: Function): void

Already joined the RTC channel, ready to initialize the local stream. At this point, some configurations for the local stream can be made. Example Code:

rtc.on('INIT_LOCAL_STREAM_READY', (evt) => {
  console.log(`准备推流,通话类型为${evt.type}`);
  evt.init({
    element: document.getElementById('local'),
    control: true,
    profile: '480p'
  });
});
evt.init(config: Object)

Start initializing the local stream and push the stream. This method must be called, otherwise, you cannot join the mic connection. Parameter Description element: HTMLElement: Node element for displaying the local stream. control?: boolean: Whether to display the control bar, default value is true. profile?: string: Set video properties, default value is '240P'.

profile Settings
Video Profile Resolution Bitrate (Kbps)
240p 320 × 240 200
240p_1 320 × 240 200
240p_4 424 × 240 220
480p 640 × 480 500
480p_1 640 × 480 500
480p_8 848 × 480 610
720p 1280 × 720 1130
720p_1 1280 × 720 1130
720p_2 1280 × 720 2080
720p_5 960 × 720 910

rtc.on('INIT_LOCALSTREAM_SUCCESS', callback: Function): void

Local stream initialization successful. Example Code:

rtc.on('INIT_LOCALSTREAM_SUCCESS', (evt) => {
  console.log('初始化本地流成功');
});

rtc.on('INIT_LOCALSTREAM_ERROR', callback: Function): void

Local stream initialization failed. Example Code:

rtc.on('INIT_LOCALSTREAM_ERROR', (evt, error) => {
  console.log(evt.message);
  console.log(error);
});

rtc.on('PUBLIC_STREAM_SUCCESS', callback: Function): void

Stream push successful. Example Code:

rtc.on('PUBLIC_STREAM_SUCCESS', (evt) => {
 console.log('推流成功');
});

rtc.on('PUBLIC_STREAM_ERROR', callback: Function): void

Stream push failed. Example Code:

rtc.on('PUBLIC_STREAM_ERROR', (evt, error) => {
  console.log(error);
});

rtc.on('CLIENT_BANNED', callback: Function): void

The instructor hangs up the mic connection. The mic connection will exit, no other operations are needed. Example Code:

rtc.on('CLIENT_BANNED', (evt) => {
  console.log('被讲师挂断连麦');
});

rtc.on('USER_STREAM_ADDED', callback: Function): void

After joining the mic connection channel, the streams of the teacher and other mic participants are received. Subscription is required at this point. Not broadcast in low-latency mode. Example Code:

rtc.on('USER_STREAM_ADDED', (evt) => {
  console.log(`是否为讲师:${evt.teacher}`);
  console.log(`流Id:${evt.streamId}`);
  console.log(`用户昵称:${evt.nick}`);
  console.log(`用户头像:${evt.pic}`);
  if (evt.teacher) {
    evt.subscribe({
      element: document.getElementById('teacher')
    }, (err) => {
      console.log('订阅失败');
    });
  } else {
    evt.subscribe({
      element: document.getElementById('student'),
      control: true
    });
  }
});
evt.subscribe(config: Object, failCallback: Function)

If the subscribe method is not called, other mic participants in the channel will not be displayed. Parameter Description element: HTMLElement: Node element for displaying the stream. control?: boolean: Whether to display the control bar, default value is true.

rtc.on('USER_STREAM_SUBSCRIBED', callback: Function): void

Subscription successful. Example Code:

rtc.on('USER_STREAM_SUBSCRIBED', (evt) => {
  cons.log('订阅成功');
  console.log(`是否为讲师:${evt.teacher}`);
  console.log(`流Id:${evt.streamId}`);
  console.log(`用户昵称:${evt.nick}`);
  console.log(`用户头像:${evt.pic}`);
});

rtc.on('USER_MUTE_VIDEO', callback: Function): void

Other mic participants in the channel disable video stream push. Example Code:

rtc.on('USER_MUTE_VIDEO', (evt) => {
  console.log(evt.streamId);
});

rtc.on('USER_UNMUTE_VIDEO', callback: Function): void

Other mic participants in the channel re-enable video stream push. Example Code:

rtc.on('USER_UNMUTE_VIDEO', (evt) => {
  console.log(evt.streamId);
});

rtc.on('USER_MUTE_AUDIO', callback: Function): void

Other mic participants in the channel disable audio stream push. Example Code:

rtc.on('USER_MUTE_AUDIO', (evt) => {
  console.log(evt.streamId);
});

rtc.on('USER_UNMUTE_AUDIO', callback: Function): void

Other mic participants in the channel re-enable audio stream push. Example Code:

rtc.on('USER_UNMUTE_AUDIO', (evt) => {
  console.log(evt.streamId);
});

rtc.on('LOCAL_MUTE_VIDEO', callback: Function): void

Local video stream push is disabled, either by the client or the user actively. Example Code:

rtc.on('LOCAL_MUTE_VIDEO', (evt) => {
  console.log('关闭视频轨道');
});

rtc.on('LOCAL_UNMUTE_VIDEO', callback: Function): void

Local video stream push is re-enabled, either by the client or the user actively. Example Code:

rtc.on('LOCAL_UNMUTE_VIDEO', (evt) => {
  console.log('关闭视频轨道');
});

rtc.on('LOCAL_MUTE_AUDIO', callback: Function): void

Local audio stream push is disabled, either by the client or the user actively. Example Code:

rtc.on('LOCAL_MUTE_AUDIO', (evt) => {
  console.log('关闭视频轨道');
});

rtc.on('LOCAL_UNMUTE_AUDIO', callback: Function): void

Local audio stream push is re-enabled, either by the client or the user actively. Example Code:

rtc.on('LOCAL_UNMUTE_AUDIO', (evt) => {
  console.log('开启音频轨道');
});

rtc.on('USER_PEER_LEAVE', callback: Function): void

Triggered when a subscribed stream exits the channel due to a mic connection hang-up. Not broadcast in low-latency mode. Example Code:

rtc.on('USER_PEER_LEAVE', (evt) => {
  console.log(`${evt.streamId}退出连麦`);
});

rtc.on('LEAVE_CHANNEL_SUCCESS', callback: Function): void

Successfully left the video call. Example Code:

rtc.on('LEAVE_CHANNEL_SUCCESS', (evt) => {
  console.log('离开视频通话成功');
});

rtc.on('STOP', callback: Function): void

Actively hang up the video call (triggered by clicking the hang-up button on the default control bar). At this point, you can return to the state before applying for the mic connection. Example Code:

rtc.on('STOP', (evt) => {
  console.log('主动挂断通话');
});

rtc.on('SWITCH_MASTER', callback: Function): void

Speaker switching event. At this point, the corresponding mic participant on the page can be repositioned. It is recommended to switch positions via CSS. Not broadcast in low-latency mode. Example Code:

rtc.on('SWITCH_MASTER', function(evt) {
    var currentUser = evt.currentUser;
    var previousUser = evt.previousUser;

    // 上一个主讲,只在离开的情况为空
    var previousElement = previousUser.element;
    // 当前需要设置的主讲
    var currentElement = currentUser.element;

    rtc.remove(currentUser.streamId);

    // 上一个是因为离开才切换的
    if (previousUser.leave) {
      // 设置到主讲位置
      rtc.play(currentUser.streamId, {
        element: document.getElementById('playerRTC')
      });

      // 上一个主讲已经离开,不需要原来的位置了,删掉元素
      var pn = currentElement.parentNode;
      pn && pn.removeChild(currentElement);
    } else {
      // 设置到上一个主讲位置
      rtc.remove(previousUser.streamId);
      rtc.play(currentUser.streamId, {
        element: previousElement
      });

      // 不是因为离开才切换的需要重新播放上一个主讲的流到新的位置
      rtc.play(previousUser.streamId, {
        element:  currentElement
      });
    }
});

rtc.on('NETWORK_QUALITY', callback: Function): void

The uplink and downlink network quality of the current user, triggered approximately every one to two seconds. uplinkNetworkQuality is the uplink quality, downlinkNetworkQuality is the downlink quality, values are 0|1|2|3|4|5|6.

  • 0 Network quality unknown
  • 1 Network quality excellent
  • 2 Network quality good
  • 3 Network quality fair
  • 4 Network quality poor
  • 5 Network quality bad
  • 6 Network quality disconnected Example Code:
rtc.on('NETWORK_QUALITY', function(evt) {
      console.log('上行质量为:', evt.uplinkNetworkQuality);
      console.log('下行质量为:', evt.downlinkNetworkQuality);
});

rtc.on('INVITE_TO_MICROPHONE', callback: Function): void

Received a mic connection invitation event. At this point, a mic connection invitation popup can be displayed. Example Code:

rtc.on('INVITE_TO_MICROPHONE', function () {
    rtc.openInviting();
});

Notes

  • In low-latency mode, the SDK will automatically subscribe to user streams, so the 'USER_STREAM_ADDED', 'SWITCH_MASTER', 'USER_PEER_LEAVE' events will not be broadcast.
  • In standard scenarios, after a successful mic connection, remember to hide the CDN player and display the RTC. After leaving the mic connection, restore the CDN player.
联系客服,在线咨询
在线咨询