trtc-room.js 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267
  1. import UserController from 'controller/user-controller.js'
  2. import Pusher from 'model/pusher.js'
  3. import { EVENT, DEFAULT_COMPONENT_CONFIG } from 'common/constants.js'
  4. import Event from 'utils/event.js'
  5. import * as ENV from 'utils/environment.js'
  6. import TIM from 'libs/tim-wx.js'
  7. import MTA from 'libs/mta_analysis.js'
  8. const TAG_NAME = 'TRTC-ROOM'
  9. const IM_GROUP_TYPE = TIM.TYPES.GRP_CHATROOM // TIM.TYPES.GRP_CHATROOM 体验版IM无数量限制,成员20个, TIM.TYPES.GRP_AVCHATROOM IM体验版最多10个,升级后无限制
  10. let touchX = 0
  11. let touchY = 0
  12. Component({
  13. /**
  14. * 组件的属性列表
  15. */
  16. properties: {
  17. // 必要的初始化参数
  18. config: {
  19. type: Object,
  20. value: {
  21. sdkAppID: '',
  22. userID: '',
  23. userSig: '',
  24. template: '',
  25. debugMode: false, // 是否开启调试模式
  26. enableIM: false, // 是否开启 IM
  27. },
  28. observer: function(newVal, oldVal) {
  29. this._propertyObserver({
  30. 'name': 'config', newVal, oldVal,
  31. })
  32. },
  33. },
  34. },
  35. /**
  36. * 组件的初始数据
  37. */
  38. data: {
  39. pusher: null,
  40. debugPanel: true, // 是否打开组件调试面板
  41. debug: false, // 是否打开player pusher 的调试信息
  42. streamList: [], // 用于渲染player列表,存储stram
  43. visibleStreamList: [], // 有音频或者视频的StreamList
  44. userList: [], // 扁平化的数据用来返回给用户
  45. template: '', // 不能设置默认值,当默认值和传入组件的值不一致时,iOS渲染失败
  46. cameraPosition: '', // 摄像头位置,用于debug
  47. panelName: '', // 控制面板名称,包括 setting-panel memberlist-panel
  48. localVolume: 0,
  49. remoteVolumeList: [],
  50. enableIM: false, // 用于组件内渲染
  51. showIMPanel: false,
  52. exitIMThrottle: false,
  53. messageContent: '',
  54. messageList: [], // 仅保留10条消息
  55. maxMessageListLength: 10,
  56. messageListScrollTop: 0,
  57. appVersion: ENV.APP_VERSION,
  58. libVersion: ENV.LIB_VERSION,
  59. hasGridPageTipsShow: false,
  60. gridPageCount: 0, // grid 布局 player 分页的总页数
  61. gridCurrentPage: 1, // grid 布局 当前页码
  62. gridPlayerPerPage: 4, // grid 布局每页 player的数量, 如果大于3,在逻辑里第一页需要减1。等于3 pusher 在每一页都出现。可选值: 3,4
  63. gridPagePlaceholderStreamList: [], // 占位数量
  64. isFullscreenDevice: ENV.IS_FULLSCREEN_DEVICE,
  65. isShowMoreMenu: false,
  66. MICVolume: 50,
  67. BGMVolume: 50,
  68. BGMProgress: 0,
  69. beautyStyle: 'smooth',
  70. beautyStyleArray: [
  71. { value: 'smooth', label: '光滑', checked: true },
  72. { value: 'nature', label: '自然', checked: false },
  73. { value: 'close', label: '关闭', checked: false },
  74. ],
  75. filterIndex: 0,
  76. audioReverbType: 0,
  77. audioReverbTypeArray: ['关闭', 'KTV', '小房间', '大会堂', '低沉', '洪亮', '金属声', '磁性'],
  78. },
  79. /**
  80. * 生命周期方法
  81. */
  82. lifetimes: {
  83. created: function() {
  84. // 在组件实例刚刚被创建时执行
  85. console.log(TAG_NAME, 'created', ENV)
  86. MTA.App.init({
  87. appID: '500710685',
  88. eventID: '500710697',
  89. autoReport: true,
  90. statParam: true,
  91. })
  92. },
  93. attached: function() {
  94. // 在组件实例进入页面节点树时执行
  95. console.log(TAG_NAME, 'attached')
  96. this._init()
  97. MTA.Page.stat()
  98. },
  99. ready: function() {
  100. // 在组件在视图层布局完成后执行
  101. console.log(TAG_NAME, 'ready')
  102. },
  103. detached: function() {
  104. // 在组件实例被从页面节点树移除时执行
  105. console.log(TAG_NAME, 'detached')
  106. // 停止所有拉流,并重置数据
  107. this.exitRoom()
  108. },
  109. error: function(error) {
  110. // 每当组件方法抛出错误时执行
  111. console.log(TAG_NAME, 'error', error)
  112. },
  113. },
  114. pageLifetimes: {
  115. show: function() {
  116. // 组件所在的页面被展示时执行
  117. console.log(TAG_NAME, 'show status:', this.status)
  118. if (this.status.isPending) {
  119. // 经历了 5000 挂起事件
  120. this.status.isPending = false
  121. // 修复iOS 最小化触发5000事件后,音频推流失败的问题
  122. // if (ENV.IS_IOS && this.data.pusher.enableMic) {
  123. // this.unpublishLocalAudio().then(()=>{
  124. // this.publishLocalAudio()
  125. // })
  126. // }
  127. // 经历了 5001 浮窗关闭事件,小程序底层会自动退房,恢复小程序时组件需要重新进房
  128. // 重新进房
  129. this.enterRoom({ roomID: this.data.config.roomID }).then(()=>{
  130. // 进房后开始推送视频或音频
  131. })
  132. }
  133. this.status.pageLife = 'show'
  134. },
  135. hide: function() {
  136. // 组件所在的页面被隐藏时执行
  137. console.log(TAG_NAME, 'hide')
  138. this.status.pageLife = 'hide'
  139. },
  140. resize: function(size) {
  141. // 组件所在的页面尺寸变化时执行
  142. console.log(TAG_NAME, 'resize', size)
  143. },
  144. },
  145. /**
  146. * 组件的方法列表
  147. */
  148. methods: {
  149. /**
  150. * 初始化各项参数和用户控制模块,在组件实例触发 attached 时调用,此时不建议对View进行变更渲染(调用setData方法)
  151. */
  152. _init() {
  153. console.log(TAG_NAME, '_init')
  154. this.userController = new UserController(this)
  155. this._emitter = new Event()
  156. this.EVENT = EVENT
  157. this._initStatus()
  158. this._bindEvent()
  159. // this._gridBindEvent()
  160. this._keepScreenOn()
  161. console.log(TAG_NAME, '_init success component:', this)
  162. },
  163. _initStatus() {
  164. this.status = {
  165. isPush: false, // 推流状态
  166. isPending: false, // 挂起状态,触发5000事件标记为true,onShow后标记为false
  167. pageLife: '', // 页面生命周期 hide, show
  168. isOnHideAddStream: false, // onHide后有新增Stream
  169. }
  170. this._lastTapTime = 0 // 点击时间戳 用于判断双击事件
  171. this._beforeLastTapTime = 0 // 点击时间戳 用于判断双击事件
  172. this._lastTapCoordinate = { x: 0, y: 0 }, // 点击时的坐标
  173. this._isFullscreen = false // 是否进入全屏状态
  174. },
  175. /**
  176. * 监听组件属性变更,外部变更组件属性时触发该监听
  177. * @param {Object} data newVal,oldVal
  178. */
  179. _propertyObserver(data) {
  180. console.log(TAG_NAME, '_propertyObserver', data, this.data.config)
  181. if (data.name === 'config') {
  182. const config = Object.assign({}, DEFAULT_COMPONENT_CONFIG, data.newVal)
  183. console.log(TAG_NAME, '_propertyObserver config:', config)
  184. // 由于 querystring 只支持 String 类型,做一个类型防御
  185. if (typeof config.debugMode === 'string') {
  186. config.debugMode = config.debugMode === 'true' ? true : false
  187. }
  188. // 初始化IM
  189. if (config.enableIM && config.sdkAppID) {
  190. this._initIM(config)
  191. }
  192. if (config.sdkAppID && data.oldVal.sdkAppID !== config.sdkAppID && MTA) {
  193. MTA.Event.stat('sdkAppID', { 'value': config.sdkAppID })
  194. }
  195. // 独立设置与pusher无关的配置
  196. this.setData({
  197. enableIM: config.enableIM,
  198. template: config.template,
  199. debugMode: config.debugMode || false,
  200. debug: config.debugMode || false,
  201. })
  202. this._setPusherConfig(config)
  203. }
  204. },
  205. // _______ __ __ __
  206. // | \ | \ | \| \
  207. // | $$$$$$$\ __ __ | $$____ | $$ \$$ _______
  208. // | $$__/ $$| \ | \| $$ \ | $$| \ / \
  209. // | $$ $$| $$ | $$| $$$$$$$\| $$| $$| $$$$$$$
  210. // | $$$$$$$ | $$ | $$| $$ | $$| $$| $$| $$
  211. // | $$ | $$__/ $$| $$__/ $$| $$| $$| $$_____
  212. // | $$ \$$ $$| $$ $$| $$| $$ \$$ \
  213. // \$$ \$$$$$$ \$$$$$$$ \$$ \$$ \$$$$$$$
  214. /**
  215. * 进房
  216. * @param {Object} params 必传 roomID 取值范围 1 ~ 4294967295
  217. * @returns {Promise}
  218. */
  219. enterRoom(params) {
  220. return new Promise((resolve, reject) => {
  221. console.log(TAG_NAME, 'enterRoom')
  222. console.log(TAG_NAME, 'params', params)
  223. console.log(TAG_NAME, 'config', this.data.config)
  224. console.log(TAG_NAME, 'pusher', this.data.pusher)
  225. // 1. 补齐进房参数,校验必要参数是否齐全
  226. if (params) {
  227. Object.assign(this.data.pusher, params)
  228. Object.assign(this.data.config, params)
  229. }
  230. if (!this._checkParam(this.data.config)) {
  231. reject(new Error('缺少必要参数'))
  232. return
  233. }
  234. // 2. 根据参数拼接 push url,赋值给 live-pusher,
  235. this._getPushUrl(this.data.config).then((pushUrl)=> {
  236. this.data.pusher.url = pushUrl
  237. console.log(pushUrl, '····pushUrl····')
  238. getApp().globalData.pusher = this.data.pusher
  239. this.setData({
  240. pusher: this.data.pusher,
  241. }, () => {
  242. // 真正进房成功需要通过 1018 事件通知
  243. console.log(TAG_NAME, 'enterRoom', this.data.pusher)
  244. // view 渲染成功回调后,开始推流
  245. this.data.pusher.getPusherContext().start()
  246. this.status.isPush = true
  247. resolve()
  248. })
  249. }).catch((res)=> {
  250. // 进房失败需要通过 pusher state 事件通知,目前还没有准确的事件通知
  251. console.error(TAG_NAME, 'enterRoom error', res)
  252. reject(res)
  253. })
  254. // 初始化 IM SDK
  255. // this._initIM(this.data.config)
  256. // 登录IM
  257. this._loginIM({ ...this.data.config, roomID: params.roomID })
  258. })
  259. },
  260. /**
  261. * 退房,停止推流和拉流,并重置数据
  262. * @returns {Promise}
  263. */
  264. exitRoom() {
  265. console.log('exitRoom')
  266. if (this.status.pageLife === 'hide') {
  267. // 如果是退后台触发 onHide,不能调用 pusher API
  268. console.warn(TAG_NAME, '小程序最小化时不能调用 exitRoom,如果不想听到远端声音,可以调用取消订阅,如果不想远端听到声音,可以调用取消发布')
  269. }
  270. return new Promise((resolve, reject) => {
  271. console.log(TAG_NAME, 'exitRoom')
  272. this._exitIM()
  273. this.data.pusher.reset()
  274. this.status.isPush = false
  275. const result = this.userController.reset()
  276. this.setData({
  277. pusher: this.data.pusher,
  278. userList: result.userList,
  279. streamList: result.streamList,
  280. visibleStreamList: this._filterVisibleStream(result.streamList),
  281. }, () => {
  282. // 在销毁页面时调用exitRoom时,不会走到这里
  283. resolve({ userList: this.data.userList, streamList: this.data.streamList })
  284. console.log(TAG_NAME, 'exitRoom success', this.data.pusher, this.data.streamList, this.data.userList)
  285. // 20200421 iOS 仍然没有1019事件通知退房,退房事件移动到 exitRoom 方法里,但不是后端通知的退房成功
  286. this._emitter.emit(EVENT.LOCAL_LEAVE, { userID: this.data.pusher.userID })
  287. })
  288. })
  289. },
  290. /**
  291. * 开启摄像头
  292. * @returns {Promise}
  293. */
  294. publishLocalVideo() {
  295. // 设置 pusher enableCamera
  296. console.log(TAG_NAME, 'publishLocalVideo 开启摄像头')
  297. return this._setPusherConfig({ enableCamera: true })
  298. },
  299. /**
  300. * 关闭摄像头
  301. * @returns {Promise}
  302. */
  303. unpublishLocalVideo() {
  304. // 设置 pusher enableCamera
  305. console.log(TAG_NAME, 'unpublshLocalVideo 关闭摄像头')
  306. return this._setPusherConfig({ enableCamera: false })
  307. },
  308. /**
  309. * 开启麦克风
  310. * @returns {Promise}
  311. */
  312. publishLocalAudio() {
  313. // 设置 pusher enableCamera
  314. console.log(TAG_NAME, 'publishLocalAudio 开启麦克风')
  315. return this._setPusherConfig({ enableMic: true })
  316. },
  317. /**
  318. * 关闭麦克风
  319. * @returns {Promise}
  320. */
  321. unpublishLocalAudio() {
  322. // 设置 pusher enableCamera
  323. console.log(TAG_NAME, 'unpublshLocalAudio 关闭麦克风')
  324. return this._setPusherConfig({ enableMic: false })
  325. },
  326. /**
  327. * 订阅远端视频 主流 小画面 辅流
  328. * @param {Object} params {userID,streamType} streamType 传入 small 时修改对应的主流 url 的 _definitionType 参数为 small, stream.streamType 仍为 main
  329. * @returns {Promise}
  330. */
  331. subscribeRemoteVideo(params) {
  332. console.log(TAG_NAME, 'subscribeRemoteVideo', params)
  333. // 设置指定 user streamType 的 muteVideo 为 false
  334. const config = {
  335. muteVideo: false,
  336. }
  337. // 本地数据结构里的 streamType 只支持 main 和 aux ,订阅 small 也是对 main 进行处理
  338. const streamType = params.streamType === 'small' ? 'main' : params.streamType
  339. const stream = this.userController.getStream({
  340. userID: params.userID,
  341. streamType: streamType,
  342. })
  343. stream.muteVideoPrev = false // 用于分页切换时保留player当前的订阅状态
  344. if (params.streamType === 'small' || params.streamType === 'main') {
  345. if (stream && stream.streamType === 'main') {
  346. console.log(TAG_NAME, 'subscribeRemoteVideo switch small', stream.src)
  347. if (params.streamType === 'small') {
  348. config.src = stream.src.replace('main', 'small')
  349. config._definitionType = 'small' // 用于设置面板的渲染
  350. } else if (params.streamType === 'main') {
  351. stream.src = stream.src.replace('small', 'main')
  352. config._definitionType = 'main'
  353. }
  354. console.log(TAG_NAME, 'subscribeRemoteVideo', stream.src)
  355. }
  356. }
  357. return this._setPlayerConfig({
  358. userID: params.userID,
  359. streamType: streamType,
  360. config: config,
  361. })
  362. },
  363. /**
  364. * 取消订阅远端视频
  365. * @param {Object} params {userID,streamType}
  366. * @returns {Promise}
  367. */
  368. unsubscribeRemoteVideo(params) {
  369. console.log(TAG_NAME, 'unsubscribeRemoteVideo', params)
  370. const stream = this.userController.getStream({
  371. userID: params.userID,
  372. streamType: params.streamType,
  373. })
  374. stream.muteVideoPrev = true // 用于分页切换时保留player当前的订阅状态
  375. // 设置指定 user streamType 的 muteVideo 为 true
  376. return this._setPlayerConfig({
  377. userID: params.userID,
  378. streamType: params.streamType,
  379. config: {
  380. muteVideo: true,
  381. },
  382. })
  383. },
  384. /**
  385. * 订阅远端音频
  386. * @param {Object} params userID 用户ID
  387. * @returns {Promise}
  388. */
  389. subscribeRemoteAudio(params) {
  390. console.log(TAG_NAME, 'subscribeRemoteAudio', params)
  391. return this._setPlayerConfig({
  392. userID: params.userID,
  393. streamType: 'main',
  394. config: {
  395. muteAudio: false,
  396. },
  397. })
  398. },
  399. /**
  400. * 取消订阅远端音频
  401. * @param {Object} params userID 用户ID
  402. * @returns {Promise}
  403. */
  404. unsubscribeRemoteAudio(params) {
  405. console.log(TAG_NAME, 'unsubscribeRemoteAudio', params)
  406. return this._setPlayerConfig({
  407. userID: params.userID,
  408. streamType: 'main',
  409. config: {
  410. muteAudio: true,
  411. },
  412. })
  413. },
  414. on(eventCode, handler, context) {
  415. this._emitter.on(eventCode, handler, context)
  416. },
  417. off(eventCode, handler) {
  418. this._emitter.off(eventCode, handler)
  419. },
  420. getRemoteUserList() {
  421. return this.data.userList
  422. },
  423. /**
  424. * 切换前后摄像头
  425. */
  426. switchCamera() {
  427. if (!this.data.cameraPosition) {
  428. // this.data.pusher.cameraPosition 是初始值,不支持动态设置
  429. this.data.cameraPosition = this.data.pusher.frontCamera
  430. }
  431. console.log(TAG_NAME, 'switchCamera', this.data.cameraPosition)
  432. this.data.cameraPosition = this.data.cameraPosition === 'front' ? 'back' : 'front'
  433. this.setData({
  434. cameraPosition: this.data.cameraPosition,
  435. }, () => {
  436. console.log(TAG_NAME, 'switchCamera success', this.data.cameraPosition)
  437. })
  438. // wx 7.0.9 不支持动态设置 pusher.frontCamera ,只支持调用 API switchCamer() 设置,这里修改 cameraPosition 是为了记录状态
  439. this.data.pusher.getPusherContext().switchCamera()
  440. },
  441. /**
  442. * 设置指定player view的渲染坐标和尺寸
  443. * @param {object} params
  444. * userID: string
  445. * streamType: string
  446. * xAxis: number
  447. * yAxis: number
  448. * width: number
  449. * height: number
  450. * @returns {Promise}
  451. */
  452. setViewRect(params) {
  453. console.log(TAG_NAME, 'setViewRect', params)
  454. if (this.data.template !== 'custom') {
  455. console.warn(`如需使用setViewRect方法,请初始化时设置template:"custom", 当前 template:"${this.data.template}"`)
  456. }
  457. console.info(`不建议使用该方法动态修改样式,避免引起微信小程序渲染问题,建议直接修改 wxml wxss 进行样式定制化`)
  458. if (this.data.pusher.userID === params.userID) {
  459. return this._setPusherConfig({
  460. xAxis: params.xAxis,
  461. yAxis: params.yAxis,
  462. width: params.width,
  463. height: params.height,
  464. })
  465. }
  466. return this._setPlayerConfig({
  467. userID: params.userID,
  468. streamType: params.streamType,
  469. config: {
  470. xAxis: params.xAxis,
  471. yAxis: params.yAxis,
  472. width: params.width,
  473. height: params.height,
  474. },
  475. })
  476. },
  477. /**
  478. * 设置指定 player 或者 pusher view 是否可见
  479. * @param {object} params
  480. * userID: string
  481. * streamType: string
  482. * isVisible:boolean
  483. * @returns {Promise}
  484. */
  485. setViewVisible(params) {
  486. console.log(TAG_NAME, 'setViewVisible', params)
  487. if (this.data.template !== 'custom') {
  488. console.warn(`如需使用setViewVisible方法,请初始化时设置template:"custom", 当前 template:"${this.data.template}"`)
  489. }
  490. console.info(`不建议使用该方法动态修改样式,避免引起微信小程序渲染问题,建议直接修改 wxml wxss 进行样式定制化`)
  491. if (this.data.pusher.userID === params.userID) {
  492. return this._setPusherConfig({
  493. isVisible: params.isVisible,
  494. })
  495. }
  496. return this._setPlayerConfig({
  497. userID: params.userID,
  498. streamType: params.streamType,
  499. config: {
  500. isVisible: params.isVisible,
  501. },
  502. })
  503. },
  504. /**
  505. * 设置指定player view的层级
  506. * @param {Object} params
  507. * userID: string
  508. * streamType: string
  509. * zIndex: number
  510. * @returns {Promise}
  511. */
  512. setViewZIndex(params) {
  513. console.log(TAG_NAME, 'setViewZIndex', params)
  514. if (this.data.template !== 'custom') {
  515. console.warn(`如需使用setViewZIndex方法,请初始化时设置template:"custom", 当前 template:"${this.data.template}"`)
  516. }
  517. console.info(`不建议使用该方法动态修改样式,避免引起微信小程序渲染问题,建议直接修改 wxml wxss 进行样式定制化`)
  518. if (this.data.pusher.userID === params.userID) {
  519. return this._setPusherConfig({
  520. zIndex: params.zindex || params.zIndex,
  521. })
  522. }
  523. return this._setPlayerConfig({
  524. userID: params.userID,
  525. streamType: params.streamType,
  526. config: {
  527. zIndex: params.zindex || params.zIndex,
  528. },
  529. })
  530. },
  531. /**
  532. * 播放背景音
  533. * @param {Object} params url
  534. * @returns {Promise}
  535. */
  536. playBGM(params) {
  537. return new Promise((resolve, reject) => {
  538. this.data.pusher.getPusherContext().playBGM({
  539. url: params.url,
  540. // 已经有相关事件不需要在这里监听,目前用于测试
  541. success: () => {
  542. console.log(TAG_NAME, '播放背景音成功')
  543. // this._emitter.emit(EVENT.BGM_PLAY_START)
  544. resolve()
  545. },
  546. fail: () => {
  547. console.log(TAG_NAME, '播放背景音失败')
  548. this._emitter.emit(EVENT.BGM_PLAY_FAIL)
  549. reject(new Error('播放背景音失败'))
  550. },
  551. // complete: () => {
  552. // console.log(TAG_NAME, '背景完成')
  553. // this._emitter.emit(EVENT.BGM_PLAY_COMPLETE)
  554. // },
  555. })
  556. })
  557. },
  558. stopBGM() {
  559. this.data.pusher.getPusherContext().stopBGM()
  560. },
  561. pauseBGM() {
  562. this.data.pusher.getPusherContext().pauseBGM()
  563. },
  564. resumeBGM() {
  565. this.data.pusher.getPusherContext().resumeBGM()
  566. },
  567. /**
  568. * 设置背景音音量
  569. * @param {Object} params volume
  570. */
  571. setBGMVolume(params) {
  572. console.log(TAG_NAME, 'setBGMVolume', params)
  573. this.data.pusher.getPusherContext().setBGMVolume({ volume: params.volume })
  574. },
  575. /**
  576. * 设置麦克风音量
  577. * @param {Object} params volume
  578. */
  579. setMICVolume(params) {
  580. console.log(TAG_NAME, 'setMICVolume', params)
  581. this.data.pusher.getPusherContext().setMICVolume({ volume: params.volume })
  582. },
  583. /**
  584. * 发送SEI消息
  585. * @param {Object} params message
  586. * @returns {Promise}
  587. */
  588. sendSEI(params) {
  589. return new Promise((resolve, reject) => {
  590. this.data.pusher.getPusherContext().sendMessage({
  591. msg: params.message,
  592. success: function(result) {
  593. resolve(result)
  594. },
  595. })
  596. })
  597. },
  598. /**
  599. * pusher 和 player 的截图并保存
  600. * @param {Object} params userID streamType
  601. * @returns {Promise}
  602. */
  603. snapshot(params) {
  604. console.log(TAG_NAME, 'snapshot', params)
  605. return new Promise((resolve, reject) => {
  606. this.captureSnapshot(params).then((result)=>{
  607. wx.saveImageToPhotosAlbum({
  608. filePath: result.tempImagePath,
  609. success(res) {
  610. wx.showToast({
  611. title: '已保存到相册',
  612. })
  613. console.log('save photo is success', res)
  614. resolve(result)
  615. },
  616. fail: function(error) {
  617. wx.showToast({
  618. icon: 'none',
  619. title: '保存失败',
  620. })
  621. console.log('save photo is fail', error)
  622. reject(error)
  623. },
  624. })
  625. }).catch((error)=>{
  626. reject(error)
  627. })
  628. })
  629. },
  630. /**
  631. * 获取pusher 和 player 的截图
  632. * @param {Object} params userID streamType
  633. * @returns {Promise}
  634. */
  635. captureSnapshot(params) {
  636. return new Promise((resolve, reject) => {
  637. if (params.userID === this.data.pusher.userID) {
  638. // pusher
  639. this.data.pusher.getPusherContext().snapshot({
  640. quality: 'raw',
  641. complete: (result) => {
  642. console.log(TAG_NAME, 'snapshot pusher', result)
  643. if (result.tempImagePath) {
  644. resolve(result)
  645. } else {
  646. console.log('snapShot 回调失败', result)
  647. reject(new Error('截图失败'))
  648. }
  649. },
  650. })
  651. } else {
  652. // player
  653. this.userController.getStream(params).playerContext.snapshot({
  654. quality: 'raw',
  655. complete: (result) => {
  656. console.log(TAG_NAME, 'snapshot player', result)
  657. if (result.tempImagePath) {
  658. resolve(result)
  659. } else {
  660. console.log('snapShot 回调失败', result)
  661. reject(new Error('截图失败'))
  662. }
  663. },
  664. })
  665. }
  666. })
  667. },
  668. /**
  669. * 设置 player 视图的横竖屏显示
  670. * @param {Object} params userID streamType orientation: vertical, horizontal
  671. * @returns {Promise}
  672. */
  673. setRemoteOrientation(params) {
  674. return this._setPlayerConfig({
  675. userID: params.userID,
  676. streamType: params.streamType,
  677. config: {
  678. orientation: params.orientation,
  679. },
  680. })
  681. },
  682. // 改为:
  683. setViewOrientation(params) {
  684. return this._setPlayerConfig({
  685. userID: params.userID,
  686. streamType: params.streamType,
  687. config: {
  688. orientation: params.orientation,
  689. },
  690. })
  691. },
  692. /**
  693. * 设置 player 视图的填充模式
  694. * @param {Object} params userID streamType fillMode: contain,fillCrop
  695. * @returns {Promise}
  696. */
  697. setRemoteFillMode(params) {
  698. return this._setPlayerConfig({
  699. userID: params.userID,
  700. streamType: params.streamType,
  701. config: {
  702. objectFit: params.fillMode,
  703. },
  704. })
  705. },
  706. // 改为:
  707. setViewFillMode(params) {
  708. return this._setPlayerConfig({
  709. userID: params.userID,
  710. streamType: params.streamType,
  711. config: {
  712. objectFit: params.fillMode,
  713. },
  714. })
  715. },
  716. /**
  717. * 发送C2C文本消息
  718. * @param {*} params userID,message
  719. * @returns {Promise}
  720. */
  721. sendC2CTextMessage(params) {
  722. if (!this.tim) {
  723. console.warn(TAG_NAME, '未开启IM功能,该方法无法使用', params)
  724. return
  725. }
  726. console.log(TAG_NAME, 'sendC2CTextMessage', params)
  727. const message = this.tim.createTextMessage({
  728. to: params.userID + '',
  729. conversationType: TIM.TYPES.CONV_C2C,
  730. payload: {
  731. text: params.message,
  732. },
  733. })
  734. const promise = this.tim.sendMessage(message)
  735. promise.then(function(imResponse) {
  736. // 发送成功
  737. console.log(TAG_NAME, 'sendC2CTextMessage success', imResponse)
  738. }).catch(function(imError) {
  739. // 发送失败
  740. console.warn(TAG_NAME, 'sendC2CTextMessage error:', imError)
  741. })
  742. return promise
  743. },
  744. /**
  745. * 发送C2C自定义消息
  746. * @param {*} params: userID payload
  747. * @returns {Promise}
  748. *
  749. */
  750. sendC2CCustomMessage(params) {
  751. if (!this.tim) {
  752. console.warn(TAG_NAME, '未开启IM功能,该方法无法使用', params)
  753. return
  754. }
  755. console.log(TAG_NAME, 'sendC2CCustomMessage', params)
  756. const message = this.tim.createCustomMessage({
  757. to: params.userID + '',
  758. conversationType: TIM.TYPES.CONV_C2C,
  759. payload: params.payload,
  760. })
  761. const promise = this.tim.sendMessage(message)
  762. promise.then(function(imResponse) {
  763. // 发送成功
  764. console.log(TAG_NAME, 'sendMessage success', imResponse)
  765. }).catch(function(imError) {
  766. // 发送失败
  767. console.warn(TAG_NAME, 'sendMessage error:', imError)
  768. })
  769. return promise
  770. },
  771. /**
  772. * 发送群组文本消息
  773. * @param {*} params roomID message
  774. * @returns {Promise}
  775. *
  776. */
  777. sendGroupTextMessage(params) {
  778. if (!this.tim) {
  779. console.warn(TAG_NAME, '未开启IM功能,该方法无法使用', params)
  780. return
  781. }
  782. console.log(TAG_NAME, 'sendGroupTextMessage', params)
  783. const message = this.tim.createTextMessage({
  784. to: params.roomID + '',
  785. conversationType: TIM.TYPES.CONV_GROUP,
  786. payload: {
  787. text: params.message,
  788. },
  789. })
  790. const promise = this.tim.sendMessage(message)
  791. promise.then(function(imResponse) {
  792. // 发送成功
  793. console.log(TAG_NAME, 'sendGroupTextMessage success', imResponse)
  794. }).catch(function(imError) {
  795. // 发送失败
  796. console.warn(TAG_NAME, 'sendGroupTextMessage error:', imError)
  797. })
  798. return promise
  799. },
  800. /**
  801. * 发送群组自定义消息
  802. * @param {*} params roomID payload
  803. * @returns {Promise}
  804. *
  805. */
  806. sendGroupCustomMessage(params) {
  807. if (!this.tim) {
  808. console.warn(TAG_NAME, '未开启IM功能,该方法无法使用', params)
  809. return
  810. }
  811. console.log(TAG_NAME, 'sendGroupCustomMessage', params)
  812. const message = this.tim.createCustomMessage({
  813. to: params.roomID + '',
  814. conversationType: TIM.TYPES.CONV_GROUP,
  815. payload: params.payload,
  816. })
  817. const promise = this.tim.sendMessage(message)
  818. promise.then(function(imResponse) {
  819. // 发送成功
  820. console.log(TAG_NAME, 'sendMessage success', imResponse)
  821. }).catch(function(imError) {
  822. // 发送失败
  823. console.warn(TAG_NAME, 'sendMessage error:', imError)
  824. })
  825. return promise
  826. },
  827. // ______ __ __
  828. // | \ | \ | \
  829. // \$$$$$$ _______ _| $$_ ______ ______ _______ ______ | $$
  830. // | $$ | \| $$ \ / \ / \ | \ | \ | $$
  831. // | $$ | $$$$$$$\\$$$$$$ | $$$$$$\| $$$$$$\| $$$$$$$\ \$$$$$$\| $$
  832. // | $$ | $$ | $$ | $$ __ | $$ $$| $$ \$$| $$ | $$ / $$| $$
  833. // _| $$_ | $$ | $$ | $$| \| $$$$$$$$| $$ | $$ | $$| $$$$$$$| $$
  834. // | $$ \| $$ | $$ \$$ $$ \$$ \| $$ | $$ | $$ \$$ $$| $$
  835. // \$$$$$$ \$$ \$$ \$$$$ \$$$$$$$ \$$ \$$ \$$ \$$$$$$$ \$$
  836. /**
  837. * 设置推流参数并触发页面渲染更新
  838. * @param {Object} config live-pusher 的配置
  839. * @returns {Promise}
  840. */
  841. _setPusherConfig(config, skipLog = false) {
  842. if (!skipLog) {
  843. console.log(TAG_NAME, '_setPusherConfig', config, this.data.pusher)
  844. }
  845. return new Promise((resolve, reject) => {
  846. if (!this.data.pusher) {
  847. this.data.pusher = new Pusher(config)
  848. } else {
  849. Object.assign(this.data.pusher, config)
  850. }
  851. this.setData({
  852. pusher: this.data.pusher,
  853. }, () => {
  854. if (!skipLog) {
  855. console.log(TAG_NAME, '_setPusherConfig setData compelete', 'config:', config, 'pusher:', this.data.pusher)
  856. }
  857. resolve(config)
  858. })
  859. })
  860. },
  861. /**
  862. * 设置指定 player 属性并触发页面渲染
  863. * @param {Object} params include userID,streamType,config
  864. * @returns {Promise}
  865. */
  866. _setPlayerConfig(params) {
  867. const userID = params.userID
  868. const streamType = params.streamType
  869. const config = params.config
  870. console.log(TAG_NAME, '_setPlayerConfig', params)
  871. return new Promise((resolve, reject) => {
  872. // 获取指定的userID streamType 的 stream
  873. const user = this.userController.getUser(userID)
  874. if (user && user.streams[streamType]) {
  875. Object.assign(user.streams[streamType], config)
  876. // user.streams引用的对象和 streamList 里的是同一个
  877. this.setData({
  878. streamList: this.data.streamList,
  879. visibleStreamList: this._filterVisibleStream(this.data.streamList, true),
  880. }, () => {
  881. // console.log(TAG_NAME, '_setPlayerConfig complete', params, 'streamList:', this.data.streamList)
  882. resolve(params)
  883. })
  884. } else {
  885. // 不需要reject,静默处理
  886. console.warn(TAG_NAME, '指定 userID 或者 streamType 不存在')
  887. // reject(new Error('指定 userID 或者 streamType 不存在'))
  888. }
  889. })
  890. },
  891. /**
  892. * 设置列表数据,并触发页面渲染
  893. * @param {Object} params include userList, stramList
  894. * @returns {Promise}
  895. */
  896. _setList(params) {
  897. console.log(TAG_NAME, '_setList', params, this.data.template)
  898. const { userList, streamList } = params
  899. return new Promise((resolve, reject) => {
  900. const data = {
  901. userList: userList || this.data.userList,
  902. streamList: streamList || this.data.streamList,
  903. }
  904. this.setData(data, () => {
  905. resolve(params)
  906. })
  907. })
  908. },
  909. /**
  910. * 必选参数检测
  911. * @param {Object} rtcConfig rtc参数
  912. * @returns {Boolean}
  913. */
  914. _checkParam(rtcConfig) {
  915. console.log(TAG_NAME, 'checkParam config:', rtcConfig)
  916. if (!rtcConfig.sdkAppID) {
  917. console.error('未设置 sdkAppID')
  918. return false
  919. }
  920. if (rtcConfig.roomID === undefined) {
  921. console.error('未设置 roomID')
  922. return false
  923. }
  924. if (rtcConfig.roomID < 1 || rtcConfig.roomID > 4294967296) {
  925. console.error('roomID 超出取值范围 1 ~ 4294967295')
  926. return false
  927. }
  928. if (!rtcConfig.userID) {
  929. console.error('未设置 userID')
  930. return false
  931. }
  932. if (!rtcConfig.userSig) {
  933. console.error('未设置 userSig')
  934. return false
  935. }
  936. if (!rtcConfig.template) {
  937. console.error('未设置 template')
  938. return false
  939. }
  940. return true
  941. },
  942. _getPushUrl(rtcConfig) {
  943. // 拼接 puhser url rtmp 方案
  944. console.log(TAG_NAME, '_getPushUrl', rtcConfig)
  945. if (ENV.IS_TRTC || true) {
  946. // 版本高于7.0.8,基础库版本高于2.10.0 使用新的 url
  947. return new Promise((resolve, reject) => {
  948. // appscene videocall live
  949. // cloudenv PRO CCC DEV UAT
  950. // encsmall 0
  951. // 对外的默认值是rtc ,对内的默认值是videocall
  952. rtcConfig.scene = !rtcConfig.scene || rtcConfig.scene === 'rtc' ? 'videocall' : rtcConfig.scene
  953. rtcConfig.enableBlackStream = rtcConfig.enableBlackStream || '' // 是否支持在纯音频下推送SEI消息,注意:在关闭enable-recv-message后还是无法接收
  954. rtcConfig.encsmall = rtcConfig.encsmall || 0 // 是否编小画面,这个特性不建议学生默认开启,只有老师端才比较有意义
  955. rtcConfig.cloudenv = rtcConfig.cloudenv || 'PRO'
  956. rtcConfig.streamID = rtcConfig.streamID || '' // 指定旁边路直播的流ID
  957. rtcConfig.userDefineRecordID = rtcConfig.userDefineRecordID || '' // 指定录制文件的recordid
  958. rtcConfig.privateMapKey = rtcConfig.privateMapKey || '' // 字符串房间号
  959. rtcConfig.pureAudioMode = rtcConfig.pureAudioMode || ''// 指定是否纯音频推流及录制,默认不填,值为1 或 2,其他值非法不处理
  960. rtcConfig.recvMode = rtcConfig.recvMode || 1 // 1. 自动接收音视频 2. 仅自动接收音频 3. 仅自动接收视频 4. 音视频都不自动接收, 不能绑定player
  961. let roomID = ''
  962. if (/^\d+$/.test(rtcConfig.roomID)) {
  963. // 数字房间号
  964. roomID = '&roomid=' + rtcConfig.roomID
  965. } else {
  966. // 字符串房间号
  967. roomID = '&strroomid=' + rtcConfig.roomID
  968. }
  969. setTimeout(()=> {
  970. const pushUrl = 'room://cloud.tencent.com/rtc?sdkappid=' + rtcConfig.sdkAppID +
  971. roomID +
  972. '&userid=' + rtcConfig.userID +
  973. '&usersig=' + rtcConfig.userSig +
  974. '&appscene=' + rtcConfig.scene +
  975. '&encsmall=' + rtcConfig.encsmall +
  976. '&cloudenv=' + rtcConfig.cloudenv +
  977. '&enableBlackStream=' + rtcConfig.enableBlackStream +
  978. '&streamid=' + rtcConfig.streamID +
  979. '&userdefinerecordid=' + rtcConfig.userDefineRecordID +
  980. '&privatemapkey=' + rtcConfig.privateMapKey +
  981. '&pureaudiomode=' + rtcConfig.pureAudioMode +
  982. '&recvmode=' + rtcConfig.recvMode
  983. console.warn(TAG_NAME, 'getPushUrl result:', pushUrl)
  984. resolve(pushUrl)
  985. }, 0)
  986. })
  987. }
  988. console.error(TAG_NAME, '组件仅支持微信 App iOS >=7.0.9, Android >= 7.0.8, 小程序基础库版 >= 2.10.0')
  989. console.error(TAG_NAME, '需要真机运行,开发工具不支持实时音视频')
  990. },
  991. /**
  992. * 获取签名和推流地址
  993. * @param {Object} rtcConfig 进房参数配置
  994. * @returns {Promise}
  995. */
  996. _requestSigServer(rtcConfig) {
  997. console.log(TAG_NAME, '_requestSigServer:', rtcConfig)
  998. const sdkAppID = rtcConfig.sdkAppID
  999. const userID = rtcConfig.userID
  1000. const userSig = rtcConfig.userSig
  1001. const roomID = rtcConfig.roomID
  1002. const privateMapKey = rtcConfig.privateMapKey
  1003. rtcConfig.useCloud = rtcConfig.useCloud === undefined ? true : rtcConfig.useCloud
  1004. let url = rtcConfig.useCloud ? 'https://official.opensso.tencent-cloud.com/v4/openim/jsonvideoapp' : 'https://yun.tim.qq.com/v4/openim/jsonvideoapp'
  1005. url += '?sdkappid=' + sdkAppID + '&identifier=' + userID + '&usersig=' + userSig + '&random=' + Date.now() + '&contenttype=json'
  1006. const reqHead = {
  1007. 'Cmd': 1,
  1008. 'SeqNo': 1,
  1009. 'BusType': 7,
  1010. 'GroupId': roomID,
  1011. }
  1012. const reqBody = {
  1013. 'PrivMapEncrypt': privateMapKey,
  1014. 'TerminalType': 1,
  1015. 'FromType': 3,
  1016. 'SdkVersion': 26280566,
  1017. }
  1018. console.log(TAG_NAME, '_requestSigServer:', url, reqHead, reqBody)
  1019. return new Promise((resolve, reject) => {
  1020. wx.request({
  1021. url: url,
  1022. data: {
  1023. 'ReqHead': reqHead,
  1024. 'ReqBody': reqBody,
  1025. },
  1026. method: 'POST',
  1027. success: (res) => {
  1028. console.log('_requestSigServer success:', res)
  1029. if (res.data['ErrorCode'] || res.data['RspHead']['ErrorCode'] !== 0) {
  1030. // console.error(res.data['ErrorInfo'] || res.data['RspHead']['ErrorInfo'])
  1031. console.error('获取roomsig失败')
  1032. reject(res)
  1033. }
  1034. const roomSig = JSON.stringify(res.data['RspBody'])
  1035. let pushUrl = 'room://cloud.tencent.com?sdkappid=' + sdkAppID + '&roomid=' + roomID + '&userid=' + userID + '&roomsig=' + encodeURIComponent(roomSig)
  1036. // TODO 需要重新整理的逻辑 TRTC尚未支持 20200213
  1037. // 如果有配置纯音频推流或者recordId参数
  1038. if (rtcConfig.pureAudioPushMod || rtcConfig.recordId) {
  1039. const bizbuf = {
  1040. Str_uc_params: {
  1041. pure_audio_push_mod: 0,
  1042. record_id: 0,
  1043. },
  1044. }
  1045. // 纯音频推流
  1046. if (rtcConfig.pureAudioPushMod) {
  1047. bizbuf.Str_uc_params.pure_audio_push_mod = rtcConfig.pureAudioPushMod
  1048. } else {
  1049. delete bizbuf.Str_uc_params.pure_audio_push_mod
  1050. }
  1051. // 自动录制时业务自定义id
  1052. if (rtcConfig.recordId) {
  1053. bizbuf.Str_uc_params.record_id = rtcConfig.recordId
  1054. } else {
  1055. delete bizbuf.Str_uc_params.record_id
  1056. }
  1057. pushUrl += '&bizbuf=' + encodeURIComponent(JSON.stringify(bizbuf))
  1058. }
  1059. console.log('roomSigInfo', pushUrl)
  1060. resolve(pushUrl)
  1061. },
  1062. fail: (res) => {
  1063. console.log(TAG_NAME, 'requestSigServer fail:', res)
  1064. reject(res)
  1065. },
  1066. })
  1067. })
  1068. },
  1069. _doubleTabToggleFullscreen(event) {
  1070. const curTime = event.timeStamp
  1071. const lastTime = this._lastTapTime
  1072. const lastTapCoordinate = this._lastTapCoordinate
  1073. const currentTapCoordinate = event.detail
  1074. // 计算两次点击的距离
  1075. const distence = Math.sqrt(Math.pow(Math.abs(currentTapCoordinate.x - lastTapCoordinate.x), 2) + Math.pow(Math.abs(currentTapCoordinate.y - lastTapCoordinate.y), 2))
  1076. this._lastTapCoordinate = currentTapCoordinate
  1077. // 已知问题:上次全屏操作后,必须等待1.5s后才能再次进行全屏操作,否则引发SDK全屏异常,因此增加节流逻辑
  1078. const beforeLastTime = this._beforeLastTapTime
  1079. console.log(TAG_NAME, '_doubleTabToggleFullscreen', event, lastTime, beforeLastTime, distence)
  1080. if (curTime - lastTime > 0 && curTime - lastTime < 300 && lastTime - beforeLastTime > 1500 && distence < 20) {
  1081. const userID = event.currentTarget.dataset.userid
  1082. const streamType = event.currentTarget.dataset.streamtype
  1083. if (this._isFullscreen) {
  1084. this.exitFullscreen({ userID, streamType }).then(() => {
  1085. this._isFullscreen = false
  1086. }).catch(() => {
  1087. })
  1088. } else {
  1089. // const stream = this.userController.getStream({ userID, streamType })
  1090. let direction
  1091. // // 已知问题:视频的尺寸需要等待player触发NetStatus事件才能获取到,如果进房就双击全屏,全屏后的方向有可能不对。
  1092. // if (stream && stream.videoWidth && stream.videoHeight) {
  1093. // // 如果是横视频,全屏时进行横屏处理。如果是竖视频,则为0
  1094. // direction = stream.videoWidth > stream.videoHeight ? 90 : 0
  1095. // }
  1096. this.enterFullscreen({ userID, streamType, direction }).then(() => {
  1097. this._isFullscreen = true
  1098. }).catch(() => {
  1099. })
  1100. }
  1101. this._beforeLastTapTime = lastTime
  1102. }
  1103. this._lastTapTime = curTime
  1104. },
  1105. /**
  1106. * TRTC-room 远端用户和音视频状态处理
  1107. */
  1108. _bindEvent() {
  1109. // 远端用户进房
  1110. this.userController.on(EVENT.REMOTE_USER_JOIN, (event)=>{
  1111. console.log(TAG_NAME, '远端用户进房', event, event.data.userID)
  1112. this.setData({
  1113. userList: event.data.userList,
  1114. }, () => {
  1115. this._emitter.emit(EVENT.REMOTE_USER_JOIN, { userID: event.data.userID })
  1116. })
  1117. console.log(TAG_NAME, 'REMOTE_USER_JOIN', 'streamList:', this.data.streamList, 'userList:', this.data.userList)
  1118. })
  1119. // 远端用户离开
  1120. this.userController.on(EVENT.REMOTE_USER_LEAVE, (event)=>{
  1121. console.log(TAG_NAME, '远端用户离开', event, event.data.userID)
  1122. if (event.data.userID) {
  1123. this._setList({
  1124. userList: event.data.userList,
  1125. streamList: event.data.streamList,
  1126. }).then(() => {
  1127. this._emitter.emit(EVENT.REMOTE_USER_LEAVE, { userID: event.data.userID })
  1128. })
  1129. }
  1130. console.log(TAG_NAME, 'REMOTE_USER_LEAVE', 'streamList:', this.data.streamList, 'userList:', this.data.userList)
  1131. })
  1132. // 音频可用
  1133. this.userController.on(EVENT.REMOTE_AUDIO_ADD, (event)=>{
  1134. console.log(TAG_NAME, '远端音频可用', event)
  1135. const stream = event.data.stream
  1136. this._setList({
  1137. userList: event.data.userList,
  1138. streamList: event.data.streamList,
  1139. }).then(() => {
  1140. stream.playerContext = wx.createLivePlayerContext(stream.streamID, this)
  1141. // 新增的需要触发一次play 默认属性才能生效
  1142. // stream.playerContext.play()
  1143. // console.log(TAG_NAME, 'REMOTE_AUDIO_ADD playerContext.play()', stream)
  1144. this._emitter.emit(EVENT.REMOTE_AUDIO_ADD, { userID: stream.userID, streamType: stream.streamType })
  1145. })
  1146. getApp().globalData.rtcParams = {
  1147. userList: event.data.userList,
  1148. streamList: event.data.streamList,
  1149. }
  1150. console.log(TAG_NAME, 'REMOTE_AUDIO_ADD', 'streamList:', this.data.streamList, 'userList:', this.data.userList)
  1151. })
  1152. // 音频不可用
  1153. this.userController.on(EVENT.REMOTE_AUDIO_REMOVE, (event)=>{
  1154. console.log(TAG_NAME, '远端音频移除', event, event.data.stream.userID)
  1155. const stream = event.data.stream
  1156. this._setList({
  1157. userList: event.data.userList,
  1158. streamList: event.data.streamList,
  1159. }).then(() => {
  1160. // 有可能先触发了退房事件,用户名下的所有stream都已清除
  1161. if (stream.userID && stream.streamType) {
  1162. this._emitter.emit(EVENT.REMOTE_AUDIO_REMOVE, { userID: stream.userID, streamType: stream.streamType })
  1163. }
  1164. })
  1165. console.log(TAG_NAME, 'REMOTE_AUDIO_REMOVE', 'streamList:', this.data.streamList, 'userList:', this.data.userList)
  1166. })
  1167. },
  1168. /**
  1169. * pusher event handler
  1170. * @param {*} event 事件实例
  1171. */
  1172. _pusherStateChangeHandler(event) {
  1173. const code = event.detail.code
  1174. const message = event.detail.message
  1175. console.log(TAG_NAME, 'pusherStateChange:', code, event)
  1176. switch (code) {
  1177. case 0: // 未知状态码,不做处理
  1178. console.log(TAG_NAME, message, code)
  1179. break
  1180. case 1001:
  1181. console.log(TAG_NAME, '已经连接推流服务器', code)
  1182. break
  1183. case 1002:
  1184. console.log(TAG_NAME, '已经与服务器握手完毕,开始推流', code)
  1185. break
  1186. case 1003:
  1187. console.log(TAG_NAME, '打开摄像头成功', code)
  1188. break
  1189. case 1004:
  1190. console.log(TAG_NAME, '录屏启动成功', code)
  1191. break
  1192. case 1005:
  1193. console.log(TAG_NAME, '推流动态调整分辨率', code)
  1194. break
  1195. case 1006:
  1196. console.log(TAG_NAME, '推流动态调整码率', code)
  1197. break
  1198. case 1007:
  1199. console.log(TAG_NAME, '首帧画面采集完成', code)
  1200. break
  1201. case 1008:
  1202. console.log(TAG_NAME, '编码器启动', code)
  1203. break
  1204. case 1018:
  1205. console.log(TAG_NAME, '进房成功', code)
  1206. this._emitter.emit(EVENT.LOCAL_JOIN, { userID: this.data.pusher.userID })
  1207. break
  1208. case 1019:
  1209. console.log(TAG_NAME, '退出房间', code)
  1210. // 20200421 iOS 仍然没有1019事件通知退房,退房事件移动到 exitRoom 方法里,但不是后端通知的退房成功
  1211. // this._emitter.emit(EVENT.LOCAL_LEAVE, { userID: this.data.pusher.userID })
  1212. break
  1213. case 2003:
  1214. console.log(TAG_NAME, '渲染首帧视频', code)
  1215. break
  1216. case 1020:
  1217. case 1031:
  1218. case 1032:
  1219. case 1033:
  1220. case 1034:
  1221. // 通过 userController 处理 1020 1031 1032 1033 1034
  1222. this.userController.userEventHandler(event)
  1223. break
  1224. case -1301:
  1225. console.error(TAG_NAME, '打开摄像头失败: ', code)
  1226. this._emitter.emit(EVENT.ERROR, { code, message })
  1227. break
  1228. case -1302:
  1229. console.error(TAG_NAME, '打开麦克风失败: ', code)
  1230. this._emitter.emit(EVENT.ERROR, { code, message })
  1231. break
  1232. case -1303:
  1233. console.error(TAG_NAME, '视频编码失败: ', code)
  1234. this._emitter.emit(EVENT.ERROR, { code, message })
  1235. break
  1236. case -1304:
  1237. console.error(TAG_NAME, '音频编码失败: ', code)
  1238. this._emitter.emit(EVENT.ERROR, { code, message })
  1239. break
  1240. case -1307:
  1241. console.error(TAG_NAME, '推流连接断开: ', code)
  1242. this._emitter.emit(EVENT.ERROR, { code, message })
  1243. break
  1244. case -100018:
  1245. console.error(TAG_NAME, '进房失败: userSig 校验失败,请检查 userSig 是否填写正确', code, message)
  1246. this._emitter.emit(EVENT.ERROR, { code, message })
  1247. break
  1248. case 5000:
  1249. console.log(TAG_NAME, '小程序被挂起: ', code)
  1250. // 20200421 iOS 微信点击胶囊圆点会触发该事件
  1251. // 触发 5000 后,底层SDK会退房,返回前台后会自动进房
  1252. break
  1253. case 5001:
  1254. // 20200421 仅有 Android 微信会触发该事件
  1255. console.log(TAG_NAME, '小程序悬浮窗被关闭: ', code)
  1256. this.status.isPending = true
  1257. if (this.status.isPush) {
  1258. this.exitRoom()
  1259. }
  1260. break
  1261. case 1021:
  1262. console.log(TAG_NAME, '网络类型发生变化,需要重新进房', code)
  1263. break
  1264. case 2007:
  1265. console.log(TAG_NAME, '本地视频播放loading: ', code)
  1266. break
  1267. case 2004:
  1268. console.log(TAG_NAME, '本地视频播放开始: ', code)
  1269. break
  1270. default:
  1271. console.log(TAG_NAME, message, code)
  1272. }
  1273. },
  1274. _pusherNetStatusHandler(event) {
  1275. // 触发 LOCAL_NET_STATE_UPDATE
  1276. this._emitter.emit(EVENT.LOCAL_NET_STATE_UPDATE, event)
  1277. },
  1278. _pusherErrorHandler(event) {
  1279. // 触发 ERROR
  1280. console.warn(TAG_NAME, 'pusher error', event)
  1281. try {
  1282. const code = event.detail.errCode
  1283. const message = event.detail.errMsg
  1284. this._emitter.emit(EVENT.ERROR, { code, message })
  1285. } catch (exception) {
  1286. console.error(TAG_NAME, 'pusher error data parser exception', event, exception)
  1287. }
  1288. },
  1289. _pusherBGMStartHandler(event) {
  1290. // 触发 BGM_START 已经在playBGM方法中进行处理
  1291. // this._emitter.emit(EVENT.BGM_PLAY_START, { data: event })
  1292. },
  1293. _pusherBGMProgressHandler(event) {
  1294. // BGM_PROGRESS
  1295. this._emitter.emit(EVENT.BGM_PLAY_PROGRESS, event)
  1296. },
  1297. _pusherBGMCompleteHandler(event) {
  1298. // BGM_COMPLETE
  1299. this._emitter.emit(EVENT.BGM_PLAY_COMPLETE, event)
  1300. },
  1301. _pusherAudioVolumeNotify: function(event) {
  1302. // console.log(TAG_NAME, '_pusherAudioVolumeNotify', event)
  1303. this._emitter.emit(EVENT.LOCAL_AUDIO_VOLUME_UPDATE, event)
  1304. },
  1305. // player event handler
  1306. // 获取 player ID 再进行触发
  1307. _playerStateChange(event) {
  1308. // console.log(TAG_NAME, '_playerStateChange', event)
  1309. this._emitter.emit(EVENT.REMOTE_STATE_UPDATE, event)
  1310. },
  1311. _playerFullscreenChange(event) {
  1312. // console.log(TAG_NAME, '_playerFullscreenChange', event)
  1313. this._emitter.emit(EVENT.REMOTE_FULLSCREEN_UPDATE, event)
  1314. this._emitter.emit(EVENT.VIDEO_FULLSCREEN_UPDATE, event)
  1315. },
  1316. _playerNetStatus(event) {
  1317. // console.log(TAG_NAME, '_playerNetStatus', event)
  1318. // 获取player 视频的宽高
  1319. const stream = this.userController.getStream({
  1320. userID: event.currentTarget.dataset.userid,
  1321. streamType: event.currentTarget.dataset.streamtype,
  1322. })
  1323. if (stream && (stream.videoWidth !== event.detail.info.videoWidth || stream.videoHeight !== event.detail.info.videoHeight)) {
  1324. console.log(TAG_NAME, '_playerNetStatus update video size', event)
  1325. stream.videoWidth = event.detail.info.videoWidth
  1326. stream.videoHeight = event.detail.info.videoHeight
  1327. }
  1328. this._emitter.emit(EVENT.REMOTE_NET_STATE_UPDATE, event)
  1329. },
  1330. _playerAudioVolumeNotify(event) {
  1331. // console.log(TAG_NAME, '_playerAudioVolumeNotify', event)
  1332. this._emitter.emit(EVENT.REMOTE_AUDIO_VOLUME_UPDATE, event)
  1333. },
  1334. _filterVisibleStream(streamList, skipPagination) {
  1335. const list = streamList.filter((item) => {
  1336. // 全部显示
  1337. // return true
  1338. // 只显示有视频或者有音频的 stream
  1339. return (item.hasVideo || item.hasAudio)
  1340. })
  1341. // 按 userID 进行排序
  1342. list.sort((item1, item2)=>{
  1343. const id1 = item1.userID.toUpperCase()
  1344. const id2 = item2.userID.toUpperCase()
  1345. if (id1 < id2) {
  1346. return -1
  1347. }
  1348. if (id1 > id2) {
  1349. return 1
  1350. }
  1351. return 0
  1352. })
  1353. if (this.data.template === 'grid' && !skipPagination) {
  1354. this._filterGridPageVisibleStream(list)
  1355. // console.log(TAG_NAME, '_filterVisibleStream gridPagePlaceholderStreamList:', this.data.gridPagePlaceholderStreamList)
  1356. if (// list.length > this.data.gridPlayerPerPage - 2 &&
  1357. this.data.gridCurrentPage > 1 &&
  1358. this.data.gridPagePlaceholderStreamList.length === this.data.gridPlayerPerPage) {
  1359. // 如果stream 数量大于每页可显示数量,当前页面已经没有可显示的stream(占位数量==3) 回到上一个页面。
  1360. this._gridPageToPrev(list)
  1361. }
  1362. }
  1363. // console.log(TAG_NAME, '_filterVisibleStream list:', list)
  1364. return list
  1365. },
  1366. _filterGridPageVisibleStream(list) {
  1367. // 最多只显示 gridPlayerPerPage 个stream
  1368. const length = list.length
  1369. // +1 pusher
  1370. this.data.gridPageCount = Math.ceil((length + 1) / this.data.gridPlayerPerPage)
  1371. this.data.gridPagePlaceholderStreamList = []
  1372. let visibleCount = 0
  1373. // 需要显示的player区间
  1374. let interval
  1375. if (this.data.gridPlayerPerPage > 3) {
  1376. if (this.data.gridCurrentPage === 1) {
  1377. interval = [-1, this.data.gridPlayerPerPage - 1]
  1378. } else {
  1379. // 每页显示4个时,第一页显示3个,pusher只在第一页
  1380. // -1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
  1381. // 1 2 3 4
  1382. // -1 3
  1383. // 2 7
  1384. // 6 11
  1385. interval = [this.data.gridCurrentPage * this.data.gridPlayerPerPage - (this.data.gridPlayerPerPage + 2), this.data.gridCurrentPage * this.data.gridPlayerPerPage - 1]
  1386. }
  1387. } else {
  1388. // 每页显示3个,每页都有pusher
  1389. interval = [this.data.gridCurrentPage * this.data.gridPlayerPerPage - (this.data.gridPlayerPerPage + 1), this.data.gridCurrentPage * this.data.gridPlayerPerPage]
  1390. }
  1391. for (let i = 0; i < length; i++) {
  1392. if ( i > interval[0] && i < interval[1]) {
  1393. list[i].isVisible = true
  1394. list[i].muteVideo = list[i].muteVideoPrev === undefined ? list[i].muteVideo : list[i].muteVideoPrev
  1395. visibleCount++
  1396. } else {
  1397. list[i].isVisible = false
  1398. list[i].muteVideo = true
  1399. }
  1400. }
  1401. // 第一页,不需要占位
  1402. if (this.data.gridCurrentPage !== 1) {
  1403. for (let i = 0; i < this.data.gridPlayerPerPage - visibleCount; i++) {
  1404. this.data.gridPagePlaceholderStreamList.push({ id: 'holder-' + i })
  1405. }
  1406. }
  1407. return list
  1408. },
  1409. /**
  1410. * 保持屏幕常亮
  1411. */
  1412. _keepScreenOn() {
  1413. setInterval(() => {
  1414. wx.setKeepScreenOn({
  1415. keepScreenOn: true,
  1416. })
  1417. }, 20000)
  1418. },
  1419. // ______ __ __ ______ __ __
  1420. // | \| \ / \ | \ | \ | \
  1421. // \$$$$$$| $$\ / $$ \$$$$$$ _______ _| $$_ ______ ______ _______ ______ | $$
  1422. // | $$ | $$$\ / $$$ | $$ | \| $$ \ / \ / \ | \ | \ | $$
  1423. // | $$ | $$$$\ $$$$ | $$ | $$$$$$$\\$$$$$$ | $$$$$$\| $$$$$$\| $$$$$$$\ \$$$$$$\| $$
  1424. // | $$ | $$\$$ $$ $$ | $$ | $$ | $$ | $$ __ | $$ $$| $$ \$$| $$ | $$ / $$| $$
  1425. // _| $$_ | $$ \$$$| $$ _| $$_ | $$ | $$ | $$| \| $$$$$$$$| $$ | $$ | $$| $$$$$$$| $$
  1426. // | $$ \| $$ \$ | $$ | $$ \| $$ | $$ \$$ $$ \$$ \| $$ | $$ | $$ \$$ $$| $$
  1427. // \$$$$$$ \$$ \$$ \$$$$$$ \$$ \$$ \$$$$ \$$$$$$$ \$$ \$$ \$$ \$$$$$$$ \$$
  1428. /**
  1429. * 初始化 IM SDK
  1430. * @param {Object} config sdkAppID
  1431. */
  1432. _initIM(config) {
  1433. if (!config.enableIM || !config.sdkAppID || this.tim) {
  1434. return
  1435. }
  1436. console.log(TAG_NAME, '_initIM', config)
  1437. // 初始化 sdk 实例
  1438. const tim = TIM.create({
  1439. SDKAppID: config.sdkAppID,
  1440. })
  1441. // 0 普通级别,日志量较多,接入时建议使用
  1442. // 1 release级别,SDK 输出关键信息,生产环境时建议使用
  1443. // 2 告警级别,SDK 只输出告警和错误级别的日志
  1444. // 3 错误级别,SDK 只输出错误级别的日志
  1445. // 4 无日志级别,SDK 将不打印任何日志
  1446. if (config.debugMode) {
  1447. tim.setLogLevel(1)
  1448. } else {
  1449. tim.setLogLevel(4)
  1450. }
  1451. // 取消监听
  1452. tim.off(TIM.EVENT.SDK_READY, this._onIMReady)
  1453. tim.off(TIM.EVENT.MESSAGE_RECEIVED, this._onIMMessageReceived)
  1454. tim.off(TIM.EVENT.SDK_NOT_READY, this._onIMNotReady)
  1455. tim.off(TIM.EVENT.KICKED_OUT, this._onIMKickedOut)
  1456. tim.off(TIM.EVENT.ERROR, this._onIMError)
  1457. // 监听事件
  1458. tim.on(TIM.EVENT.SDK_READY, this._onIMReady, this)
  1459. tim.on(TIM.EVENT.MESSAGE_RECEIVED, this._onIMMessageReceived, this)
  1460. tim.on(TIM.EVENT.SDK_NOT_READY, this._onIMNotReady, this)
  1461. tim.on(TIM.EVENT.KICKED_OUT, this._onIMKickedOut, this)
  1462. tim.on(TIM.EVENT.ERROR, this._onIMError, this)
  1463. this.tim = tim
  1464. wx.tim = tim
  1465. },
  1466. _loginIM(params) {
  1467. if (!this.tim) {
  1468. return
  1469. }
  1470. console.log(TAG_NAME, '_loginIM', params)
  1471. return this.tim.login({
  1472. userID: params.userID,
  1473. userSig: params.userSig,
  1474. })
  1475. },
  1476. _logoutIM() {
  1477. if (!this.tim) {
  1478. return
  1479. }
  1480. console.log(TAG_NAME, '_logoutIM')
  1481. return this.tim.logout()
  1482. },
  1483. _exitIM() {
  1484. // 方法需要调用限制,否则重复解散群 退群会有warn
  1485. if (this.data.exitIMThrottle || !this.tim) {
  1486. return
  1487. }
  1488. this.data.exitIMThrottle = true
  1489. const userList = this.getRemoteUserList()
  1490. const roomID = this.data.config.roomID
  1491. const userID = this.data.config.userID
  1492. this._searchGroup({ roomID }).then((imResponse) => {
  1493. // 查询群资料,判断是否为群主
  1494. if (imResponse.data.group.ownerID === userID && userList.length === 0) {
  1495. // 如果 userList 为 0 群主可以解散群,并登出IM
  1496. this._dismissGroup({ roomID }).then(()=>{
  1497. this.data.exitIMThrottle = false
  1498. this._logoutIM()
  1499. }).catch((imError) => {
  1500. this.data.exitIMThrottle = false
  1501. this._logoutIM()
  1502. })
  1503. } else if (imResponse.data.group.ownerID === userID) {
  1504. this.data.exitIMThrottle = false
  1505. // 群主不能退群只能登出
  1506. this._logoutIM()
  1507. } else {
  1508. // 普通成员退群并登出IM
  1509. this._quitGroup({ roomID }).then(()=>{
  1510. this.data.exitIMThrottle = false
  1511. this._logoutIM()
  1512. }).catch((imError) => {
  1513. this.data.exitIMThrottle = false
  1514. this._logoutIM()
  1515. })
  1516. }
  1517. }).catch((imError) => {
  1518. this.data.exitIMThrottle = false
  1519. // 查询异常直接登出
  1520. this._logoutIM()
  1521. })
  1522. },
  1523. _searchGroup(params) {
  1524. if (!this.tim) {
  1525. return
  1526. }
  1527. console.log(TAG_NAME, '_searchGroup', params)
  1528. const tim = this.tim
  1529. const promise = tim.searchGroupByID(params.roomID + '')
  1530. promise.then(function(imResponse) {
  1531. // const group = imResponse.data.group // 群组信息
  1532. console.log(TAG_NAME, '_searchGroup success', imResponse)
  1533. }).catch(function(imError) {
  1534. console.warn(TAG_NAME, '_searchGroup fail,TIM 报错信息不影响后续逻辑,可以忽略', imError) // 搜素群组失败的相关信息
  1535. })
  1536. return promise
  1537. },
  1538. /**
  1539. * 创建 AVchatroom
  1540. * @param {*} params roomID
  1541. * @returns {Promise}
  1542. */
  1543. _createGroup(params) {
  1544. if (!this.tim) {
  1545. return
  1546. }
  1547. console.log(TAG_NAME, '_createGroup', params)
  1548. const promise = this.tim.createGroup({
  1549. groupID: params.roomID + '',
  1550. name: params.roomID + '',
  1551. type: IM_GROUP_TYPE,
  1552. })
  1553. promise.then((imResponse) => { // 创建成功
  1554. console.log(TAG_NAME, '_createGroup success', imResponse.data.group) // 创建的群的资料
  1555. }).catch((imError) => {
  1556. console.warn(TAG_NAME, '_createGroup error', imError) // 创建群组失败的相关信息
  1557. })
  1558. return promise
  1559. },
  1560. /**
  1561. * 进入 AVchatroom
  1562. * @param {*} params roomID
  1563. * @returns {Promise}
  1564. */
  1565. _joinGroup(params) {
  1566. if (!this.tim) {
  1567. return
  1568. }
  1569. console.log(TAG_NAME, '_joinGroup', params)
  1570. const promise = this.tim.joinGroup({ groupID: params.roomID + '', type: IM_GROUP_TYPE })
  1571. promise.then((imResponse) => {
  1572. switch (imResponse.data.status) {
  1573. case TIM.TYPES.JOIN_STATUS_WAIT_APPROVAL: // 等待管理员同意
  1574. break
  1575. case TIM.TYPES.JOIN_STATUS_SUCCESS: // 加群成功
  1576. case TIM.TYPES.JOIN_STATUS_ALREADY_IN_GROUP: // 已经在群中
  1577. // console.log(imResponse.data.group) // 加入的群组资料
  1578. // wx.showToast({
  1579. // title: '进群成功',
  1580. // })
  1581. console.log(TAG_NAME, '_joinGroup success', imResponse)
  1582. break
  1583. default:
  1584. break
  1585. }
  1586. }).catch((imError) => {
  1587. console.warn(TAG_NAME, 'joinGroup error', imError) // 申请加群失败的相关信息
  1588. })
  1589. return promise
  1590. },
  1591. _quitGroup(params) {
  1592. if (!this.tim) {
  1593. return
  1594. }
  1595. console.log(TAG_NAME, '_quitGroup', params)
  1596. const promise = this.tim.quitGroup(params.roomID + '')
  1597. promise.then((imResponse) => {
  1598. console.log(TAG_NAME, '_quitGroup success', imResponse)
  1599. }).catch((imError) => {
  1600. console.warn(TAG_NAME, 'quitGroup error', imError)
  1601. })
  1602. return promise
  1603. },
  1604. _dismissGroup(params) {
  1605. if (!this.tim) {
  1606. return
  1607. }
  1608. console.log(TAG_NAME, '_dismissGroup', params)
  1609. const promise = this.tim.dismissGroup(params.roomID + '')
  1610. promise.then((imResponse) => {
  1611. console.log(TAG_NAME, '_dismissGroup success', imResponse)
  1612. }).catch((imError) => {
  1613. console.warn(TAG_NAME, '_dismissGroup error', imError)
  1614. })
  1615. return promise
  1616. },
  1617. _onIMReady(event) {
  1618. console.log(TAG_NAME, 'IM.READY', event)
  1619. this._emitter.emit(EVENT.IM_READY, event)
  1620. const roomID = this.data.config.roomID
  1621. // 查询群组是否存在
  1622. this._searchGroup({ roomID }).then((res) => {
  1623. // console.log(TAG_NAME, 'searchGroup', res)
  1624. // 存在直接进群
  1625. this._joinGroup({ roomID })
  1626. }).catch(() => {
  1627. // 不存在则创建,如果是avchatroom 创建后进群
  1628. this._createGroup({ roomID }).then((res) => {
  1629. // 进群
  1630. this._joinGroup({ roomID })
  1631. }).catch((imError)=> {
  1632. if (imError.code === 10021) {
  1633. console.log(TAG_NAME, '群已存在,直接进群', event)
  1634. this._joinGroup({ roomID })
  1635. }
  1636. })
  1637. })
  1638. // 收到离线消息和会话列表同步完毕通知,接入侧可以调用 sendMessage 等需要鉴权的接口
  1639. // event.name - TIM.EVENT.IM_READY
  1640. },
  1641. _onIMMessageReceived(event) {
  1642. // 收到推送的单聊、群聊、群提示、群系统通知的新消息,可通过遍历 event.data 获取消息列表数据并渲染到页面
  1643. console.log(TAG_NAME, 'IM.MESSAGE_RECEIVED', event)
  1644. // messageList 仅保留10条消息
  1645. const messageData = event.data
  1646. const roomID = this.data.config.roomID + ''
  1647. const userID = this.data.config.userID + ''
  1648. for (let i = 0; i < messageData.length; i++) {
  1649. const message = messageData[i]
  1650. // console.log(TAG_NAME, 'IM.MESSAGE_RECEIVED', message, this.data.config, TIM.TYPES.MSG_TEXT)
  1651. if (message.to === roomID + '' || message.to === userID) {
  1652. // 遍历messageData 获取当前room 或者当前user的消息
  1653. console.log(TAG_NAME, 'IM.MESSAGE_RECEIVED', message, message.type, TIM.TYPES.MSG_TEXT)
  1654. if (message.type === TIM.TYPES.MSG_TEXT) {
  1655. this._pushMessageList({
  1656. name: message.from,
  1657. message: message.payload.text,
  1658. })
  1659. } else {
  1660. if (message.type === TIM.TYPES.MSG_GRP_SYS_NOTICE && message.payload.operationType === 2) {
  1661. // 群系统通知
  1662. this._pushMessageList({
  1663. name: '系统通知',
  1664. message: `欢迎 ${userID}`,
  1665. })
  1666. }
  1667. // 其他消息暂不处理
  1668. }
  1669. }
  1670. }
  1671. this._emitter.emit(EVENT.IM_MESSAGE_RECEIVED, event)
  1672. },
  1673. _onIMNotReady(event) {
  1674. console.log(TAG_NAME, 'IM.NOT_READY', event)
  1675. this._emitter.emit(EVENT.IM_NOT_READY, event)
  1676. // 收到 SDK 进入 not ready 状态通知,此时 SDK 无法正常工作
  1677. // event.name - TIM.EVENT.IM_NOT_READY
  1678. },
  1679. _onIMKickedOut(event) {
  1680. console.log(TAG_NAME, 'IM.KICKED_OUT', event)
  1681. this._emitter.emit(EVENT.IM_KICKED_OUT, event)
  1682. // 收到被踢下线通知
  1683. // event.name - TIM.EVENT.KICKED_OUT
  1684. // event.data.type - 被踢下线的原因,例如 :
  1685. // - TIM.TYPES.KICKED_OUT_MULT_ACCOUNT 多实例登录被踢
  1686. // - TIM.TYPES.KICKED_OUT_MULT_DEVICE 多终端登录被踢
  1687. // - TIM.TYPES.KICKED_OUT_USERSIG_EXPIRED 签名过期被踢。使用前需要将SDK版本升级至v2.4.0或以上。
  1688. },
  1689. _onIMError(event) {
  1690. console.log(TAG_NAME, 'IM.ERROR', event)
  1691. this._emitter.emit(EVENT.IM_ERROR, event)
  1692. // 收到 SDK 发生错误通知,可以获取错误码和错误信息
  1693. // event.name - TIM.EVENT.ERROR
  1694. // event.data.code - 错误码
  1695. // event.data.message - 错误信息
  1696. },
  1697. // ________ __ __
  1698. // | \ | \ | \
  1699. // \$$$$$$$$______ ______ ____ ______ | $$ ______ _| $$_ ______
  1700. // | $$ / \ | \ \ / \ | $$ | \| $$ \ / \
  1701. // | $$ | $$$$$$\| $$$$$$\$$$$\| $$$$$$\| $$ \$$$$$$\\$$$$$$ | $$$$$$\
  1702. // | $$ | $$ $$| $$ | $$ | $$| $$ | $$| $$ / $$ | $$ __ | $$ $$
  1703. // | $$ | $$$$$$$$| $$ | $$ | $$| $$__/ $$| $$| $$$$$$$ | $$| \| $$$$$$$$
  1704. // | $$ \$$ \| $$ | $$ | $$| $$ $$| $$ \$$ $$ \$$ $$ \$$ \
  1705. // \$$ \$$$$$$$ \$$ \$$ \$$| $$$$$$$ \$$ \$$$$$$$ \$$$$ \$$$$$$$
  1706. // | $$
  1707. // | $$
  1708. // \$$
  1709. // 以下为 debug & template 相关函数
  1710. _toggleVideo() {
  1711. if (this.data.pusher.enableCamera) {
  1712. this.unpublishLocalVideo()
  1713. } else {
  1714. this.publishLocalVideo()
  1715. }
  1716. },
  1717. _toggleAudio() {
  1718. if (this.data.pusher.enableMic) {
  1719. this.unpublishLocalAudio()
  1720. } else {
  1721. this.publishLocalAudio()
  1722. }
  1723. },
  1724. _debugToggleRemoteVideo(event) {
  1725. console.log(TAG_NAME, '_debugToggleRemoteVideo', event.currentTarget.dataset)
  1726. const userID = event.currentTarget.dataset.userID
  1727. const streamType = event.currentTarget.dataset.streamType
  1728. const stream = this.data.streamList.find((item)=>{
  1729. return item.userID === userID && item.streamType === streamType
  1730. })
  1731. if (stream.muteVideo) {
  1732. this.subscribeRemoteVideo({ userID, streamType })
  1733. // this.setViewVisible({ userID, streamType, isVisible: true })
  1734. } else {
  1735. this.unsubscribeRemoteVideo({ userID, streamType })
  1736. // this.setViewVisible({ userID, streamType, isVisible: false })
  1737. }
  1738. },
  1739. _debugToggleRemoteAudio(event) {
  1740. console.log(TAG_NAME, '_debugToggleRemoteAudio', event.currentTarget.dataset)
  1741. const userID = event.currentTarget.dataset.userID
  1742. const streamType = event.currentTarget.dataset.streamType
  1743. const stream = this.data.streamList.find((item)=>{
  1744. return item.userID === userID && item.streamType === streamType
  1745. })
  1746. if (stream.muteAudio) {
  1747. this.subscribeRemoteAudio({ userID })
  1748. } else {
  1749. this.unsubscribeRemoteAudio({ userID })
  1750. }
  1751. },
  1752. _debugToggleVideoDebug() {
  1753. this.setData({
  1754. debug: !this.data.debug,
  1755. })
  1756. },
  1757. _debugExitRoom() {
  1758. this.exitRoom()
  1759. },
  1760. _debugEnterRoom() {
  1761. Object.assign(this.data.pusher, this.data.config)
  1762. this.enterRoom({ roomID: this.data.config.roomID }).then(()=>{
  1763. setTimeout(()=>{
  1764. this.publishLocalVideo()
  1765. this.publishLocalAudio()
  1766. }, 2000)
  1767. // 进房后开始推送视频或音频
  1768. })
  1769. },
  1770. _debugGoBack() {
  1771. wx.navigateBack({
  1772. delta: 1,
  1773. })
  1774. },
  1775. _debugTogglePanel() {
  1776. this.setData({
  1777. debugPanel: !this.data.debugPanel,
  1778. })
  1779. },
  1780. _debugSendRandomMessage() {
  1781. const userList = this.getRemoteUserList()
  1782. if (userList.length === 0 || !this.tim) {
  1783. return false
  1784. }
  1785. const roomID = this.data.config.roomID
  1786. const message = `Hello! ${userList[0].userID} ${9999 * Math.random()}`
  1787. const userID = userList[0].userID
  1788. this.sendC2CTextMessage({
  1789. userID: userID,
  1790. message: message,
  1791. })
  1792. const promise = this.sendGroupTextMessage({
  1793. roomID: roomID,
  1794. message: message,
  1795. })
  1796. // 消息上屏
  1797. this._pushMessageList({
  1798. name: userID,
  1799. message: message,
  1800. })
  1801. promise.then(function(imResponse) {
  1802. // 发送成功
  1803. console.log(TAG_NAME, '_debugSendRandomMessage success', imResponse)
  1804. wx.showToast({
  1805. title: '发送成功',
  1806. icon: 'success',
  1807. duration: 1000,
  1808. })
  1809. }).catch(function(imError) {
  1810. // 发送失败
  1811. console.warn(TAG_NAME, '_debugSendRandomMessage error', imError)
  1812. wx.showToast({
  1813. title: '发送失败',
  1814. icon: 'none',
  1815. duration: 1000,
  1816. })
  1817. })
  1818. },
  1819. _toggleAudioVolumeType() {
  1820. if (this.data.pusher.audioVolumeType === 'voicecall') {
  1821. this._setPusherConfig({
  1822. audioVolumeType: 'media',
  1823. })
  1824. } else {
  1825. this._setPusherConfig({
  1826. audioVolumeType: 'voicecall',
  1827. })
  1828. }
  1829. },
  1830. _toggleSoundMode() {
  1831. if (this.data.userList.length === 0 ) {
  1832. return
  1833. }
  1834. const stream = this.userController.getStream({
  1835. userID: this.data.userList[0].userID,
  1836. streamType: 'main',
  1837. })
  1838. if (stream) {
  1839. if (stream.soundMode === 'speaker') {
  1840. stream['soundMode'] = 'ear'
  1841. } else {
  1842. stream['soundMode'] = 'speaker'
  1843. }
  1844. this._setPlayerConfig({
  1845. userID: stream.userID,
  1846. streamType: 'main',
  1847. config: {
  1848. soundMode: stream['soundMode'],
  1849. },
  1850. })
  1851. }
  1852. },
  1853. /**
  1854. * 退出通话
  1855. */
  1856. _hangUp() {
  1857. this.exitRoom()
  1858. wx.navigateBack({
  1859. delta: 1,
  1860. })
  1861. },
  1862. /**
  1863. * 切换订阅音频状态
  1864. */
  1865. handleSubscribeAudio() {
  1866. if (this.data.pusher.enableMic) {
  1867. this.unpublishLocalAudio()
  1868. } else {
  1869. this.publishLocalAudio()
  1870. }
  1871. },
  1872. /**
  1873. * 切换订阅远端视频状态
  1874. * @param {Object} event native 事件对象
  1875. */
  1876. _handleSubscribeRemoteVideo(event) {
  1877. const userID = event.currentTarget.dataset.userID
  1878. const streamType = event.currentTarget.dataset.streamType
  1879. const stream = this.data.streamList.find((item)=>{
  1880. return item.userID === userID && item.streamType === streamType
  1881. })
  1882. if (stream.muteVideo) {
  1883. this.subscribeRemoteVideo({ userID, streamType })
  1884. } else {
  1885. this.unsubscribeRemoteVideo({ userID, streamType })
  1886. }
  1887. },
  1888. /**
  1889. *
  1890. * @param {Object} event native 事件对象
  1891. */
  1892. _handleSubscribeRemoteAudio(event) {
  1893. const userID = event.currentTarget.dataset.userID
  1894. const streamType = event.currentTarget.dataset.streamType
  1895. const stream = this.data.streamList.find((item)=>{
  1896. return item.userID === userID && item.streamType === streamType
  1897. })
  1898. if (stream.muteAudio) {
  1899. this.subscribeRemoteAudio({ userID })
  1900. } else {
  1901. this.unsubscribeRemoteAudio({ userID })
  1902. }
  1903. },
  1904. /**
  1905. * grid布局, 唤起 memberlist-panel
  1906. */
  1907. _switchMemberListPanel() {
  1908. this.setData({
  1909. panelName: this.data.panelName !== 'memberlist-panel' ? 'memberlist-panel' : '',
  1910. })
  1911. },
  1912. /**
  1913. * grid布局, 唤起 setting-panel
  1914. */
  1915. _switchSettingPanel() {
  1916. this.setData({
  1917. panelName: this.data.panelName !== 'setting-panel' ? 'setting-panel' : '',
  1918. })
  1919. },
  1920. _switchBGMPanel() {
  1921. this.setData({
  1922. panelName: this.data.panelName !== 'bgm-panel' ? 'bgm-panel' : '',
  1923. })
  1924. },
  1925. _handleMaskerClick() {
  1926. this.setData({
  1927. panelName: '',
  1928. })
  1929. },
  1930. _setPuserProperty(event) {
  1931. console.log(TAG_NAME, '_setPuserProperty', event)
  1932. const key = event.currentTarget.dataset.key
  1933. const valueType = event.currentTarget.dataset.valueType
  1934. let value = event.currentTarget.dataset.value
  1935. const config = {}
  1936. if (valueType === 'boolean') {
  1937. value = value === 'true' ? true : false
  1938. config[key] = !this.data.pusher[key]
  1939. }
  1940. if (valueType === 'number' && value.indexOf('|') > 0) {
  1941. value = value.split('|')
  1942. // console.log(this.data.pusher, this.data.pusher[key], key, value)
  1943. if ( this.data.pusher[key] === Number(value[0])) {
  1944. config[key] = Number(value[1])
  1945. } else {
  1946. config[key] = Number(value[0])
  1947. }
  1948. }
  1949. if (valueType === 'string' && value.indexOf('|') > 0) {
  1950. value = value.split('|')
  1951. if ( this.data.pusher[key] === value[0]) {
  1952. config[key] = value[1]
  1953. } else {
  1954. config[key] = value[0]
  1955. }
  1956. }
  1957. this._setPusherConfig(config)
  1958. },
  1959. _setPlayerProperty(event) {
  1960. console.log(TAG_NAME, '_setPlayerProperty', event)
  1961. const userID = event.currentTarget.dataset.userid
  1962. const streamType = event.currentTarget.dataset.streamtype
  1963. const key = event.currentTarget.dataset.key
  1964. let value = event.currentTarget.dataset.value
  1965. const stream = this.userController.getStream({
  1966. userID: userID,
  1967. streamType: streamType,
  1968. })
  1969. if (!stream) {
  1970. return
  1971. }
  1972. const config = {}
  1973. if (value === 'true') {
  1974. value = true
  1975. } else if (value === 'false') {
  1976. value = false
  1977. }
  1978. if (typeof value === 'boolean') {
  1979. config[key] = !stream[key]
  1980. } else if (typeof value === 'string' && value.indexOf('|') > 0) {
  1981. value = value.split('|')
  1982. if (stream[key] === value[0]) {
  1983. config[key] = value[1]
  1984. } else {
  1985. config[key] = value[0]
  1986. }
  1987. }
  1988. console.log(TAG_NAME, '_setPlayerProperty', config)
  1989. this._setPlayerConfig({ userID, streamType, config })
  1990. },
  1991. _changeProperty(event) {
  1992. const propertyName = event.currentTarget.dataset.propertyName
  1993. const newData = {}
  1994. newData[propertyName] = event.detail.value
  1995. this.setData(newData)
  1996. const volume = newData[propertyName] / 100
  1997. switch (propertyName) {
  1998. case 'MICVolume':
  1999. this.setMICVolume({ volume })
  2000. break
  2001. case 'BGMVolume':
  2002. this.setBGMVolume({ volume })
  2003. break
  2004. }
  2005. },
  2006. _switchStreamType(event) {
  2007. const userID = event.currentTarget.dataset.userid
  2008. const streamType = event.currentTarget.dataset.streamtype
  2009. const stream = this.userController.getStream({
  2010. userID: userID,
  2011. streamType: streamType,
  2012. })
  2013. if (stream && stream.streamType === 'main') {
  2014. if (stream._definitionType === 'small') {
  2015. this.subscribeRemoteVideo({ userID, streamType: 'main' })
  2016. } else {
  2017. this.subscribeRemoteVideo({ userID, streamType: 'small' })
  2018. }
  2019. }
  2020. },
  2021. _handleSnapshotClick(event) {
  2022. wx.showToast({
  2023. title: '开始截屏',
  2024. icon: 'none',
  2025. duration: 1000,
  2026. })
  2027. const userID = event.currentTarget.dataset.userid
  2028. const streamType = event.currentTarget.dataset.streamtype
  2029. this.snapshot({ userID, streamType })
  2030. },
  2031. /**
  2032. * grid布局, 绑定事件
  2033. */
  2034. _gridBindEvent() {
  2035. // 远端音量变更
  2036. this.on(EVENT.REMOTE_AUDIO_VOLUME_UPDATE, (event) => {
  2037. const data = event.data
  2038. const userID = data.currentTarget.dataset.userid
  2039. const streamType = data.currentTarget.dataset.streamtype
  2040. const volume = data.detail.volume
  2041. // console.log(TAG_NAME, '远端音量变更', userID, streamType, volume, event)
  2042. const stream = this.userController.getStream({
  2043. userID: userID,
  2044. streamType: streamType === 'aux' ? 'main' : streamType, // 远端推辅流后,音量回调会从辅流的 player 返回,而不是主流player 返回。需要等 native SDK修复。
  2045. })
  2046. if (stream) {
  2047. stream.volume = volume
  2048. }
  2049. this.setData({
  2050. streamList: this.data.streamList,
  2051. visibleStreamList: this._filterVisibleStream(this.data.streamList, true),
  2052. }, () => {
  2053. })
  2054. })
  2055. this.on(EVENT.BGM_PLAY_PROGRESS, (event) => {
  2056. // console.log(TAG_NAME, '_gridBindEvent on BGM_PLAY_PROGRESS', event)
  2057. const BGMProgress = event.data.detail.progress / event.data.detail.duration * 100
  2058. this.setData({ BGMProgress })
  2059. })
  2060. this.on(EVENT.LOCAL_AUDIO_VOLUME_UPDATE, (event) => {
  2061. // console.log(TAG_NAME, '_gridBindEvent on LOCAL_AUDIO_VOLUME_UPDATE', event)
  2062. // const data = event.data
  2063. const volume = event.data.detail.volume
  2064. // 避免频繁输出log
  2065. this._setPusherConfig({ volume }, true)
  2066. })
  2067. },
  2068. _handleGridTouchStart(event) {
  2069. touchX = event.changedTouches[0].clientX
  2070. touchY = event.changedTouches[0].clientY
  2071. },
  2072. _handleGridTouchEnd(event) {
  2073. const x = event.changedTouches[0].clientX
  2074. const y = event.changedTouches[0].clientY
  2075. if (x - touchX > 50 && Math.abs(y - touchY) < 50) {
  2076. // console.log(TAG_NAME, '向右滑 当前页面', this.data.gridCurrentPage, this.data.gridPageCount)
  2077. this._gridPagePrev()
  2078. } else if (x - touchX < -50 && Math.abs(y - touchY) < 50) {
  2079. // console.log(TAG_NAME, '向左滑 当前页面', this.data.gridCurrentPage, this.data.gridPageCount)
  2080. this._gridPageNext()
  2081. }
  2082. },
  2083. _gridPageToPrev(streamList) {
  2084. const visibleStreamList = this._filterGridPageVisibleStream(streamList)
  2085. if (this.data.gridPagePlaceholderStreamList.length === this.data.gridPlayerPerPage) {
  2086. this.data.gridCurrentPage--
  2087. this._gridPageToPrev(streamList)
  2088. } else {
  2089. return visibleStreamList
  2090. }
  2091. },
  2092. _gridPageNext() {
  2093. this.data.gridCurrentPage++
  2094. if (this.data.gridCurrentPage > this.data.gridPageCount) {
  2095. this.data.gridCurrentPage = 1
  2096. }
  2097. this._gridPageSetData()
  2098. },
  2099. _gridPagePrev() {
  2100. this.data.gridCurrentPage--
  2101. if (this.data.gridCurrentPage < 1) {
  2102. this.data.gridCurrentPage = this.data.gridPageCount
  2103. }
  2104. this._gridPageSetData()
  2105. },
  2106. _gridPageSetData() {
  2107. this._gridShowPageTips()
  2108. const visibleStreamList = this._filterVisibleStream(this.data.streamList)
  2109. this.setData({
  2110. gridCurrentPage: this.data.gridCurrentPage,
  2111. gridPageCount: this.data.gridPageCount,
  2112. visibleStreamList: visibleStreamList,
  2113. streamList: this.data.streamList,
  2114. gridPagePlaceholderStreamList: this.data.gridPagePlaceholderStreamList,
  2115. }, () => {
  2116. })
  2117. },
  2118. _gridShowPageTips(event) {
  2119. if (this.data.gridPageCount < 2) {
  2120. return
  2121. }
  2122. console.log(TAG_NAME, '_gridShowPageTips', this.data)
  2123. if (this.data.hasGridPageTipsShow) {
  2124. clearTimeout(this.data.hasGridPageTipsShow)
  2125. }
  2126. this.animate('.pages-container', [
  2127. { opacity: 1 },
  2128. ], 100, ()=>{
  2129. })
  2130. this.data.hasGridPageTipsShow = setTimeout(()=>{
  2131. this.animate('.pages-container', [
  2132. { opacity: 1 },
  2133. { opacity: 0.3 },
  2134. ], 600, ()=>{
  2135. })
  2136. }, 3000)
  2137. },
  2138. _toggleFullscreen(event) {
  2139. console.log(TAG_NAME, '_toggleFullscreen', event)
  2140. const userID = event.currentTarget.dataset.userID
  2141. const streamType = event.currentTarget.dataset.streamType
  2142. if (this._isFullscreen) {
  2143. this.exitFullscreen({ userID, streamType }).then(() => {
  2144. this._isFullscreen = false
  2145. }).catch(() => {
  2146. })
  2147. } else {
  2148. // const stream = this.userController.getStream({ userID, streamType })
  2149. const direction = 0
  2150. // 已知问题:视频的尺寸需要等待player触发NetStatus事件才能获取到,如果进房就双击全屏,全屏后的方向有可能不对。
  2151. // if (stream && stream.videoWidth && stream.videoHeight) {
  2152. // // 如果是横视频,全屏时进行横屏处理。如果是竖视频,则为0
  2153. // direction = stream.videoWidth > stream.videoHeight ? 90 : 0
  2154. // }
  2155. this.enterFullscreen({ userID, streamType, direction }).then(() => {
  2156. this._isFullscreen = true
  2157. }).catch(() => {
  2158. })
  2159. }
  2160. },
  2161. _toggleMoreMenu() {
  2162. this.setData({
  2163. isShowMoreMenu: !this.data.isShowMoreMenu,
  2164. })
  2165. },
  2166. _toggleIMPanel() {
  2167. if (!this.data.enableIM) {
  2168. wx.showToast({
  2169. icon: 'none',
  2170. title: '当前没有开启IM功能,请设置 enableIM:true',
  2171. })
  2172. }
  2173. this.setData({
  2174. showIMPanel: !this.data.showIMPanel,
  2175. })
  2176. },
  2177. _handleBGMOperation(event) {
  2178. const operationName = event.currentTarget.dataset.operationName
  2179. if (this[operationName]) {
  2180. this[operationName]({ url: 'https://trtc-1252463788.cos.ap-guangzhou.myqcloud.com/web/assets/bgm-test.mp3' })
  2181. }
  2182. },
  2183. _selectBeautyStyle: function(event) {
  2184. console.log(TAG_NAME, '_selectBeautyStyle', event)
  2185. // this.data.beauty = (event.detail.value === 'close' ? 0 : 9)
  2186. const value = event.detail.value
  2187. this.setData({
  2188. // beauty: (value === 'close' ? 0 : 9),
  2189. beautyStyle: value,
  2190. }, () => {
  2191. this._setPusherConfig({
  2192. beautyLevel: value === 'close' ? 0 : 9,
  2193. beautyStyle: value === 'close' ? 'smooth' : value,
  2194. })
  2195. })
  2196. },
  2197. _selectAudioReverbType: function(event) {
  2198. console.log(TAG_NAME, '_selectAudioReverbType', event)
  2199. const audioReverbType = parseInt(event.detail.value)
  2200. this._setPusherConfig({ audioReverbType })
  2201. },
  2202. _sendIMMessage(event) {
  2203. console.log(TAG_NAME, '_sendIMMessage', event)
  2204. if (!this.data.messageContent) {
  2205. return
  2206. }
  2207. const roomID = this.data.config.roomID
  2208. const message = this.data.messageContent
  2209. const userID = this.data.config.userID
  2210. this.sendGroupTextMessage({ roomID, message })
  2211. // 消息上屏
  2212. this._pushMessageList({
  2213. name: userID,
  2214. message: message,
  2215. })
  2216. this.setData({
  2217. messageContent: '',
  2218. })
  2219. },
  2220. _inputIMMessage(event) {
  2221. // console.log(TAG_NAME, '_inputIMMessage', event)
  2222. this.setData({
  2223. messageContent: event.detail.value,
  2224. })
  2225. },
  2226. _pushMessageList(params) {
  2227. if (this.data.messageList.length === this.data.maxMessageListLength) {
  2228. this.data.messageList.shift()
  2229. }
  2230. this.data.messageList.push(params)
  2231. this.setData({
  2232. messageList: this.data.messageList,
  2233. messageListScrollTop: this.data.messageList.length * 100,
  2234. }, () => {
  2235. })
  2236. },
  2237. },
  2238. })