Previously, we have introduced the functions, applicable categories, and integration methods of the components of the apet live component, which can be viewed below:

That is, the functions and applicable categories of small program components

Integration guidelines for building applet components

The small program live broadcast function can be applied to a wide range of scenarios, such as live show, online live class, e-commerce live sale, etc. For different scenarios, the small program live broadcast component provides personalized functions, such as audio and video live broadcast, business background management, IM interaction, commodity list push, beauty, background management and other functions for e-commerce live broadcast scenarios.

Now let’s look at how to realize the current hot e-commerce live streaming function from zero based on the small program components of instant broadcast.

Initialize the SDK

After integrating the SDK, you need to initialize the SDK if you want to use the FUNCTIONS of the SDK.

Let {ZegoExpressEngine} = require(".. / lib/ZegoExpressMiniProgram - 1.6.0 "); let zg; Zg = new ZegoExpressEngine(this.data.appid, this.data.server); // Initialize the instance zg = new ZegoExpressEngine(this.data.appid, this.data.server); SetLogConfig ({logLevel: 'debug', remoteLogLevel: 'debug', logURL: this.data.logURL})Copy the code

If you want to implement a full live functionality, you also need to handle the SDK’s related callbacks. Callbacks need only be set once during the SDK lifecycle.

2. Log in to the room

1. Set room-related callbacks

Before logging in to a room, you need to set a room-related callback so that you can receive notifications of room-related events after successfully logging in to a room. For example, you can handle problems such as room exit due to network interruption.

Take the room state callback as an example:

zg.on('roomStateUpdate', (roomID, updateType, err) => {
      console.log('>>>[liveroom-room] roomStateUpdate, updateType: ' + updateType + ', err: ' , err);
})
Copy the code

UpdateType: ‘DISCONNECTED’, ‘CONNECTING’, and ‘CONNECTED’.

DISCONNECTED: Indicates the DISCONNECTED state, which is entered before logging in to the room and after logging out of the room. If a steady-state exception occurs during the login process, for example, the AppID and AppSign are incorrect, or the local end is KickOut due to the same user name.

CONNECTING: indicates that a request is being made in the CONNECTING state. After you successfully log in to a room, you enter the CONNECTING state. Usually, the application interface is displayed through the CONNECTING state. If the connection is lost due to poor network quality, the SDK will retry internally and return to the requesting connection state.

CONNECTED: indicates that the connection is successful. If the user enters this state, it indicates that the user has logged in to the room successfully. The user can normally receive callback notifications about the addition and deletion of user and flow information in the room.

Select other callback interfaces based on actual service conditions. For the complete room callback interface, click here to view ~~~

2. Log in to obtain the Token

During the development phase, ZEGO provides an interface for obtaining tokens only in the test environment. When it is officially launched, the token logic must be implemented by the developer’s business server.

For details about how to obtain the login token, see Room Login Security

Example call:

/* ZEGO provides an interface for obtaining tokens during development :https://wsliveroom-alpha.zego.im:8282/token, which can only be used in test environments. GetLoginToken: function () {var self = this; Const requestTask = wx.request({url: 'XXXX ', // this interface is created by the developer's backend, and the developer's token is obtained from their respective backend data: {app_id: self.data.appID, id_name: self.data.userID, }, header: { 'content-type': 'text/plain' }, success: function (res) { console.log(">>>[liveroom-room] get login token success. token is: " + res.data); if (res.statusCode ! = 200) { return; } zg.setUserStateUpdate(true); self.loginRoom(res.data, self); }, fail: function (e) { console.log(">>>[liveroom-room] get login token fail, error is: ") console.log(e); }}); }, /** Call 'loginRoom' to login to the room ** Note: Ensure that 'roomID' information is globally unique. Only digits, underscores, and letters of 128 bytes in length are supported. A successful login is the prerequisite for all subsequent operations. **/ zg.loginRoom(this.data.roomid, token, {userID: this.data.userid, userName: this.data.userName }) .then(result => { console.log(TAG_NAME, 'login room succeeded', result); }).catch(err => { console.error(TAG_NAME, 'login room fail', err); })Copy the code

Three, push flow

In the process of live broadcasting, anchors need to push their local pictures, which requires the operation of push stream.

1. Component description

The function of pushing streams in wechat small programs requires the use of zego-Pusher tag provided by ZEGO “Small Program Live broadcast plug-in”.

