vue 集成环信 web im 加 一对一视频通话

vue引入集成环信Web IM有2种方式
1、NPM
2、引用本地文件

这里采用第一种:
1.1、通过 NPM 安装 Web SDK

npm install easemob-websdk --save // 核心功能
npm install easemob-webrtc --save //单人视频

1.2、在main.js引入

// 引入环信
import websdk from "easemob-websdk" // 白板
// 引入视频配置
import webrtc from "easemob-webrtc"; // 单人视频
// 配置
const config = {
  xmppURL: '//im-api.easemob.com',           // xmpp Server地址,对于在console.easemob.com创建的appKey,固定为该值
  apiURL: 'http://a1.easemob.com',           // rest Server地址,对于在console.easemob.com创建的appkey,固定为该值
  appkey: '申请的key',         // App key
  https: true,                             // 视频通话功能只支持 https+Webkit 浏览器。 不支持使用http/socks5 代理。
  isHttpDNS: true,                           // 防止DNS劫持从服务端获取XMPPUrl、restUrl
  isMultiLoginSessions: false,               // 是否开启多页面同步收消息,注意,需要先联系商务开通此功能
  isDebug: true,                            // 打开调试,会自动打印log,在控制台的console中查看log
  autoReconnectNumMax: 2,                    // 断线重连最大次数
  autoReconnectInterval: 3,                  // 断线重连每次尝试连接的间隔
  heartBeatWait: 30000,                      // 使用webrtc(视频聊天)时发送心跳包的时间间隔,单位ms
  delivery: true                            // 是否发送已读回执
}

1.3、初始化

// 初始化
var conn = {};
WebIM.config = config;
conn = WebIM.conn = new WebIM.connection({
    appKey: WebIM.config.appkey,
    isHttpDNS: WebIM.config.isHttpDNS,
    isMultiLoginSessions: WebIM.config.isMultiLoginSessions,
    https: WebIM.config.https,
    url: WebIM.config.socketServer,
    apiUrl: WebIM.config.restServer,
    isAutoLogin: WebIM.config.isAutoLogin,
    heartBeatWait: WebIM.config.heartBeatWait,
    autoReconnectNumMax: WebIM.config.autoReconnectNumMax,
    autoReconnectInterval: WebIM.config.autoReconnectInterval,
    delivery: WebIM.config.delivery,
    useOwnUploadFun: WebIM.config.useOwnUploadFun
})
// WebIM.config 为之前集成里介绍的WebIMConfig.js

// 初始化 WebRTC Call 
var rtcCall = new WebIM.WebRTC.Call({
    connection: conn,
    mediaStreamConstaints: {
      audio: true,
      video: true,
      /**
      * 修改默认摄像头,可以按照以下设置,不支持视频过程中切换
      * video:{ 'facingMode': "user" } 调用前置摄像头
      * video: { facingMode: { exact: "environment" } } 后置
      */
    },
    listener: {
        onAcceptCall: function (from, options) {
            console.log('onAcceptCall::', 'from: ', from, 'options: ', options);
        },
        //通过streamType区分视频流和音频流,streamType: 'VOICE'(音频流),'VIDEO'(视频流)
        onGotRemoteStream: function (stream, streamType) {
            console.log('onGotRemoteStream::', 'stream: ', stream, 'streamType: ', streamType);
            var video = document.getElementById('video');
            video.srcObject = stream;
        },
        onGotLocalStream: function (stream, streamType) {
            console.log('onGotLocalStream::', 'stream:', stream, 'streamType: ', streamType);
            var video = document.getElementById('localVideo');
            video.srcObject = stream;
        },
        onRinging: function (caller, streamType) {
            console.log("onRinging", caller)
        },
        onTermCall: function (reason) {
            console.log('onTermCall::');
            console.log('reason:', reason);
        },
        onIceConnectionStateChange: function (iceState) {
            console.log('onIceConnectionStateChange::', 'iceState:', iceState);
        },
        onError: function (e) {
            console.log(e);
        }
     }
});

