preface
Hello everyone, today xiaobian brings you a audio and video call function based on anyRTC Web SDK (this project adopts VUE development).
The premise condition
There are a few things you need to do before you start writing code. If you haven’t used the anyRTC Web SDK before, take a few minutes to prepare
Operation process
Download and import project dependencies
npm i ar-rtm-sdk -S
npm i ar-rtc-sdk -S
Copy the code
import ArRTM from 'ar-rtm-sdk';
import ArRTC from 'ar-rtc-sdk';
import config from '.. /config';
Copy the code
config.js
export default {
appid: ' '.// AppID generated by anyRTC console (see prerequisites)
uid: 'web' + Math.floor(Math.random() * 10000000) // Randomly generate the local UID
}
Copy the code
Data Initial data
data() {
return {
localInvitation: null./ / by ArRTMClient createLocalInvitation created instance
ArRTMClient: null.RTM client instance created with arrtm. createInstance
ArRTCClient: null.// Client object created with arrtc.createclient
audioTrack: null.// Local audio track
videoTrack: null.// Local video track
audioDevices: [].// List of local audio devices
videoDevices: [] // List of local video devices
remoteUid: ' ' // Uid of the remote user}}Copy the code
mounted
mounted() {
this.getRemoteUid(); // Get the uid of the remote user
this.getDevices(); // Get audio and video devices
this.createTrack(); // Create a local audio and video track
},
Copy the code
methods
// Get the uid of the remote user (this step can be replaced by an input box)
getRemoteUid() {
const remoteUid = this.$route.query.uid;
if (remoteUid) {
this.remoteUid = remoteUid;
this.createClient(); }},// Get audio and video devices
async getDevices() {
const [ videoDevices, audioDevices ] = await Promise.all([
ArRTC.getCameras(),
ArRTC.getMicrophones(),
]);
this.videoDevices = videoDevices;
this.audioDevices = audioDevices;
},
// Create a local audio and video track
async createTrack() {
this.audioTrack = await ArRTC.createMicrophoneAudioTrack();
// No video track is created if there is no camera device
if (this.videoDevices.length) {
this.videoTrack = awaitArRTC.createCameraVideoTrack(); }},// Create RTM and RTC client objects
createClient() {
this.ArRTMClient = ArRTM.createInstance(config.appid);
this.ArRTCClient = ArRTC.createClient({ mode: 'rtc'.codec: 'h264' });
// Listen for remote users to publish audio and video streams
this.listenUserPublished();
// Listen for point-to-point messages
this.listenMessageFromPeer();
/ / login RTM
this.ArRTMClient.login({ uid: config.uid }).then(() = > {
// Listen for the remote user to go online or offline
this.listenPeersOnlineStatusChanged();
// Subscriber goes offline
this.subscribePeersOnlineStatus();
}).catch((err) = > {
console.log(err);
});
},
// Listen for point-to-point messages (the main function here is to tell us about its status via RTM messages)
listenMessageFromPeer() {
this.ArRTMClient.on('MessageFromPeer'.message= > {
// The status code is self-defined
if (message.text === '100') {
// The other party is on another line
} else if (message.text === '200') {
// We have to leave the room when they hang up
this.handleLeave(); }}); },// Listen for remote users to publish audio and video streams
listenUserPublished() {
this.ArRTCClient.on("user-published".async (user, mediaType) => {
await this.ArRTCClient.subscribe(user, mediaType);
this.inTheCall = true;
if (mediaType === 'video') {
// Play the remote video (pass in a DOM element ID)
user.videoTrack.play('#remote_video');
} else if (mediaType === 'audio') {
// Play remote audio (audio does not require elements)user.audioTrack.play(); }}); },// Listen for the remote user to go online or offline
listenPeersOnlineStatusChanged() {
this.ArRTMClient.on('PeersOnlineStatusChanged'.(status) = > {
const ONLINE = status[this.remoteUid] === 'ONLINE';
// If the other party is online, send a call invitation
ONLINE && this.callRemote(this.remoteUid);
});
},
// Listen for localInvitation status
localInvitationListen() {
// Triggered when the called party has accepted the call invitation
this.localInvitation.on('LocalInvitationAccepted'.(response) = > {
// The peer party agrees to accept the local join channel
this.joinChannel();
console.log(response, 'Triggered when called party has accepted call invitation')}); },// Join the channel
joinChannel() {
this.ArRTCClient.join(config.appid, config.uid, null, config.uid).then(() = > {
this.videoTrack && this.videoTrack.play('local_video');
// Publish local audio and video
this.audioTrack && this.ArRTCClient.publish(this.audioTrack);
this.videoTrack && this.ArRTCClient.publish(this.videoTrack);
}).catch((err) = > {
console.log(err);
});
},
// Subscriber goes offline
subscribePeersOnlineStatus() {
this.ArRTMClient.subscribePeersOnlineStatus([this.remoteUid]);
},
// Call a remote user
callRemote() {
// Create an instance of LocalInvitation
this.localInvitation = this.ArRTMClient.createLocalInvitation(this.remoteUid);
// Listen for localInvitation status
this.localInvitationListen();
// Initiate a call
this.localInvitation.send();
},
/ / hang up
handleLeave() {
// Leave the channel
this.ArRTCClient.leave();
// Cancel the sent call invitation
this.localInvitation.cancel();
},
Copy the code
HTML
<! - hang up -- -- >
<div class='hangUp' @click='handleLeave'>
<img src=".. /assets/images/hangUp.png" alt="">
</div>
<! -- Call again -->
<div class='replay' @click='callRemote'>
<div>
<img src=".. /assets/images/replay.png" alt="">
</div>
<p>Call again</p>
</div>
<! -- Local Video container -->
<div id='local_video'></div>
<! -- Remote video container -->
<div id='remote_video'></div>
Copy the code
CSS
<style lang='less' scoped>
#call {
position: fixed;
z-index: 90;
top: 0;
left: 0;
right: 0;
bottom: 0; .hangUp { position: fixed;z-index: 999;
left: 0;
right: 0;
bottom: 100px;
margin: auto;
width: 78px;
height: 78px;
cursor: pointer;
}
.replay {
position: fixed;
z-index: 999;
left: 0;
right: 0;
bottom: 100px;
margin: auto;
display: flex;
flex-direction: column;
align-items: center;
div {
width: 78px;
height: 78px;
cursor: pointer;
}
p {
margin-top: 17px;
font-size: 16px;
font-family: PingFang, PingFang-Regular;
font-weight: 400;
color: #fff; }}#local_video {
position: fixed;
z-index: 300;
top: 38px;
left: 32px;
width: 297px;
height: 167px;
}
#remote_video {
position: fixed;
z-index: 200;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
}
</style>
Copy the code