Example call:

<zego-pusher 
        id="zg-pusher" 
        url="{{pusherInfo.url}}" 
        class="push-content"
        waitingImage="{{waitingImage}}" 
        enableCamera="{{enableCamera}}" 
        debug="{{debug}}" 
        autoFocus="{{autoFocus}}" 
        aspect="{{aspect}}" 
        minBitrate="{{minBitrate}}" 
        maxBitrate="{{maxBitrate}}" 
        zoom="{{zoom}}"
        mode="{{mode}}"
        muted="{{muted}}"
        beauty="{{beauty}}" 
        whiteness="{{whiteness}}"
        orientation="{{orientation}}"
        bindstatechange="onPushStateChange" 
        bindnetstatus="onPushNetStateChange">
</zego-pusher>
Copy the code

2. Start pushing

Anchor After logging in to the room, prepare to push the flow according to the service logic. To use the SDK to push streams, perform the following steps:

1) Trigger push flow.

2) Call startPublishingStream of SDK to obtain the address of the push stream corresponding to streamID.

3) Set the push address obtained in Step 2 to the URL of zego-pusher.

4) Get the push-stream component instance, and then call start() of the instance to record the video.

Example call:

zgPusher = this.selectComponent("#zg-pusher"); // 1/2. When the anchor logs in to the room successfully, the push flow is triggered. Zg. loginRoom(this.data.roomid, token, {userID: this.data.userID, userName: this.data.userName }) .then(result => { console.log(TAG_NAME, 'login room succeeded', result); zg.startPublishingStream(this.data.pusherInfo.streamID).then(({ streamID, url}) => { this.data.pusherInfo = { streamID, url } this.setData({ pusherInfo: this.data.pusherInfo }, () => { zgPusher.start(); })}); }).catch(err => { console.error(TAG_NAME, 'login room fail', err); })Copy the code

3. Push flow event processing

The mini program of wechat will notify the state event of the push flow in the bindStatechange binding method of Zego-Pusher. The developer needs to perform the following operations:

1) In the callback function bound with BindStatechange, call updatePlayerState API provided by SDK to transparently pass the push stream event to SDK.

2) Handle the start and fail states of the push stream in the publisherStateUpdate callback provided by the SDK.

Example call:

// zego-pusher binding onPushStateChange(e) {console.log(' ${TAG_NAME} onPushStateChange ', e.dyail.code, e.detail.message ); zg.updatePlayerState(this.data.pusherInfo.streamID, e); }, // After the server pushes the stream, the stream status is updated; Active stop push flow without callback, Zg. On ('publisherStateUpdate', ({streamID, state, errorCode}) => {console.warn(TAG_NAME, 'publisherStateUpdate', state, streamID, errorCode); this.setData({ publishing: state === 'PUBLISHING' ? true : false, beginToPush: false }) })Copy the code

3) wechat applet will notify the push stream network event in the method bound with BindnetStatus of Zego-pusher. Developers also need to call updatePlayerNetStatus in the corresponding applet callback to pass the push stream event through to SDK.

Example call:

// zego-pusher bind the network status event onPushNetStateChange(e) {console.log(' ${TAG_NAME} onPushNetStateChange ', e.dyail.code, e.detail.message ); zg.updatePlayerNetStatus(this.data.pusherInfo.streamID, e); Zg. on('publishQualityUpdate', (streamID, publishStats) => {console.log('publishQualityUpdate', streamID, stats); });Copy the code

4) Stop the push flow

To stop the push flow, the developer needs to do the following:

1) Call stopPublishingStream(streamID) provided by SDK to clear the push flow state.

2) Stop the push flow by calling stop() provided by the zego-pusher instance.

Note: Step 1 is mandatory; otherwise, the SDK status may be abnormal.

Example call:

Zg. StopPublishingStream (this.data.pushStreamid); zgPusher.stop();Copy the code

Fourth, pull flow

In the process of live broadcasting, if the audience in the studio wants to see the push screen of the anchor, it needs to perform the pull operation.

1. Component description

The pull flow function of wechat applica ti on needs to use the zego-Player tag provided by the plug-in.

Example call:

<zego-player 
        id="zg-player" 
        sid="{{playerInfo.streamID}}" 
        url="{{playerInfo.url}}"
        orientation="{{orientation}}" 
        objectFit="{{objectFit}}" 
        minCache="{{minCache}}" 
        maxCache="{{maxCache}}" 
        mode="{{mode}}" 
        muted="{{muted}}" 
        debug="{{debug}}"
        pictureInPictureMode="{{pictureInPictureMode}}" 
        objectFit="{{objectFit}}" 
        class="play-content" 
        bindstatechange="onPlayStateChange" 
        bindnetstatus="onPlayNetStateChange">
</zego-player>
Copy the code

2. Start pulling flow

After the audience logs in to the room successfully, prepare the pull flow according to the business logic. To use the SDK to pull streams, perform the following steps:

1) Trigger pull flow

2) Call SDK’s startPlayingStream to get the play address of streamID

3) Set the push stream address obtained in Step 2 to the URL of zego-Player and the stream ID to SID.

4) Get the pull stream component instance, and then call play() of the instance toplay the video or set the autoPlay property of the pull stream component to true to realize automatic pull stream.

Example call:

Zg. startPlayingStream(streamList[0].streamid).then(({streamID, url }) => { console.warn(TAG_NAME, 'startPlayingStream', streamID, url); that.data.playerInfo.streamID = streamID; that.data.playerInfo.url = url; that.setData({ playerInfo: that.data.playerInfo }, () => { console.error(that.data.playerInfo, zgPlayer) zgPlayer.play(); }) }).catch(err => { console.warn(TAG_NAME, 'startPlayingStream', err); }); zgPlayer = this.selectComponent("#zg-player"); zgPlayer.play();Copy the code

3. Pull event processing

The wechat mini program will notify the pull flow status event in the bindStatechange binding method of zego-Player. The developer needs to perform the following operations:

1) In the callback function bound with BindStatechange, call updatePlayerState API provided by SDK to transparently pass the push stream event to SDK.

2) Handle the start and failure states of push and pull streams in the onPlayStateUpdate callback provided by the SDK.

Example call:

// zego-player binding onPlayStateChange(e) {// Passthrough the stream event to the SDK, type 0 stream zg.updatePlayerState(e.dyail.streamid, e); }, // The server actively pushes over the stream's play status, video play status notification; type: { start:0, stop:1}; zg.onPlayStateUpdate = function (updatedType, streamID) { console.log(`${TAG_NAME} onPlayStateUpdate ${updatedType === 0 ? 'start ' : 'stop '} ${streamID}`); };Copy the code

3) wechat applet will notify the pull flow network event in the method bound with BindnetStatus of Zego-Player. Developers also need to call updatePlayerNetStatus in the corresponding applet callback to pass the push flow event through to SDK.

Example call:

// zego-player bind the network status event onPlayNetStateChange(e) {console.log(' ${TAG_NAME} onPlayNetStateChange ', e.deail.info); zg.updatePlayerNetStatus(e.detail.streamID, e); }, // SDK pulls the network quality callback zg.on('playQualityUpdate', (streamID, stats) => { console.log(`${TAG_NAME} playQualityUpdate ${streamID}`, stats); });Copy the code

4, stop pulling flow

To stop pull flow, the developer needs to do the following:

1) Call stopPlayingStream(Streamid) provided by SDK to clear the pull state.

2) Call stop() provided by zego-player to stop the push stream.

Note: Step 1 is mandatory; otherwise, the SDK status may be abnormal.

Example call:

/ / stop pull flow mid-december. StopPlayingStream (. This data. PlayInfo. StreamID); zgPlayer.stop();Copy the code

Exit the room

Call logoutRoom below to exit the room. Before exiting the room, be sure to stop the push and pull flow and clean up the associated state.

Example call:

zg.logoutRoom(this.data.roomID);
Copy the code

Configure the domain name of the public platform

The URL (including HTTPS and WSS protocol) assigned by ZEGO to developers needs to be configured with the “legitimate domain name” on the wechat public platform before the small program can access it normally.

Wechat background configuration address: wechat public platform -> Settings -> development Settings -> server domain name.

Please fill the domain name assigned by ZEGO into the specified request domain name or socket domain name according to the protocol classification. Such as:

Through the above steps, the function of small program live broadcasting can be realized. The functions such as commodity list and background management can be opened in the message area or private message. It only takes 1 week to complete the configuration of all functions.