// 回调 按自己需求加 可以不全要
conn.listen({
    onOpened: function ( message ) {},         //连接成功回调
    onClosed: function ( message ) {},         //连接关闭回调
    onTextMessage: function ( message ) {},    //收到文本消息
    onEmojiMessage: function ( message ) {},   //收到表情消息
    onPictureMessage: function ( message ) {}, //收到图片消息
    onCmdMessage: function ( message ) {},     //收到命令消息
    onAudioMessage: function ( message ) {},   //收到音频消息
    onLocationMessage: function ( message ) {},//收到位置消息
    onFileMessage: function ( message ) {},    //收到文件消息
    onVideoMessage: function (message) {
        var node = document.getElementById('privateVideo');
        var option = {
            url: message.url,
            headers: {
              'Accept': 'audio/mp4'
            },
            onFileDownloadComplete: function (response) {
                var objectURL = WebIM.utils.parseDownloadResponse.call(conn, response);
                node.src = objectURL;
            },
            onFileDownloadError: function () {
                console.log('File down load error.')
            }
        };
        WebIM.utils.download.call(conn, option);
    },   //收到视频消息
    onPresence: function ( message ) {},       //处理“广播”或“发布-订阅”消息,如联系人订阅请求、处理群组、聊天室被踢解散等消息
    onRoster: function ( message ) {},         //处理好友申请
    onInviteMessage: function ( message ) {},  //处理群组邀请
    onOnline: function () {},                  //本机网络连接成功
    onOffline: function () {},                 //本机网络掉线
    onError: function ( message ) {},          //失败回调
    onBlacklistUpdate: function (list) {       //黑名单变动
        // 查询黑名单,将好友拉黑,将好友从黑名单移除都会回调这个函数,list则是黑名单现有的所有好友信息
        console.log(list);
    },
    onRecallMessage: function(message){},      //收到撤回消息回调
    onReceivedMessage: function(message){},    //收到消息送达服务器回执
    onDeliveredMessage: function(message){},   //收到消息送达客户端回执
    onReadMessage: function(message){},        //收到消息已读回执
    onCreateGroup: function(message){},        //创建群组成功回执(需调用createGroupNew)
    onMutedMessage: function(message){},        //如果用户在A群组被禁言,在A群发消息会走这个回调并且消息不会传递给群其它成员
});

// 登录
var options = { 
  apiUrl: WebIM.config.apiURL,
  user: '',
  pwd: '',
  appKey: WebIM.config.appkey,
  success: function (res) {
    // console.log('成功')
    console.log(res)
  },
  error: function (err) {
    console.log(err)
  }
};

1.4、添加在原型方便调用

// 把环信api添加到原型
Vue.prototype.$conn = conn;
Vue.prototype.$rtcCall = rtcCall;
Vue.prototype.$login = options; //登录

1.5、A页面

<template>
  <div>
    <div @click="call">111</div>
    <video id="video" autoplay></video>
    <video id="localVideo" autoplay></video>
  </div>
</template>

