rtc.vue 31 KB

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