| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978 |
- <template>
- <page-meta :page-font-size="fontValue+'px'" :root-font-size="fontValue+'px'"></page-meta>
- <view>
- <cu-custom :isBack='true' >
- <template v-slot:content>
- <text class="text-jiachu text-black">在线通话</text>
- </template>
- </cu-custom>
- <view class="IncolumnC">
- <image class="AvatarImg" :src="friendAvatar" mode="scaleToFill"></image>
- <text v-if="friend.value" class="text-black text-lg"></text>
- <text class="text-black text-lg" style="margin-top: 10rpx;">{{friendName}}</text>
- <view class="InrowC" style="margin-top: 80rpx;">
- <text class="text-black text-lg">{{stateNote}}</text>
- <image style="width: 52rpx;height: 52rpx;margin-left: 6rpx;" src="/static/mine/loading2.gif" mode=""></image>
- </view>
- <view class="InrowC" style="margin-top: 300rpx;">
- <image v-if="!canClose" style="width:110rpx ;height: 110rpx;" src="/static/mine/icon_on.png" mode="scaleToFill" @click="acceptWebrtc"></image>
- <image v-if="canClose" style="width:110rpx ;height: 110rpx;" src="/static/mine/icon_off.png" mode="scaleToFill" @click="closeWebrtcBT"></image>
- <image v-if="speacker" style="margin-left: 50rpx;width:110rpx ;height: 110rpx;" src="/static/mine/ysq_on.png" mode="scaleToFill" @click="changeSpeack"></image>
- <image v-if="!speacker" style="margin-left: 50rpx;width:110rpx ;height: 110rpx;" src="/static/mine/ysq_off.png" mode="scaleToFill" @click="changeSpeack"></image>
- </view>
- </view>
- </view>
- </template>
- <script setup lang="ts">
- import {onLoad,onReady,onShow,onUnload} from '@dcloudio/uni-app';
- import {ref,watch} from 'vue'
- import * as ASCIIUtils from '@/uni_modules/wrs-js-modbusCRCHex/js_sdk/wrs-ASCIIUtils.js';
- import * as HexUtils from '@/uni_modules/wrs-js-modbusCRCHex/js_sdk/wrs-HexUtils.js';
- import {
- UTSWebRTC
- } from "@/uni_modules/wrs-uts-webrtc";
- import {
- UTSVoipMgr
- } from "@/uni_modules/wrs-uts-voip"
-
- import MessageUtils from "@/utils/MessageUtils";
- import CuCustom from '@/colorui/components/cu-custom.vue'
- import UserApi from "@/api/UserApi";
- import {useUserStore} from '@/store/userStore'
- import {useWsStore} from "@/store/WsStore";
- import {storeToRefs} from "pinia";
- import type Webrtc from '@/mode/Webrtc';
- import ChatType from "@/utils/ChatType";
- import {usePeerStore} from "@/store/peerStore";
- import SendCode from '@/utils/SendCode'
- import Auth from "@/api/Auth";
- const fontValue=ref(Auth.getfontSize());
-
- let webRTC = new UTSWebRTC();
- let candidateList=[];
- let friendAvatar='/static/logo512.png';
- let friendName='';
- let stateNote =ref("正在呼叫");
- let audioObj=null;
- const timeCall=ref(0);
- const timer=ref();
-
- const wsStore = useWsStore();
- const peerStore = usePeerStore();
- const friendId = ref("");
- const friend = ref("");
-
- const startTime = ref(0)
- const isCaller = ref(false);
- const showVideo = ref(false);
- const speacker = ref(false);
- const canClose = ref(true);
- const user = useUserStore().getUser()
- const isConnect = ref(false)
- const videoIsOpen = ref(false)
- const videocanOpen = ref(false)
- const hadClose = ref(false);
- const androidpermission = ref(false);
-
- const {isClose} = storeToRefs(peerStore)
- const {offer} = storeToRefs(peerStore)
- const {answer} = storeToRefs(peerStore)
-
- const {candidate} = storeToRefs(peerStore)
- const {isAccept} = storeToRefs(peerStore)
-
-
- watch(isAccept, (newVal) => {
- if (newVal) {
- timeCall.value=45;
- startTime.value = new Date().getTime()
- createPeerConnection(friendId.value);
- getoffer();
- }
- })
- watch(isClose, (newVal) => {
- console.log('isCloseisClose',newVal)
- if (newVal) {
- if(videoIsOpen.value){
- //通知视频播放页面关闭
- let data={
- type:'isClose'
- }
- uni.$emit('webRTCvideoE', { msg:JSON.stringify(data)});
- }
- else{
- uni.navigateBack()
- }
-
- }
- })
-
- watch(offer, (newVal) => {
- if (newVal) {//收到answeroffer
- console.log('offer',newVal)
- recOffer();
- }
- })
-
- watch(answer, (newVal) => {
- if (newVal) {//收到answer
- recAnswer();
- }
- })
-
- watch(candidate, (newVal) => {
- if (newVal) {//收到candidate
- console.log('candidate');
- var list = JSON.parse(newVal);
- recCandidate(list);
- }
- if(!isCaller.value){
- sendCandidate();
- }
- })
-
- const chaoshipanduan = () => {
- timeCall.value=45;
- timer.value = setInterval(() => {
- timeCall.value=timeCall.value-1;
- if(timeCall.value==0&&!isConnect.value){
- MessageUtils.message('暂时无法连接,请稍后重试!')
- }
- else if(isConnect.value){
- clearInterval(timer.value);//正常接通
- return;
- }
- else if(timeCall.value<-2&&!isConnect.value){
- uni.navigateBack();
- }
- }, 1000);
- }
-
- const audioObjstart = () => {
- audioObj=uni.createInnerAudioContext();
- audioObj.loop=true;
- audioObj.volume=0.2;
- audioObj.src='/hybrid/html/images/calling.mp3';
- audioObj.play();
- }
-
- const audioObjstop = () => {
- if(audioObj){
- audioObj.stop();
- }
- }
-
- onShow(()=>{
- // console.log('onShow',videoIsOpen.value)
- if(videoIsOpen.value){
- uni.navigateBack();
- return;
- }
- if(uni.getSystemInfoSync().platform == "ios"){
- let state = UTSVoipMgr.getApplicationState();
- if(state!=2){
- if(!isCaller.value){
- //let provider = new UTSCXProvider()
- UTSVoipMgr.endCall({
- uuid: uni.getStorageSync("voip_UUID")
- }, (resp: any)=>{
- console.log(JSON.stringify(resp))
- })
- }
- initData();
- getfriendMsg();
- //audioObjstart();
- setTimeout(function() {
- // 这里写要延时执行
- if(isCaller.value){//主动发起通话
- }
- else{
- acceptWebrtc();//自动接听
- }
- }, 1500);
- }
- }
- else{
- initData();
- getfriendMsg();
- setTimeout(function() {
- // 这里写要延时执行
- if(isCaller.value){//主动发起通话
- }
- else{
- acceptWebrtc();//自动接听
- }
- }, 1500);
- }
-
- // console.log('getApplicationstate2-------',state);
-
- })
- onReady(()=>{
- console.log('onReady');
- chaoshipanduan();
- setTimeout(function() {
- // 这里写要延时执行的代码
- if(showVideo.value){
- console.log('onReady1');
- webRTC.setSpeakerEnable(true)
- speacker.value=true;
- }
- else{
- console.log('onReady2');
- webRTC.setSpeakerEnable(false)
- }
- }, 300);
- });
- onLoad((opt) => {
- console.log('onLoad')
- usePeerStore().updateBusyStatus(true)
- usePeerStore().updateCloseStatus(false)
- videocanOpen.value=false;
- if(typeof opt?.isCaller === 'string'){
- isCaller.value = opt?.isCaller === 'true'
- if(isCaller.value){
- canClose.value = true;
- }
- console.log('isCaller',canClose);
- }
- if(typeof opt?.showVideo === 'string'){
- showVideo.value = opt?.showVideo === 'true'
- }
- candidateList=[];
- friendId.value = opt?.friendId;
- audioObjstart();
-
- // 开始本地抓流
- if (uni.getSystemInfoSync().platform == "ios") {
- videocanOpen.value=true;
- }
- else{
- requestPermission([
- "android.permission.CAMERA",
- "android.permission.RECORD_AUDIO"
- ])
- }
-
- });
-
- onUnload(()=>{
- clearInterval(timer.value);//正常接通
- audioObjstop();
- if(!hadClose.value){
- closeWebrtc();
- }
- webRTC.destroyAllPeerConnection();
- peerStore.setCallId(undefined);
- peerStore.setOffer(undefined);
- peerStore.setAnswer(undefined);
- peerStore.setCandidate(undefined);
- peerStore.updateBusyStatus(false);
- peerStore.updateCloseStatus(false);
- peerStore.setIsAccept(false);
- });
- const requestPermission = (permissions:any) =>{
- plus.android.requestPermissions(
- permissions,
- function(resultObj) {
- for (var i = 0; i < resultObj.granted.length; i++) {
- var grantedPermission = resultObj.granted[i];
- androidpermission.value=true;
- console.log('已获取的权限:' + grantedPermission);
- if(grantedPermission=='android.permission.CAMERA'){
- webRTC.startVideoCapture({
- isFront:true,
- width: 1280,
- height: 720,
- fps: 30
- })
- }
- }
- for (var i = 0; i < resultObj.deniedPresent.length; i++) {
- var deniedPresentPermission = resultObj.deniedPresent[i];
- console.log('拒绝本次申请的权限:' + deniedPresentPermission);
- }
- for (var i = 0; i < resultObj.deniedAlways.length; i++) {
- var deniedAlwaysPermission = resultObj.deniedAlways[i];
- console.log('永久拒绝申请的权限:' + deniedAlwaysPermission);
- }
- // 若所需权限被永久拒绝,则打开APP设置界面,可以在APP设置界面打开相应权限
- if (resultObj.deniedAlways.length > 0) {
- // var Intent = plus.android.importClass("android.content.Intent");
- // var Settings = plus.android.importClass("android.provider.Settings");
- // var Uri = plus.android.importClass("android.net.Uri");
- // var mainActivity = plus.android.runtimeMainActivity();
- // var intent = new Intent();
- // intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
- // var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
- // intent.setData(uri);
- // mainActivity.startActivity(intent);
- }
- },
- function(error) {
- console.log('申请权限错误:' + error.code + " = " + error.message);
- });
- }
-
- const initData = () =>{
- console.log('initWebRTC')
- // 设置webRTC的回调
- webRTC.onCallback((resp:any) => {
- let opt = resp.opt
- console.log("webRTC.onCallback opt:" + opt)
- switch (opt) {
- // 信令状态改变
- case "onSignalingChange": {
- console.log("onSignalingChange:" + JSON.stringify(resp))
- let state = resp.state
- if (state) {
- switch (state) {
- case 0: {
- console.log("RTCSignalingStateStable")
- }
- break;
- case 1: {
- console.log("RTCSignalingStateHaveLocalOffer")
- }
- break;
- case 2: {
- console.log("RTCSignalingStateHaveLocalPrAnswer")
- }
- break;
- case 3: {
- //
- console.log("RTCSignalingStateHaveRemoteOffer")
- }
- break;
- case 4: {
- console.log("RTCSignalingStateHaveRemotePrAnswer")
- }
- break;
- case 5: {
- console.log("RTCSignalingStateClosed")
- let userId = resp.userId
- if (userId) {
- //this.userLeave(userId)
- }
- }
-
- break;
- default:
- break;
- }
- }
- }
- break;
- case "onIceGatheringChange": {
- console.log("onIceGatheringChange:" + JSON.stringify(resp))
- let state = resp.state
- if (state) {
- switch (state) {
- case 0: {
- console.log("RTCIceGatheringStateNew")
- }
- break;
- case 1: {
- console.log("RTCIceGatheringStateGathering")
- }
- break;
- case 2: {
- console.log("RTCIceGatheringStateComplete")
- }
- break;
- default:
- break;
- }
- }
- }
- break;
- // 生成IceCandidate
- case "onIceCandidate": {
- console.log("onIceCandidate",resp)
- let candidate = resp.iceCandidate
- let data = {
- candidate: candidate.sdp,
- sdpMLineIndex: candidate.sdpMLineIndex,
- sdpMid: candidate.sdpMid,
- }
- candidateList.push(data);
- }
- break;
- case "onIceConnectionChange": {
- console.log("onIceConnectionChange:" + JSON.stringify(resp))
- let state = resp.state
- switch (state) {
- case 0: {
- console.log("RTCIceConnectionStateNew")
- }
- break;
- case 1: {
- console.log("RTCIceConnectionStateChecking")
- }
- break;
- case 2: {
- // 这步没有
- console.log("RTCIceConnectionStateConnected");
- stateNote.value ='已连接';
- isConnect.value=true;
- audioObjstop();
- console.log('------1',showVideo.value,videoIsOpen.value)
- if(showVideo.value&&!videoIsOpen.value&&videocanOpen.value){//打开视频
- let users=[];
- users.push(friendId.value)
- peerStore.setUsers(JSON.stringify(users));
- videoIsOpen.value=true;
- webRTC.setSpeakerEnable(true)
- console.log('------2',showVideo.value,videoIsOpen.value)
- uni.navigateTo({
- url:'/imcall/webRTCVideoView?friendId='+friendId.value
- })
- }
- }
- break;
- case 3: {
- console.log("RTCIceConnectionStateCompleted")
- }
- break;
- case 4: {
- console.log("RTCIceConnectionStateFailed")
- stateNote.value ='连接已断开';
-
- }
- break;
- case 5: {
- // 通讯被断开,一般是对方掉线或者STUN/TURN 服务器问题:如果 ICE 服务器配置不当,或者 STUN/TURN 服务器不可用,可能会导致连接失败。确保你的 STUN/TURN 服务器正常工作并且可达。
- stateNote.value ='连接已断开';
- console.log("RTCIceConnectionStateDisconnected")
- let data={
- type:'state',
- stateNote:stateNote.value
- }
- uni.$emit('webRTCvideoE', { msg:JSON.stringify(data)});
- let userId = resp.userId
- if (userId) {
- //this.userLeave(userId)
- }
- }
- break;
- case 6: {
- console.log(" RTCIceConnectionStateClosed")
- stateNote.value ='连接已断开';
- let userId = resp.userId
- if (userId) {
- //this.userLeave(userId)
- }
- }
- break;
- case 7: {
- console.log(" RTCIceConnectionStateCount")
- }
- break;
- default:
- break;
- }
-
- }
-
- break;
- // 收到其他用户的音频或视频流
- case "onAddStream": {
- let userId = resp.userId
- console.log("onAddStream:"+JSON.stringify(resp))
- if (userId) {
- let stream = resp.stream
- if (stream) {
- // 如果有视频流,则显示其他用户的视频
- let videoTracks = stream.videoTracks
- if (videoTracks) {
- if (videoTracks.length > 0) {
- let users=[];
- users.push(friendId.value);
- let data={
- type:'users',
- users:users
- }
- uni.$emit('webRTCvideoE', { msg:JSON.stringify(data)});
- // let exist = this.existUser(userId)
- // if (!exist) {
- // console.log("显示远程视频流:" + userId)
- // this.$refs.remoteView.renderRemoteVideo(userId)
- // // this.otherPersons.push({
- // // userId: userId
- // // })
- // }
- }
- }
- }
- }
-
- }
- break;
- case "onRemoveStream": {
-
- }
- break;
-
- default:
- break;
- }
- })
- console.log('initWebRTC11')
- // 初始化视频
- webRTC.initVideoTrack({
- trackId: "video0",
- isScreencast: false // 仅对Android生效
- })
- // 初始化音频
- webRTC.initAudioTrack({
- trackId: "audio0"
- })
- console.log('initWebRTC22')
- if (uni.getSystemInfoSync().platform == "ios") {
- webRTC.configureAudioSession({
- category: "playAndRecord",
- mode: "voiceChat"
- })
- } else {
-
- }
- // 开始本地抓流
- if (uni.getSystemInfoSync().platform == "ios") {
- webRTC.startVideoCapture({
- isFront:true,
- width: 1280,
- height: 720,
- fps: 30
- })
- }
- };
-
- const getfriendMsg = () => {
- UserApi.getUser(friendId.value).then((res) => {
- friend.value = res.data
- if (friend.value) {
- friendName=friend.value.name;
- friendAvatar=encodeURI(friend.value.avatar);
- if(isCaller.value){//主动发起通话
- sendcallingMsg();
- }
- else{
- //acceptWebrtc();//自动接听
- }
- }
- })
- }
-
- const changeSpeack = () => {
- if(speacker.value){
- speacker.value=false;
- }
- else{
- speacker.value=true;
- }
- console.log('setAudioEnabled',speacker.value)
- webRTC.setSpeakerEnable(speacker.value)
- }
-
- const acceptWebrtc = () => {
- console.log('acceptWebrtc');
- //给自己发一份忙碌状态,多个客户端同一个人不能同时接受,需要客户端接受后,其他客户端就关闭
- let data={
- code: SendCode.WEBRTC_BUSY,
- message: {
- chatId:friendId.value,
- fromId: user.id,
- type: ChatType.FRIEND,
- msgtype:'accept',
- video: showVideo.value,
- }
- }
- console.log(data);
- useWsStore().send(JSON.stringify(data));
- canClose.value = true;
- }
- const closeWebrtcBT = () => {
- uni.navigateBack();
- }
- const closeWebrtc = () => {
- if (user.id) {
- const closeMessage = {
- code: SendCode.WEBRTC_CLOSE,
- message: {
- chatId:friendId.value,
- fromId: user.id,
- timestamp: new Date().getTime(),
- type: ChatType.FRIEND,
- msgtype:'close'
- }
- }
- wsStore.send(JSON.stringify(closeMessage))
- hadClose.value=true;
- console.log('发送关闭消息', closeMessage)
- //发起方才有发送视频结果消息的权限
- if (isCaller.value) {
- //界面展示视频消息情况,例如:对方是否接受了视频通话,通话时长
- const message= {
- id:null,
- localtime:null,
- mine:true,
- messageType:SendCode.WEBRTC_result,
- chatId:friendId.value,
- fromId: user.id,
- timestamp: new Date().getTime(),
- type: ChatType.FRIEND,
- result: isConnect.value,
- video: showVideo.value,
- duration: isConnect.value ? new Date().getTime() - startTime.value : 0
- }
- console.log(message)
- wsStore.sendWEBRTCresult(message);
- }
- }
- }
- const sendSocketData = (data:any) => {
- wsStore.sendWEBRTC(data)
- console.log('发送消息', data);
- }
-
- const sendCandidate = () =>{
- let msg: Webrtc = {
- chatId: friendId.value,
- fromId: user.id,
- type: ChatType.FRIEND,
- msgtype:'candidate',
- conetType:showVideo.value,
- payload:JSON.stringify(candidateList)
- }
- console.log("将本机candidate发送给对方")
- sendSocketData(msg);
- }
-
- //主动发起通话操作,isCaller为true-----------------------------
- const sendcallingMsg = () => {
- console.log('sendcallingMsg');
- let msg: Webrtc = {
- chatId:friendId.value,
- fromId: user.id,
- type: ChatType.FRIEND,
- msgtype:'calling',
- conetType:showVideo.value,
- timestamp: new Date().getTime(),
- payload:''
- }
- let data={
- code:SendCode.WEBRTC_CALL,
- message: msg
- }
- console.log('sendcallingMsg',data);
- useWsStore().send(JSON.stringify(data))
- }
- // 创建与某个用户的连接
- const createPeerConnection = (userId:any) => {
- let hasPeerConnection = webRTC.hasPeerConnection({
- userId: userId
- })
- if (!hasPeerConnection) { // 如果没有连接则创建连接
- console.log("当前用户没有连接,正在创建")
-
- let params = {
- iceServers:[],
- sdpSemantics:1,
- continualGatheringPolicy:1,
- constraints:{},
- userId:''
- }
-
- params.iceServers = [{
- urls: ["stun:203.175.169.52:3478",
- "turn:203.175.169.52:3478"
- ],
- username: 'aaaaa',
- credential: 'bbbbb'
- }
- ]
-
- params.userId = userId;
- params.sdpSemantics = 1 // 0: RTCSdpSemanticsPlanB 1:RTCSdpSemanticsUnifiedPlan
- params.continualGatheringPolicy =
- 1 // 0: RTCContinualGatheringPolicyGatherOnce 1: RTCContinualGatheringPolicyGatherContinually
- params.constraints = {
- mandatory: {},
- optional: {
- DtlsSrtpKeyAgreement: "true"
- }
- }
- userId = webRTC.createPeerConnection(params)
- // 给连接添加本地视频
- console.log("添加本地视频")
- let videoResp = webRTC.addVideoTrack({
- userId: userId,
- streamIds: ["video0"]
- })
- let videoFlag = videoResp.flag
- if (!videoFlag) {
- console.log("添加本地视频出错:" + JSON.stringify(videoFlag))
- }
- // 给连接添加本地音频
- console.log("添加本地音频")
- let audioResp = webRTC.addAudioTrack({
- userId: userId,
- streamIds: ["audio0"]
- })
- let audioFlag = audioResp.flag
- if (!audioFlag) {
- console.log("添加本地音频出错:" + JSON.stringify(videoFlag))
- }
- } else {
- console.log("已经有连接,无需创建")
- }
- };
-
- const getoffer = () => {
- // var videoV="false";
- // if(showVideo.value){
- // videoV="true";
- // }
- console.log('getoffer')
- webRTC.createOffer({
- userId:friendId.value,
- setLocalDescription: false
- }, (resp:any) => {
- console.log(resp);
- let flag = resp.flag
- if (flag) {
- let sessionDescription = resp.sessionDescription
- let type = sessionDescription.type
- let sdp = sessionDescription.sdp
- console.log('sessionDescription',sessionDescription)
-
- webRTC.setLocalDescription({
- userId: friendId.value,
- type: type,
- sdp: sdp
- }, (localDescResp:any) => {
- let localFlag = localDescResp.flag
- console.log('setLocalDescription',localFlag)
- })
-
- let data = {
- type: "SessionDescription",
- payload: {
- sdp:sdp,
- type: type
- }
- }
- let msg: Webrtc = {
- chatId: friendId.value,
- fromId: user.id,
- type: ChatType.FRIEND,
- msgtype:'offer',
- conetType:showVideo.value,
- payload:JSON.stringify(data.payload)
- }
- // 发送给接听方
- sendSocketData(msg)
- }
- }
- )
-
- }
-
- //收到answer
- const recAnswer = () => {
- let answer=JSON.parse(peerStore.offer)
- console.log('answeroffer1----',answer);
- createPeerConnection(friendId.value)
- webRTC.setRemoteDescription({
- userId: friendId.value,
- type: "answer",
- sdp: answer.sdp
- }, (resp) => {
- let flag = resp.flag
- console.log('answeroffer2----',resp);
- if(flag){
- sendCandidate();
- }
- else{
- console.log("receiveAnswer setRemoteDescription error:" + JSON.stringify(resp))
- }
- })
-
- }
-
- //被动接听通话操作,isCaller为false-----------------------------
- //收到recOffer
- const recOffer = () => {
- let payload=JSON.parse(peerStore.offer);
- createPeerConnection(friendId.value)
- // 设置远程Description
- console.log("设置远程Description type:",payload)
- webRTC.setRemoteDescription({
- userId: friendId.value,
- type: payload.type,
- sdp: payload.sdp
- }, (resp) => {
- let flag = resp.flag
- if (flag) {
- console.log("生成answer")
- // 生成answer
- webRTC.createAnswer({
- userId: friendId.value,
- setLocalDescription: false
- }, (answerResp:any) => {
- let flag = answerResp.flag
- if (flag) {
- // console.log("createAnswer result:" + JSON.stringify())
- let sessionDescription = answerResp.sessionDescription
- let type = sessionDescription.type
- let sdp = sessionDescription.sdp
- // 设置本地Description
- console.log("设置setLocalDescription")
- webRTC.setLocalDescription({
- userId: friendId.value,
- type: type,
- sdp: sdp
- }, (localDescResp:any) => {
- let localFlag = localDescResp.flag
- if (localFlag) {
- // 将answer发送给对方
- let data = {
- type: "SessionDescription",
- payload: {
- sdp:sdp,
- type: type
- }
- }
- // 发送给呼叫方
- let msg: Webrtc = {
- chatId:friendId.value,
- fromId:user.id,
- type: ChatType.FRIEND,
- msgtype:'answer',
- conetType:showVideo.value,
- payload:JSON.stringify(data.payload)
- }
- console.log('answer',msg)
- sendSocketData(msg)
- } else {
- console.log("setLocalDescription error:" + JSON
- .stringify(
- localDescResp))
- }
- })
- } else {
- console.log("createAnswer error:" + JSON.stringify(resp))
- }
- })
-
- } else {
- console.log("setRemoteDescription error:")
- }
- })
- }
-
- const recCandidate = (data:any) => {
-
- let hasPeerConnection = webRTC.hasPeerConnection({
- userId: friendId.value
- })
- if (!hasPeerConnection) {
- return
- }
-
- data.forEach((item) => {
- console.log("添加远程IceCandidate:",item)
- // 添加远程IceCandidate
- webRTC.addIceCandidate({
- userId: friendId.value,
- sdpMid:item.sdpMid,
- sdpMLineIndex: item.sdpMLineIndex,
- sdp: item.candidate
- }, (resp:any) => {
- let flag = resp.flag
- if (!flag) {
- console.log("addIceCandidate error:" + JSON.stringify(resp))
- }
- })
- })
- videocanOpen.value=true;
- }
-
- // const answer = () => {
- // var videoV="false";
- // if(showVideo.value){
- // videoV="true";
- // }
- // webRTC.answer({
- // OfferToReceiveAudio: "true",
- // OfferToReceiveVideo:videoV
- // }, (resp) => {
- // let flag = resp.flag
- // if (flag) {
- // let sdp = resp.sdp
- // let type = ""
- // switch (sdp.type) {
- // case 0:
- // type = "offer"
- // break;
- // case 1:
- // type = "prAnswer"
- // break;
- // case 2:
- // type = "answer"
- // break;
- // case 3:
- // type = "rollback"
- // break;
- // default:
- // break;
- // }
- // let data = {
- // type: "SessionDescription",
- // payload: {
- // sdp: sdp.sdp,
- // type: type
- // }
- // }
- // // 发送给呼叫方
- // let msg: Webrtc = {
- // chatId:friendId.value,
- // fromId:user.id,
- // type: ChatType.FRIEND,
- // msgtype:'answer',
- // conetType:showVideo.value,
- // payload:JSON.stringify(data.payload)
- // }
- // console.log('answer',msg)
- // sendSocketData(msg)
- // } else {
- // console.log(resp)
- // }
- // })
- // }
-
-
- </script>
- <style>
- .AvatarImg{
- margin-top: 40rpx;
- width: 160rpx;
- height: 160rpx;
- border-radius: 10rpx;
- }
- .IncolumnC{
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content:center;
- }
- .InrowC{
- display: flex;
- flex-direction:row;
- align-items: center;
- justify-content:center;
- }
- </style>
|