<script>
  export default {
    data () {
      return {}
    },
    mounted () { // 页面加载完调用
      this.$login.user = '用户名'
      this.$login.pwd = '密码'
      this.$conn.open(this.$login) // 调用登录
      this.$conn.listen({
        onOpened: function ( message ) { //连接成功回调 
          console.log('登录成功')
        }
      })
      
      // 初始化视频
      var taht = this
      taht.$rtcCall = new WebIM.WebRTC.Call({
          connection: taht.$conn,
          mediaStreamConstaints: {
            audio: true,
            video: true
          },
          listener: {
              onAcceptCall: function (from, options) {
                  console.log('onAcceptCall::', 'from: ', from, 'options: ', options);
              },
              //通过streamType区分视频流和音频流,streamType: 'VOICE'(音频流),'VIDEO'(视频流)
              onGotRemoteStream: function (stream, streamType) { // 接受音视频流
                  console.log('onGotRemoteStream::', 'stream: ', stream, 'streamType: ', streamType);
                  var video = document.getElementById('video');
                  video.srcObject = stream;
              },
              onGotLocalStream: function (stream, streamType) { // 发出音视频流
                  console.log('onGotLocalStream::', 'stream:', stream, 'streamType: ', streamType);
                  var video = document.getElementById('localVideo');
                  video.srcObject = stream;
              },
              onRinging: function (caller, streamType) { // 振铃
                  console.log("onRinging", caller)
                  taht.$rtcCall.acceptCall(); // 接受
              },
              onTermCall: function (reason) {
                  console.log('onTermCall::');
                  console.log('reason:', reason);
              },
              onIceConnectionStateChange: function (iceState) {
                  console.log('onIceConnectionStateChange::', 'iceState:', iceState);
              },
              onError: function (e) {
                  console.log(e);
              }
           }
      });
    },
    methods: {
      call () {
        // this.$rtcCall.controlStream(0, 'id') // 申请麦克风
        // this.$rtcCall.controlStream(3, 'id') // 申请摄像头
        // 音频呼叫对方
        // this.$rtcCall.caller = '自己id';
        // this.$rtcCall.makeVoiceCall('对方id'); //第三个参数为是否录制、第四个参数为是否合并,参数可以为空
        // 视频呼叫对方
        this.$rtcCall.caller = '自己id';
        this.$rtcCall.makeVideoCall('对方id');//用法同视频
        
        // 发送文字消息
        let taht = this
        var sendPrivateText = function () {
            var id = taht.$conn.getUniqueId();                 // 生成本地消息id
            var msg = new WebIM.message('txt', id);      // 创建文本消息
            console.log(msg)
            msg.set({
                msg: 'message content',                  // 消息内容
                to: '对象id',                          // 接收消息对象(用户id)
                roomType: false,                  //扩展消息
                success: function (id, serverMsgId) {
                    console.log('发送成功');  
                },                                       // 对成功的相关定义,sdk会将消息id登记到日志进行备份处理
                fail: function(e){
                    console.log("发生失败");  
                }                                        // 对失败的相关定义,sdk会将消息id登记到日志进行备份处理
            });
            taht.$conn.send(msg.body);
        };
        sendPrivateText()
      }
    }
  }
</script>

1.6、B页面

<template>
  <div>
    <div @click="call">222</div>
    <video id="video" autoplay></video>
    <video id="localVideo" autoplay></video>
  </div>
</template>

<script>
  export default {
    data () {
      return {}
    }
    mounted () { // 页面加载完调用
      this.$login.user = '用户名'
      this.$login.pwd = '密码'
      this.$conn.open(this.$login) // 调用登录
      this.$conn.listen({
        onOpened: function ( message ) { //连接成功回调 
          console.log('登录成功')
        },
        onTextMessage: function (message) { //接受文本消息
          console.log(message)
          alert(message.data)
        }
      })
      // 初始化视频
      var taht = this
      taht.$rtcCall = new WebIM.WebRTC.Call({
          connection: taht.$conn,
          mediaStreamConstaints: {
            audio: true,
            video: true
          },
          listener: {
              onAcceptCall: function (from, options) {
                  console.log('onAcceptCall::', 'from: ', from, 'options: ', options);
              },
              //通过streamType区分视`频流和音频流,streamType: 'VOICE'(音频流),'VIDEO'(视频流)
              onGotRemoteStream: function (stream, streamType) { // 接收音视频流
                  console.log('onGotRemoteStream::', 'stream: ', stream, 'streamType: ', streamType);
                  var video = document.getElementById('video');
                  video.srcObject = stream;
              },
              onGotLocalStream: function (stream, streamType) { // 发生音视频流
                  console.log('onGotLocalStream::', 'stream:', stream, 'streamType: ', streamType);
                  var video = document.getElementById('localVideo');
                  video.srcObject = stream;
              },
              onRinging: function (caller, streamType) { // 振铃
                  console.log("onRinging", caller)
                  taht.$rtcCall.acceptCall(); // 接受
              },
              onTermCall: function (reason) {
                  console.log('onTermCall::');
                  console.log('reason:', reason);
              },
              onIceConnectionStateChange: function (iceState) {
                  console.log('onIceConnectionStateChange::', 'iceState:', iceState);
              },
              onError: function (e) {
                  console.log(e);
              }
           }
      });
    },
    methods: {
      call () {
        // this.$rtcCall.caller = '自己id';
        // this.$rtcCall.makeVideoCall('对方id',null,false,false); //第三个参数为是否录制、第四个参数为是否合并,参数可以为空
      }
    }
  }
</script>

以下是其他相关
vue集成环信Web IM
vue集成环信 web im视频通话

猜你喜欢

转载自blog.csdn.net/weixin_45936690/article/details/107667752