rtc.vue 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  1. <template>
  2. <div align="center" class="rtc-page cover-bg" :style="{height: pageData.height + 'px'}">
  3. <!-- video 容器 -->
  4. <div class="video-wrapper" id="videoRef" :style="{width: pageData.videoWidth + 'px', height: pageData.videoHeight + 'px'}"></div>
  5. <!-- 三menu键 -->
  6. <div id="foot-menu-wrap" :style="`height: ${pageData.footMenuHeight}px`">
  7. <div @click.stop="sendKey(187)"><van-icon name="wap-nav" size="24px"/></div>
  8. <div @click.stop="sendKey(3)"><van-icon name="wap-home-o" size="24px"/></div>
  9. <div @click.stop="sendKey(4)"><van-icon name="arrow-left" size="24px"/></div>
  10. </div>
  11. <!-- 悬浮按钮 -->
  12. <FloatBtn :width="pageData.width" :height="pageData.height" :latency="rtcNetwork.currentRoundTripTime" @onClick="levitatedSphereVisible = true"/>
  13. <!-- 左侧popup -->
  14. <LeftMenuPopup
  15. ref="leftMenuPopupRef"
  16. :engine="engine"
  17. :userCardId="this.parametersData.userCardId"
  18. :levitatedSphereVisible.sync="levitatedSphereVisible"
  19. :latency="rtcNetwork.currentRoundTripTime"
  20. @shearplate="shearplate"
  21. @funcHandle="funcHandle"
  22. @exit="exit"
  23. />
  24. <!-- 右侧popup -->
  25. <!-- <RightPopup ref="rightPopupRef" :engine="engine" :userCardId="this.parametersData.userCardId" :levitatedSphereVisible.sync="levitatedSphereVisible" @shearplate="shearplate" @exit="exit"/> -->
  26. <!-- 输入并复制到粘贴板 -->
  27. <InputCopy ref="inputCopyRef" @openPasteboard="openPasteboard"/>
  28. <!-- 云机内部的粘贴板内容 -->
  29. <CloudPhoneClipboard ref="cloudPhoneClipboardRef" :doConnectDirectivesWs="doConnectDirectivesWs"/>
  30. <!-- 超时无操作 -->
  31. <TimeoutNoOps ref="timeoutNoOpsRef" />
  32. <!-- 计时卡计时 | 计费规则 | 应用推荐 -->
  33. <TimeBalance ref="timeBalanceRef" :parametersData="parametersData" @downline="$refs.rightPopupRef.downline()"/>
  34. </div>
  35. </template>
  36. <script>
  37. import meta from './config/meta.js';
  38. import request from './config/request.js';
  39. import logReport from './config/logReport.js';
  40. import publicMixin from './mixins/public.js';
  41. import * as uni from '../../static/static/js/uni.webview.1.5.2.js';
  42. import FloatBtn from './components/FloatBtn.vue';
  43. import RightPopup from './components/RightPopup.vue';
  44. import LeftMenuPopup from './components/LeftMenuPopup.vue';
  45. import InputCopy from './components/InputCopy.vue';
  46. import CloudPhoneClipboard from './components/CloudPhoneClipboard.vue';
  47. import TimeoutNoOps from './components/TimeoutNoOps.vue';
  48. import TimeBalance from './components/TimeBalance.vue';
  49. /**
  50. * @description: 判断当前页面运行环境
  51. * @return {Object} 返回当前页面运行环境
  52. */
  53. const isBrowserEnvironment = function() {
  54. // 判断是否在浏览器环境中
  55. const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && typeof navigator !== 'undefined';
  56. // 判断是否在微信环境中
  57. const isWechat = /MicroMessenger/i.test(navigator.userAgent);
  58. // 判断是否在微信小程序的 web-view 中
  59. const isMiniProgramWebview = isWechat && /miniProgram/i.test(navigator.userAgent);
  60. // 判断是否是 iPhone 设备
  61. const isIPhone = /iPhone/i.test(navigator.userAgent);
  62. // 判断是否是顶级窗口(不是嵌套在 iframe 中)目前只有ios的浏览器中才会是顶级窗口
  63. const isTopWindow = window.parent === window.self;
  64. return {
  65. isBrowser, // 是否在浏览器环境中
  66. isWechat, // 是否在微信环境中
  67. isMiniProgramWebview, // 是否在微信小程序的 web-view 中
  68. isIPhone, // 是否是 iPhone 设备
  69. isTopWindow, // 是否是顶级窗口
  70. };
  71. }
  72. export default {
  73. auth: false,
  74. name: 'webRTC',
  75. layout: 'cloudPhone',
  76. components: {
  77. FloatBtn,
  78. RightPopup,
  79. InputCopy,
  80. CloudPhoneClipboard,
  81. TimeoutNoOps,
  82. TimeBalance,
  83. LeftMenuPopup,
  84. },
  85. head() {
  86. return {
  87. title: '云手机',
  88. meta: [ ...meta ],
  89. script: [
  90. {
  91. // ./ 路径指向nuxt.config.js同级目录的static文件夹
  92. src: './rtcEngine/config/js/SDK.min.js', // sdk 2.0文件
  93. type: 'text/javascript',
  94. async: false,
  95. defer: false,
  96. onload: '$_script_loadHandler()', // 加载成功回调created生命周期中定义的方法
  97. onerror: '$_script_errHandler()', // 加载失败回调created生命周期中定义的方法
  98. },
  99. // {
  100. // // ./ 路径指向nuxt.config.js同级目录的static文件夹
  101. // src: './static/js/uni.webview.1.5.2.js', // uniapp webview 1.5.2文件
  102. // type: 'text/javascript',
  103. // async: true,
  104. // defer: false,
  105. // onload: '$_script_uni_loadHandler()', // 加载成功回调created生命周期中定义的方法
  106. // }
  107. ]
  108. }
  109. },
  110. mixins: [publicMixin],
  111. data() {
  112. return {
  113. // 日志上报实例
  114. logReportObj: null,
  115. // SDK加载状态
  116. sdkLoadStatus: 'loading', // sdk 加载状态 [loading|success|error]
  117. // 页面数据
  118. pageData: {
  119. width: 0, // 页面宽度
  120. height: 0, // 页面高度
  121. footMenuHeight: 40, // 底部菜单高度
  122. videoWidth: 0, // 视频宽度
  123. videoHeight: 0, // 视频高度
  124. },
  125. // 是否支持webRTC
  126. isSupportRtc: !!(
  127. typeof RTCPeerConnection !== 'undefined' &&
  128. typeof RTCIceCandidate !== 'undefined' &&
  129. typeof RTCSessionDescription !== 'undefined'
  130. ),
  131. // url 问号后的参数
  132. parametersData: {
  133. /**
  134. * @description: 传递的参数
  135. * @param {String} record 数据id
  136. * @param {Number} userCardId 云机的id
  137. * @param {String} mealType 云机套餐类型 eg: VIP、STARBALL...
  138. * @param {Number} sourceType 云机来源: 0:购买 1试用 2:免费激活码 3:免费活动抽奖 4:ar app注册 5:9.9元套餐年卡 ',
  139. * @param {Number} userCardType 云机的类型 0 普通套餐 1、2、3:年卡、普通计时、自动续费普通计时
  140. * @param {Number} validTime 卡的有效期
  141. * @param {String} rm 卡所在的机房
  142. * @param {Number} isShowCountdown 是否显示倒计时 0:否 1:是
  143. * @param {Number} isShowRule 是否显示规则 0:否 1:是
  144. * @param {Number} timingStatus 卡的计时状态 0:停止计时 1:开始计时 2:待确认开始计时"
  145. * @param {String} isFirstConnect 是否是首次连接
  146. * @param {Number} authPhone 0自身购买的云手机 1获取得到的云手机
  147. * @param {String} username 用户名
  148. * @param {String} token token
  149. * @param {Number} isTips 是否显示提示 0:否 1:是
  150. * @param {Number} isWeixin 是否是微信小程序环境 0:否 1:是
  151. * @param {String} merchantSign 商户标识
  152. */
  153. },
  154. // 卡的连接信息
  155. connectData: {},
  156. // 云手机引擎 播放器实例
  157. engine: {},
  158. rtcNetwork: {
  159. currentRoundTripTime: 0, // 当前往返时间(网络延迟)
  160. }, // webRtc网络分析数据
  161. doConnectDirectivesWs: null, // 云手机指令通道
  162. doConnectDirectivesIntervalerPing: null, // 业务通道定时标识 云手机指令通道心跳
  163. doConnectDirectivesRequestNum: 1, // 业务通道重连次数
  164. doConnectDirectivesRequestNumMax: 6, // 业务通道重连次数上限
  165. // 右侧popup显隐
  166. levitatedSphereVisible: false,
  167. }
  168. },
  169. // 页面初始化后触发
  170. async fetch() {
  171. // 获取页面传递参数
  172. this.parametersData = this.$route.query;
  173. this.getCloudList();
  174. this.getMealIconInfo();
  175. },
  176. computed: {
  177. // 是否为微信浏览器环境
  178. isWeChatBrowser() {
  179. return this.$userAgent.isWx;
  180. },
  181. },
  182. created() {
  183. this.$toast.loading({
  184. duration: 0, // 持续展示 toast
  185. message: '数据加载中...',
  186. });
  187. // 设置html标签的背景为黑色
  188. document.body.style.background = '#000';
  189. // 定义全局变量 用于监听sdk加载状态
  190. window.$_script_loadHandler = async ()=> {
  191. console.log('$_script_loadHandler: SDK加载成功');
  192. this.sdkLoadStatus = 'success';
  193. // 初始化日志上报
  194. this.initLogReport();
  195. // 调用接口获取卡连接数据
  196. const cardData = await this.getConnectData(this.parametersData);
  197. // 判断卡的连接方式
  198. const connectData = await this.judgeConnectType(cardData);
  199. // 保存卡连接信息
  200. this.connectData = connectData;
  201. this.initWebRtc();
  202. };
  203. window.$_script_errHandler = ()=> {
  204. console.log('SDK加载失败');
  205. this.sdkLoadStatus = 'error';
  206. }
  207. },
  208. mounted() {
  209. // 获取窗口尺寸
  210. this.getInitSize();
  211. window.onresize = () => {
  212. console.log('窗口尺寸变化');
  213. this.getInitSize()
  214. };
  215. // 初始化页面监听事件
  216. this.initListener();
  217. },
  218. // 页面销毁前触发
  219. beforeDestroy() {
  220. // 销毁页面监听事件
  221. this.destroyListener();
  222. },
  223. methods: {
  224. // 初始化页面监听事件
  225. initListener() {
  226. // 禁止双击缩放
  227. document.addEventListener('dblclick', this.preventDefault);
  228. // 添加监听 页面显示或隐藏 事件
  229. document.addEventListener('visibilitychange', this.visibilitychanged);
  230. },
  231. // 销毁页面监听事件
  232. destroyListener() {
  233. // 允许双击缩放
  234. document.removeEventListener('dblclick', this.preventDefault);
  235. // 移除监听 页面显示或隐藏 事件
  236. document.removeEventListener('visibilitychange', this.visibilitychanged);
  237. },
  238. // 阻止默认事件
  239. preventDefault(e) {
  240. e.preventDefault();
  241. },
  242. // 监听 页面显示或隐藏 执行的函数
  243. visibilitychanged() {
  244. // 获取当前环境
  245. const env = isBrowserEnvironment();
  246. // 获取当前页面的可见性状态
  247. const visibilityState = document.visibilityState;
  248. if (visibilityState === 'visible') {
  249. // 页面显示时的逻辑
  250. // 网页重载
  251. if (env.isBrowser && env.isTopWindow && env.isIPhone) {
  252. location.reload();
  253. }
  254. } else if (visibilityState === 'hidden') {
  255. // 页面隐藏时的逻辑
  256. // video.pause();
  257. } else if (visibilityState === 'prerender') {
  258. // 页面预渲染时的逻辑
  259. console.log('页面处于预渲染状态');
  260. } else if (visibilityState === 'unloaded') {
  261. // 页面即将卸载时的逻辑 移除监听
  262. document.removeEventListener('visibilitychange', this.visibilitychanged);
  263. }
  264. },
  265. // 获取初始化尺寸
  266. getInitSize() {
  267. // 获取窗口尺寸
  268. this.pageData.height = window.innerHeight;
  269. this.pageData.width = window.innerWidth;
  270. // 计算视频尺寸 webRTC需要做成16:9的画面
  271. let videoWidth = this.pageData.width;
  272. let videoHeight = this.pageData.height - this.pageData.footMenuHeight;
  273. // 计算当前视口的宽高比
  274. const currentRatio = videoWidth / videoHeight;
  275. console.log(`当前视口的宽高比: ${currentRatio}`);
  276. // 9:16 的目标比例
  277. const targetRatio = 9 / 16;
  278. // 判断当前视口的宽高比与目标比例的关系
  279. if (currentRatio > targetRatio) {
  280. // 当前视口的宽高比大于目标比例,说明宽度“过宽”,需要以高度为基准
  281. console.log("当前视口宽度过宽,应以高度为基准调整宽度");
  282. this.pageData.videoWidth = videoHeight * targetRatio;
  283. this.pageData.videoHeight = videoHeight;
  284. console.log(`1目标: 宽${this.pageData.videoWidth},高${this.pageData.videoHeight}`);
  285. } else {
  286. // 当前视口的宽高比小于目标比例,说明高度“过高”,需要以宽度为基准
  287. console.log("当前视口高度过高,应以宽度为基准调整高度");
  288. this.pageData.videoWidth = videoWidth;
  289. this.pageData.videoHeight = videoWidth / targetRatio;
  290. console.log(`2目标: 宽${this.pageData.videoWidth},高${this.pageData.videoHeight}`);
  291. }
  292. },
  293. // 获取卡的信息
  294. async getConnectData(params) {
  295. let userCardId = params.userCardId;
  296. try {
  297. // 设置上报参数
  298. this.logReportObj.setParams({userCardId});
  299. let isWx = this.$userAgent.isWx;
  300. let { isWeixin } = params;
  301. let clientType = (+isWeixin || isWx) ? 'wx' : undefined;
  302. // 设置上报参数
  303. this.logReportObj.setParams({userCardId});
  304. clientType && this.logReportObj.setParams({clientType});
  305. const res = await this.$axios.$post('/resources/user/cloud/connect', { userCardId }, {
  306. headers: {
  307. merchantSign: params.merchantSign,
  308. },
  309. });
  310. if (!res.success) {
  311. // 设置日志 推流状态为失败,和链接状态
  312. this.logReportObj.setParams({plugFowStatus: 2, linkWay: this.logReportObj.RESPONSE_CODE[res.status] || 0, linkEndTime: this.logReportObj.formatDate(new Date())});
  313. // 日志上报
  314. this.logReportObj.collectLog(
  315. `接口获取数据失败:
  316. url: /api/resources/user/cloud/connect
  317. method: post
  318. 参数: ${JSON.stringify({ userCardId })}
  319. 响应: ${JSON.stringify(res)}`
  320. );
  321. // res.status状态码枚举值 0: 正常
  322. const statusEnum = {
  323. // 5200:RBD资源挂载中
  324. 5200: '网络异常,请稍后重试',
  325. // 入使用排队9.9,年卡
  326. 5220: '云手机正在一键修复中',
  327. 5203: '正在排队中,请稍等',
  328. // 9.9年卡连接异常,重新进入排队
  329. 5204: '云机异常,正在为你重新分配云机',
  330. 5228: '卡的网络状态为差',
  331. 5229: '接口返回链接信息缺失',
  332. };
  333. // NOTE 这里可设置重连机制, 重连次数上限6次, 每次重连间隔3秒, 暂不做重连
  334. // 提示错误信息
  335. this.$toast(statusEnum[res.status] || '网络异常,请稍后重试');
  336. return Promise.reject(new Error(statusEnum[res.status] || '网络异常,请稍后重试'));
  337. }
  338. return res.data;
  339. }catch (error) {
  340. // 设置上报参数
  341. this.logReportObj.setParams({linkWay: 4, plugFowStatus: 2, linkEndTime: this.logReportObj.formatDate(new Date())});
  342. // 日志上报
  343. this.logReportObj.collectLog(
  344. `接口获取数据失败:
  345. url: /api/resources/user/cloud/connect
  346. method: post
  347. 参数: ${JSON.stringify({ userCardId })}
  348. 响应: ${JSON.stringify(error)}`
  349. );
  350. console.log('error connectAxios:', error);
  351. return Promise.reject(error);
  352. }
  353. },
  354. // 判断卡的连接方式
  355. async judgeConnectType(cardData) {
  356. try {
  357. // 设置上报参数
  358. this.logReportObj.setParams({videoType: cardData.videoCode.toLowerCase(), resourceId: cardData.resourceId});
  359. // 不支持webRTC跳转到指定的页面进行拉流
  360. if (!cardData.isWebrtc) {
  361. // 关闭日志上报
  362. this.logReportObj.destroy();
  363. // 跳转指定页面
  364. location.replace(`${location.origin}/h5/webRtcYJ/WXtrialInterface.html${location.search}`)
  365. return Promise.reject();
  366. }
  367. // 是否支持webRTC
  368. if (!this.isSupportRtc) {
  369. // 设置日志 推流状态为失败
  370. this.logReportObj.setParams({plugFowStatus: 2, linkEndTime: this.logReportObj.formatDate(new Date())});
  371. // 日志上报
  372. this.logReportObj.collectLog(`${+this.parametersData.isWeixin ? '微信小程序' : ''}当前版本暂不支持使用`);
  373. this.$dialog.alert({
  374. title: '提示',
  375. message: '当前环境不支持使用,可下载谷歌浏览器或客户端进行使用',
  376. confirmButtonText: '确定',
  377. confirmButtonColor: '#3cc51f',
  378. callback: (_, done) => {
  379. done();
  380. this.exit();
  381. }
  382. })
  383. return Promise.reject(new Error('当前浏览器不支持webRTC'));
  384. }
  385. // webRtc连接,需获取连接中转地址
  386. if (cardData.webrtcNetworkAnalysis) {
  387. // 如果有网络分析的请求地址, 则请求,否则失败
  388. const { data: webrtcNetworkAnalysisReq }= await request.get(cardData.webrtcNetworkAnalysis); // 这个接口单独使用axios请求, 因为返回的数据跟封装的数据结构不一统一,是其他平台的接口,所以单独请求
  389. if (webrtcNetworkAnalysisReq !== null && webrtcNetworkAnalysisReq.success && webrtcNetworkAnalysisReq.data) {
  390. // 保存获取的连接地址到connect的请求的响应中, 方便后面使用
  391. cardData.webrtcNetwork = webrtcNetworkAnalysisReq.data;
  392. // 设置上报参数
  393. this.logReportObj.setParams({transferServerIp: webrtcNetworkAnalysisReq.data});
  394. return cardData;
  395. }else{
  396. // 设置上报参数
  397. this.logReportObj.setParams({linkWay: 4, plugFowStatus: 2, linkEndTime: this.logReportObj.formatDate(new Date())});
  398. // 日志上报
  399. this.logReportObj.collectLog(
  400. `webRtc连接,获取中转地址失败:
  401. url: ${cardData.webrtcNetworkAnalysis}
  402. method: get
  403. 参数: 无
  404. 响应: ${JSON.stringify(webrtcNetworkAnalysisReq)}`
  405. );
  406. // 弹窗并退出
  407. this.$dialog.alert({
  408. title: '提示',
  409. message: '访问失败,请稍后重试',
  410. confirmButtonText: '确定',
  411. confirmButtonColor: '#3cc51f',
  412. beforeClose: (action, done) => {
  413. done()
  414. this.exit();
  415. }
  416. })
  417. return Promise.reject(new Error('网络分析请求失败'));
  418. }
  419. }else{
  420. // 设置上报参数
  421. this.logReportObj.setParams({linkWay: 4, plugFowStatus: 2});
  422. // 日志上报
  423. this.logReportObj.collectLog(
  424. `webRtc连接,获取请求中转地址为空:
  425. url: /api/resources/user/cloud/connect
  426. method: post
  427. 参数: ${JSON.stringify({ userCardId: this.parametersData.userCardId })}
  428. 响应: ${JSON.stringify(res)}`
  429. );
  430. return Promise.reject(new Error('网络分析请求地址不存在'));
  431. }
  432. } catch (error) {
  433. console.log('判断卡的连接方式', error);
  434. return Promise.reject(error);
  435. }
  436. },
  437. // 初始化webRTC及相关配置
  438. initWebRtc() {
  439. try {
  440. // 获取挂载的容器元素
  441. const videoRef = document.getElementById("videoRef");
  442. // 解构connectData中的数据
  443. const { sn: topic, cardToken: authToken, localIp, internetHttps, internetHttp, webrtcNetwork, webrtcTransferCmnet, webrtcTransferTelecom, webrtcTransferUnicom, videoCode } = this.connectData;
  444. // 判断长连接的协议方式
  445. const isWss = location.protocol === 'https:';
  446. // 生成连接地址
  447. const url = `${isWss ? 'wss://' : 'ws://'}${isWss ? internetHttps : internetHttp}/nats`;
  448. let quality = localStorage.getItem('definitionValue') ?? '自动';
  449. // 统一使用三网解析地址
  450. const ICEServerUrl = [
  451. { "CMNET": webrtcNetwork }, // 移动
  452. { 'CHINANET-GD': webrtcNetwork }, // 电信
  453. { 'UNICOM-GD': webrtcNetwork }, // 联通
  454. ];
  455. // 配置连接参数
  456. const connection = {
  457. mount: videoRef,
  458. displaySize: { // 视频在页面显示的尺寸 必填
  459. width: this.pageData.videoWidth,
  460. height: this.pageData.videoHeight,
  461. },
  462. topic, // SN号 必填
  463. url, //信令服务地址 必填
  464. ICEServerUrl,
  465. forwardServerAddress: '', // 转发服务器地址
  466. ip: localIp, // 实例ip
  467. controlToken: '', // 控制token
  468. width: 720, // 推流视频宽度 必填
  469. height: 1080, // 推流视频高度 必填
  470. cardWidth: 0, // 云机系统分辨率 宽 必填
  471. cardHeight: 0, // 云机系统分辨率 高 必填
  472. cardDensity: 0, // 云机系统显示 密度 必填
  473. authToken, //拉流鉴权 token 必填
  474. quality, // 画质(码率) 超清 | 高清 | 标清 | 流畅
  475. fps: 30, //必填
  476. videoCodec: videoCode, // 视频编码格式 必填
  477. videoCodecMethod: true, // 硬编true | 软编false
  478. isMuted: false, // 是否静音
  479. isAllowedOpenCamera: true, // 是否允许打开摄像头
  480. sendFollow: true, // 是否允许主控转发文本到实例
  481. callback: (event)=> {}
  482. };
  483. // 设置日志参数 推流质量
  484. this.logReportObj.setParams({imageQuality: quality});
  485. // 获取SDK类
  486. const MediaSdk = window.rtc_sdk.MediaSdk;
  487. // 初始化 SDK
  488. this.engine = new MediaSdk();
  489. console.log('RtcEngineConfig==', connection)
  490. // 初始化 SDK 并传入连接参数
  491. this.engine.RtcEngine(connection);
  492. // 监听回调方法
  493. this.eventCallbackFunction();
  494. } catch (error) {
  495. console.log('webRTC初始化失败', error);
  496. }
  497. },
  498. // webRTC状态回调监听回调方法
  499. eventCallbackFunction() {
  500. const engine = this.engine;
  501. // 连接成功
  502. engine.on('CONNECT_SUCCESS', (r) => {
  503. console.log("webrtc连接成功====★★★★★", r);
  504. if (r.code === 1005) { // 1005: 拉流鉴权成功
  505. // 设置日志 推流状态为成功
  506. let now = new Date();
  507. this.logReportObj.setParams({plugFowStatus: 1, linkWay: 1, timeConsuming: now.getTime() - this.logReportObj.timeStartTime, linkEndTime: this.logReportObj.formatDate(now)});
  508. // 日志上报
  509. this.logReportObj.collectLog(`拉流成功`);
  510. // 初始化业务指令通道
  511. this.initControlChannel();
  512. // 查询超过指定触碰时间是否提示关闭弹窗
  513. this.$refs.timeoutNoOpsRef.pushflowPopup();
  514. // 获取云机剩余时长
  515. this.$refs.timeBalanceRef.getResidueTime();
  516. }
  517. });
  518. // 连接关闭
  519. engine.on('CONNECT_CLOSE', (r) => {
  520. console.log("webrtc关闭====★★★★★", r);
  521. });
  522. // 网络连接统计信息监听
  523. engine.on('NETWORK_STATS', (r) => {
  524. this.rtcNetwork = r;
  525. });
  526. // 连接异常
  527. engine.on('CONNECT_ERROR', (r) => {
  528. console.log("webrtc异常状态====★★★★★", r);
  529. // 异常状态枚举值
  530. const statusEnum = {
  531. 10011: '连接超时',
  532. 10012: '连接失败',
  533. 1002: 'rtc连接失败',
  534. 1003: 'rtc异常断开',
  535. 1004: 'rtc连接失败',
  536. 1006: '鉴权失败',
  537. };
  538. // 设置日志 推流状态为失败
  539. this.logReportObj.setParams({plugFowStatus: 2, linkWay: 0, linkEndTime: this.logReportObj.formatDate(new Date())});
  540. // 日志上报
  541. this.logReportObj.collectLog( `${statusEnum[r.code] || '连接异常'}: 消息: ${JSON.stringify(r)}` );
  542. this.$dialog.alert({
  543. title: '提示',
  544. message: '链接超时',
  545. confirmButtonText: '确定',
  546. confirmButtonColor: '#3cc51f',
  547. beforeClose: (action, done) => {
  548. done()
  549. this.exit()
  550. }
  551. })
  552. });
  553. // 显示区域大小发生改变 响应
  554. engine.on('RECEIVE_RESOLUTION', (r) => {
  555. // 分辨率大小发生改变,响应
  556. console.log("分辨率大小发生改变,响应 => RECEIVE_RESOLUTION", r);
  557. });
  558. },
  559. // 业务指令通道初始化
  560. initControlChannel() {
  561. try {
  562. // 初始化业务指令通道
  563. let { internetHttps, internetHttp, localIp, cardToken } = this.connectData;
  564. const isWss = location.protocol === 'https:';
  565. let cUrl = `${isWss ? 'wss' : 'ws'}://${isWss ? internetHttps : internetHttp}/businessChannel?cardIp=${localIp}&token=${cardToken}&type=directives`;
  566. this.doConnectDirectivesWs = new WebSocket(cUrl);
  567. this.doConnectDirectivesWs.binaryType = 'arraybuffer';
  568. // 清除定时器
  569. if (this.doConnectDirectivesIntervalerPing) {
  570. clearInterval(this.doConnectDirectivesIntervalerPing);
  571. }
  572. // 链接成功
  573. this.doConnectDirectivesWs.onopen = (e) => {
  574. // 日志上报
  575. this.logReportObj.collectLog( `消息: 业务通道连接成功` );
  576. // 清除loading
  577. this.$toast.clear();
  578. // 重置重连次数
  579. this.doConnectDirectivesRequestNum = 1;
  580. // 设置定时器 每3秒发送一次心跳
  581. this.doConnectDirectivesIntervalerPing = setInterval(() => {
  582. if (this.doConnectDirectivesWs.readyState === 1) {
  583. this.doConnectDirectivesWs.send(JSON.stringify({ type: 'ping' }));
  584. } else {
  585. clearInterval(this.doConnectDirectivesIntervalerPing);
  586. }
  587. }, 3000);
  588. // 输入法: 本地输入法 1 云机输入法 2
  589. this.doConnectDirectivesWs.send(JSON.stringify({ type: 'InputMethod', data: { type: 2 } }));
  590. }
  591. // 接受到的消息
  592. this.doConnectDirectivesWs.onmessage = res => {
  593. const result = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
  594. switch (result.type) {
  595. case 'reProduceText':
  596. this.$native.clipboard.writeText(result.data.text);
  597. break
  598. case 'downAdnInstallRep':
  599. this.$toast(result.data.msg)
  600. break
  601. // 接受到这个消息就自动退出云机
  602. case 'exitPhone':
  603. this.exit();
  604. break
  605. }
  606. }
  607. // 链接报错的回调
  608. this.doConnectDirectivesWs.onerror = res => {
  609. // 设置日志
  610. this.logReportObj.setParams({plugFowStatus: 1, linkWay: 0, linkEndTime: this.logReportObj.formatDate(new Date())});
  611. // 日志上报
  612. this.logReportObj.collectLog(
  613. `业务指令通道报错:
  614. url: ${res.target.url}
  615. type: ${res.type}
  616. 消息: ${JSON.stringify(res)}`
  617. );
  618. if (this.doConnectDirectivesRequestNum > this.doConnectDirectivesRequestNumMax) {
  619. return this.exit();
  620. }else{
  621. // 重连次数加1
  622. ++this.doConnectDirectivesRequestNum;
  623. // 重连
  624. this.initControlChannel();
  625. }
  626. }
  627. } catch (error) {
  628. console.log('initControlChannel error', error);
  629. }
  630. },
  631. /**
  632. * popup 功能按钮点击事件
  633. * @param {Object} val 传递的参数
  634. * @description 传递的参数格式: { code: 'hideKey', label: '隐藏虚拟键', icon: 'icon-hide' }
  635. */
  636. funcHandle({code}) {
  637. console.log('funcHandle code:', code);
  638. switch (code) {
  639. case 'hideKey':
  640. // 隐藏虚拟按键
  641. document.getElementById('foot-menu-wrap').style.display = 'none';
  642. this.pageData.footMenuHeight = 0; // 设置底部菜单高度为0
  643. this.getInitSize(); // 重新计算视频尺寸
  644. this.changeVideoStyle(); // 重新设置视频尺寸
  645. break;
  646. case 'showKey':
  647. // 显示虚拟按键
  648. document.getElementById('foot-menu-wrap').style.display = 'flex';
  649. this.pageData.footMenuHeight = 40; // 设置底部菜单高度为40px
  650. this.getInitSize(); // 重新计算视频尺寸
  651. this.changeVideoStyle(); // 重新设置视频尺寸
  652. break
  653. case 'shearplate':
  654. // 粘贴板按钮
  655. this.shearplate();
  656. break;
  657. }
  658. },
  659. // 重新设置视频尺寸
  660. changeVideoStyle() {
  661. this.$nextTick(() => {
  662. // 获取video元素
  663. const video = document.getElementById("videoRef").getElementsByTagName('video')[0];
  664. video.style.width = this.pageData.videoWidth + 'px';
  665. video.style.height = this.pageData.videoHeight + 'px';
  666. });
  667. },
  668. // 三键
  669. sendKey (keyCode) {
  670. try {
  671. this.engine?.sendKey(keyCode);
  672. // 重置超时无操作定时器
  673. this.$refs.timeoutNoOpsRef?.noOperationSetTimeout();
  674. } catch (error) {
  675. console.log('sendKey error', error);
  676. }
  677. },
  678. // popup粘贴板按钮点击事件
  679. shearplate(){
  680. // 调用InputCopy组件的pasteText方法读取粘贴板
  681. this.$refs.inputCopyRef.pasteText();
  682. },
  683. // 打开去取云机内的粘贴板内容
  684. openPasteboard(text){
  685. this.$refs.cloudPhoneClipboardRef.init(text);
  686. },
  687. // 退出功能
  688. exit() {
  689. // 关闭日志上报
  690. this.logReportObj.destroy();
  691. // 关闭webRTC
  692. this.engine.disconnect && this.engine.disconnect();
  693. // 关闭业务指令通道
  694. this.doConnectDirectivesWs && this.doConnectDirectivesWs.close();
  695. // 获取当前环境
  696. const env = isBrowserEnvironment();
  697. // ios环境下 直接使用浏览器api返回上一页
  698. if(env.isBrowser && !env.isMiniProgramWebview && env.isIPhone && env.isTopWindow) {
  699. // 上面的方法执行未生效就走这里
  700. if (window.history.length > 1) {
  701. return window.history.back();
  702. }
  703. }
  704. uni && uni.reLaunch({ url: '/pages/index/index' });
  705. },
  706. // 初始化日志上报实例
  707. initLogReport() {
  708. // 初始化日志上报实例
  709. this.logReportObj = new logReport({ request: this.$axios });
  710. uni.getEnv((res) => {
  711. // 设置上报参数
  712. this.logReportObj.setParams({ clientType: Object.keys(res)[0] });
  713. })
  714. },
  715. }
  716. }
  717. </script>
  718. <style lang="scss" scoped>
  719. html{
  720. background-color: #000;
  721. }
  722. // 动态生成 从 0 到 100px 的样式
  723. @for $i from 0 through 100 {
  724. .mb-#{$i} {
  725. margin-bottom: #{$i}px;
  726. }
  727. .mt-#{$i} {
  728. margin-top: #{$i}px;
  729. }
  730. .ml-#{$i} {
  731. margin-left: #{$i}px;
  732. }
  733. .mr-#{$i} {
  734. margin-right: #{$i}px;
  735. }
  736. }
  737. $-radeus-12: 12px;
  738. $-bg-yellow: rgb(255, 253, 241);
  739. .rtc-page{
  740. position: relative;
  741. font-size: 14px;
  742. .video-wrapper{
  743. position: relative;
  744. }
  745. }
  746. .cover-bg{
  747. background-color: #000;
  748. }
  749. #foot-menu-wrap{
  750. border-width: 0px;
  751. position: absolute;
  752. left: 0px;
  753. bottom: 0px;
  754. width: 100%;
  755. // height: 40px; // 三大功能键高度,通过vue动态添加
  756. background: inherit;
  757. background-color: rgba(0, 12, 23, 1);
  758. border: none;
  759. border-radius: 0px;
  760. -moz-box-shadow: none;
  761. -webkit-box-shadow: none;
  762. box-shadow: none;
  763. z-index: 1;
  764. display: flex;
  765. justify-content: space-evenly;
  766. align-items: center;
  767. color: #fff;
  768. }
  769. </style>