audioCall.nvue 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. <template>
  2. <view>
  3. <customNav :shownav="true" :title="i18n('audioCall.imtitle')" tinColor="#00A6FF" jiantou="0"></customNav>
  4. <view class="contentColumnC" style="width: 700rpx;margin-left: 25rpx;margin-top: 50rpx;">
  5. <netImage class="spIcon" width="120" height="120" :mysrc="avatar" mymode="scaleToFill"></netImage>
  6. <text style="margin-top: 30rpx;font-size: 32rpx;">{{nickName}}</text>
  7. <image v-if="!callState" style="width: 80rpx;height: 80rpx;margin-top: 80rpx;" src="/static/images/jietong.png" mode="scaleToFill" @click="bohaoAct(1)"></image>
  8. <image v-if="callState" style="width: 80rpx;height: 80rpx;margin-top: 80rpx;" src="/static/images/guaduandd.png" mode="scaleToFill" @click="bohaoAct(2)"></image>
  9. <text style="margin-top: 80rpx;font-size: 32rpx;">{{noteMessage}}</text>
  10. </view>
  11. </view>
  12. </template>
  13. <script>
  14. import api from "@/pages/api/api.js"
  15. import permision from "@/TrtcCloud/permission.js";
  16. import TrtcCloud from '@/TrtcCloud/lib/index';
  17. import { TRTCAppScene, TRTCVideoStreamType, TRTCCloudDef } from '@/TrtcCloud/lib/TrtcDefines';
  18. import { genTestUserSig } from '@/debug/GenerateTestUserSig';
  19. import TrtcLocalView from '@/TrtcCloud/view/TrtcLocalView';
  20. import TrtcRemoteView from '@/TrtcCloud/view/TrtcRemoteView';
  21. //const roomId = Math.floor(Math.random() * 100000).toString();
  22. //const userId = 'user_' + Math.floor(Math.random() * 100000).toString();
  23. export default {
  24. components: {
  25. TrtcLocalView: TrtcLocalView,
  26. TrtcRemoteView: TrtcRemoteView,
  27. },
  28. data() {
  29. return {
  30. iscaller:false,
  31. trtcCloud: null,
  32. sdkAppId:1600036174,
  33. userSig: '',
  34. roomId: Math.floor(Math.random() * 100000),
  35. userId:'',
  36. appScene: TRTCAppScene.TRTCAppSceneVideoCall, // TRTCAppSceneVideoCall
  37. isFrontCamera: true,
  38. streamType: TRTCVideoStreamType.TRTCVideoStreamTypeBig,
  39. remoteUserId: '',
  40. userinfo:'',
  41. friend:'',
  42. nickName:'',
  43. avatar:'',
  44. noteMessage:'',
  45. callState:false,
  46. isAndroid:false,
  47. audioObj:null,
  48. soundPlay:false
  49. }
  50. },
  51. onLoad(option) {
  52. var systemInfo = uni.getSystemInfoSync();
  53. this.isAndroid = systemInfo.platform.toLowerCase() === 'android';
  54. console.log('onLoad---------------------');
  55. getApp().globalData.imViewOpen=true;
  56. this.userinfo = uni.getStorageSync('userInfo');
  57. this.userId='user_'+this.userinfo.userId;
  58. console.log(this.userId);
  59. if(option.caller==1){
  60. this.iscaller=true;
  61. var friendinfo = uni.getStorageSync('imUser');
  62. this.friend = {
  63. id:'userid_'+friendinfo.userId,
  64. name:friendinfo.nickName,
  65. avatar:friendinfo.avatar
  66. }
  67. console.log(friendinfo);
  68. this.nickName=friendinfo.nickName;
  69. this.avatar=friendinfo.avatar;
  70. this.noteMessage=this.i18n('audioCall.zhengzhj');;
  71. }
  72. else{
  73. if(!this.isAndroid){
  74. this.audioObj=uni.createInnerAudioContext();
  75. this.audioObj.src='static/y800.mp3';
  76. this.audioObj.play();
  77. this.soundPlay=true;
  78. }
  79. }
  80. },
  81. mounted() {
  82. if (uni.getSystemInfoSync().platform === 'android') {
  83. permision.requestAndroidPermission('android.permission.RECORD_AUDIO');
  84. permision.requestAndroidPermission('android.permission.CAMERA');
  85. }
  86. console.log('mounted---------------------');
  87. // 生成 userSig
  88. if(this.iscaller){//主动拨号
  89. this.getUserSig(this.userId);
  90. }
  91. else{//接听,解析发起人信息
  92. var payload=uni.getStorageSync('impayload');
  93. this.doPushMessage(payload);
  94. if(this.isAndroid){
  95. this.getUserSig(this.userId);
  96. }
  97. //this.getUserSig(this.userId);
  98. }
  99. },
  100. unmounted() {
  101. this.handleUninstallEvents();
  102. },
  103. onUnload() {
  104. if(this.soundPlay){
  105. this.audioObj.pause();
  106. }
  107. getApp().globalData.imViewOpen=false;
  108. this.destroyInstance();
  109. console.log('- onUnload');
  110. },
  111. onBackPress() {
  112. getApp().globalData.imViewOpen=false;
  113. this.destroyInstance();
  114. },
  115. methods: {
  116. i18n(str){
  117. var rstr = getApp().globalData.$t(str);
  118. return rstr;
  119. },
  120. doPushMessage(str){
  121. if(str.indexOf("\\\"")!=-1){
  122. str=str.replace(/\\\"/g, '\"');
  123. str = str.replace(/\"{/g, '{');
  124. str = str.replace(/}\"/g, '}');
  125. }
  126. var obj = JSON.parse(str)
  127. this.friend = {
  128. id:'userid_'+obj.userId,
  129. name:obj.nickName,
  130. avatar:obj.avatar
  131. }
  132. console.log('doPushMessage',obj)
  133. this.roomId=obj.roomId;
  134. this.nickName=obj.nickName;
  135. this.avatar=obj.avatar;
  136. },
  137. destroyInstance() {
  138. this.exitRoom();
  139. if (this.trtcCloud) {
  140. TrtcCloud.destroyInstance();
  141. this.trtcCloud = null;
  142. // uni.showToast({
  143. // title: '通话结束',
  144. // icon: 'none'
  145. // });
  146. }
  147. },
  148. createTrtcCloud() {
  149. // uni.showToast({
  150. // title: '创建实例 ',
  151. // icon: 'none',
  152. // });
  153. this.trtcCloud = TrtcCloud.createInstance();
  154. this.handleEvents();
  155. },
  156. enterRoom() {
  157. try {
  158. // 【1】创建实例
  159. this.createTrtcCloud();
  160. // 【2】进房
  161. const { roomId, userId, sdkAppId, appScene, userSig } = this;
  162. let param = { roomId: +roomId, userId, sdkAppId, userSig };
  163. console.log(param);
  164. this.trtcCloud.enterRoom(param, appScene);
  165. if(!this.iscaller){//接听者开始进入房间
  166. this.noteMessage=this.i18n('audioCall.zhengzjt');
  167. }
  168. } catch (error) {
  169. this.noteMessage=this.i18n('audioCall.wfjt');
  170. console.log(`enterRoom error = ${JSON.stringify(error)}`);
  171. // this.sdkAppId && uni.$enterRoomFailedUpload(this.sdkAppId, JSON.stringify(error));
  172. }
  173. },
  174. exitRoom() {
  175. try {
  176. this.stopLocalAudio();
  177. this.trtcCloud.exitRoom();
  178. this.remoteUserId = '';
  179. } catch (e) {
  180. // TODO handle the exception
  181. }
  182. },
  183. // 开启本地音频采集和上行
  184. startLocalAudio() {
  185. this.trtcCloud.enableAudioVolumeEvaluation(300);
  186. this.trtcCloud.startLocalAudio();
  187. },
  188. // 关闭本地音频采集和上行
  189. stopLocalAudio() {
  190. this.trtcCloud.stopLocalAudio();
  191. },
  192. handleEvents() {
  193. this.trtcCloud.on('onWarning', (res) => {
  194. uni.showToast({
  195. title: `onWarning: ${JSON.stringify(res)}`,
  196. icon: 'none',
  197. });
  198. });
  199. this.trtcCloud.on('onError', (res) => {
  200. console.log('- onError: ', JSON.stringify(res));
  201. uni.showToast({
  202. title: `error: ${JSON.stringify(res)}`,
  203. icon: 'none',
  204. });
  205. // this.sdkAppId && uni.$onErrorUpload(this.sdkAppId, JSON.stringify(res));
  206. });
  207. this.trtcCloud.on('onEnterRoom', (result) => {
  208. console.log(`- onEnterRoom = ${result}`);
  209. if (result > 0) {
  210. if(this.iscaller){
  211. //this.sentroomId();
  212. this.goEasypushmsg();
  213. }
  214. else{
  215. this.startLocalAudio();
  216. this.noteMessage=this.i18n('audioCall.yijietong');
  217. }
  218. // uni.showToast({
  219. // title: `进房成功,耗时: ${result}ms`,
  220. // icon: 'none',
  221. // });
  222. } else {
  223. this.noteMessage=this.i18n('audioCall.wfjt');
  224. console.log(`enter room failed,error code = ${result}`);
  225. }
  226. });
  227. this.trtcCloud.on('onExitRoom', (reason) => {
  228. this.noteMessage=this.i18n('audioCall.yiguanduan');
  229. //const reasonList = ['主动调用 exitRoom 退房', '被服务器踢出当前房间', '当前房间整个被解散'];
  230. // uni.showToast({
  231. // title: `退房 ${reasonList[reason]}`,
  232. // icon: 'none',
  233. // duration: 1000
  234. // });
  235. });
  236. this.trtcCloud.on('onFirstVideoFrame', (res) => {
  237. console.log(`渲染的首帧画面响应 = ${JSON.stringify(res)}`);
  238. });
  239. this.trtcCloud.on('onRemoteUserEnterRoom', (userId) => {
  240. this.remoteUserId = userId;
  241. this.startLocalAudio();
  242. this.noteMessage=this.i18n('audioCall.yijietong');
  243. // uni.showToast({
  244. // title: `远端进房: userId = ${userId}`,
  245. // icon: 'none',
  246. // });
  247. });
  248. this.trtcCloud.on('onUserVideoAvailable', (res) => {
  249. const {
  250. userId,
  251. available
  252. } = res;
  253. if (userId && available) {
  254. this.remoteUserId = userId;
  255. this.trtcCloud.startRemoteView(this.remoteUserId, this.streamType, this.remoteUserId);
  256. }
  257. });
  258. this.trtcCloud.on('onUserVoiceVolume', (res) => {
  259. //console.log('音量 = ', res);
  260. });
  261. },
  262. handleUninstallEvents() {
  263. this.trtcCloud.off('*');
  264. },
  265. //---------------------------------------------------------------
  266. bohaoAct(index){
  267. if(index==1){//接通
  268. if(this.soundPlay){
  269. this.audioObj.pause();
  270. }
  271. this.getUserSig(this.userId);
  272. }
  273. else if(index==2){//挂断
  274. uni.navigateBack();
  275. }
  276. },
  277. getUserSig(userId){
  278. this.callState=true;
  279. console.log(userId);
  280. // // 生成 userSig
  281. // const { sdkAppId, userSig } = genTestUserSig(userId);
  282. // this.sdkAppId = sdkAppId;
  283. // this.userSig = userSig;
  284. // this.enterRoom();
  285. // console.log(userId,this.userSig);
  286. // return;
  287. api('getUserSig',{
  288. userId:userId,
  289. },res=>{
  290. console.log('getUserSig',res)
  291. if(res.data.code==200){
  292. this.userSig = res.data.data;
  293. this.enterRoom();
  294. }
  295. else{
  296. this.noteMessage=this.i18n('audioCall.wfjt');
  297. }
  298. },failc=>{
  299. //console.log('getadvertis----',failc)
  300. })
  301. },
  302. sentroomId(){
  303. if(this.imUser.cid==''||this.imUser.cid==null||this.imUser.cid==undefined){
  304. uni.showToast({
  305. title:this.i18n('audioCall.hujiaosb'),
  306. icon: 'none',
  307. duration: 1000
  308. });
  309. return;
  310. }
  311. var payload={
  312. roomId:JSON.stringify(this.roomId),
  313. nickName:this.userinfo.nickName,
  314. avatar:this.userinfo.avatar,
  315. }
  316. api('pushMsgQS',{
  317. cid:this.imUser.cid,
  318. title:'IM Call',
  319. content:'IM Call',
  320. payload:payload
  321. },res=>{
  322. console.log(res)
  323. },failc=>{
  324. //console.log('getadvertis----',failc)
  325. })
  326. },
  327. goEasypushmsg(){
  328. var payload={
  329. roomId:JSON.stringify(this.roomId),
  330. userId:this.userinfo.userId,
  331. nickName:this.userinfo.nickName,
  332. avatar:this.userinfo.avatar,
  333. ptype:1
  334. }
  335. var goEasy=getApp().globalData.goEasy;
  336. var pubsub = goEasy.pubsub;
  337. pubsub.publish({
  338. channel:this.friend.id, //请确认与接收端一致
  339. message:JSON.stringify(payload), //app内onMessage收到的消息内容
  340. notification: { //定义通知栏推送
  341. title: 'IM Call', //通知栏提醒标题,仅显示于通知栏
  342. body:'Call', //通知栏提醒内容,仅显示于通知栏
  343. },
  344. onSuccess: function () {
  345. console.log("Publish successfully.")
  346. },
  347. onFailed: function (error) {
  348. console.log("Failed to publish message, code:" + error.code + ' error:' + error.content);
  349. }
  350. });
  351. },
  352. }
  353. }
  354. </script>
  355. <style>
  356. .iconImg{
  357. margin-top: 30rpx;
  358. width: 200rpx;
  359. height: 200rpx;
  360. border-radius: 10rpx;
  361. background-color: #1A1A1A;
  362. }
  363. .spIcon{
  364. margin: 20rpx;
  365. width: 150rpx;
  366. height: 150rpx;
  367. }
  368. </style>