添加音视频发送信息

This commit is contained in:
bobobobo
2026-02-09 02:10:27 +08:00
parent bed88896f8
commit eb57bfb6b4
8 changed files with 1147 additions and 901 deletions

View File

@@ -11,13 +11,14 @@
TUIFriendService, TUIFriendService,
TUIChatService TUIChatService
} from '@tencentcloud/chat-uikit-engine-lite' } from '@tencentcloud/chat-uikit-engine-lite'
import { useUserStore } from '../../../../../stores/user'
const props = withDefaults( const props = withDefaults(
defineProps<{ defineProps<{
/** 通话状态: 0 语音 1 视频 */ /** 通话状态: 0 语音 1 视频 */
type ?: '0' | '1' type?: '0' | '1'
/** 信息数据 */ /** 信息数据 */
currentConversation ?: IConversationModel currentConversation?: IConversationModel
}>(), }>(),
{ {
type: '0', type: '0',
@@ -25,6 +26,8 @@
} }
) )
const { updateCallMode } = useUserStore()
/** 语音通话状态 */ /** 语音通话状态 */
const isType = computed(() => props.type === '0') const isType = computed(() => props.type === '0')
@@ -37,34 +40,34 @@
container?.value?.toggleDialogDisplay(false) container?.value?.toggleDialogDisplay(false)
} }
const onDialogShow = () => { const onDialogShow = () => {
console.log('弹出窗口', props.currentConversation) console.log('弹出窗口', props.currentConversation)
const data = props.currentConversation.userProfile const data = props.currentConversation.userProfile
emits('onDialogPopupShowOrHide', true) emits('onDialogPopupShowOrHide', false)
if (isType.value) { if (isType.value) {
let params = { let params = {
to: props.currentConversation.conversationID, to: props.currentConversation.conversationID,
conversationType: TUIChatEngine.TYPES.CONV_C2C, conversationType: TUIChatEngine.TYPES.CONV_C2C,
payload: { payload: {
text: "拨打语音" text: '拨打语音'
} }
} }
console.log('params: ', params); updateCallMode('0')
console.log('params: ', params)
// TUIChatService.sendTextMessage(params) // TUIChatService.sendTextMessage(params)
navigateTo('/pages/room/incom', { navigateTo('/pages/room/incom', {
type: 'call', type: 'call',
userID: data.userID, userID: data.userID,
mediaType: 'audio', mediaType: 'audio',
callType: 'out', callType: 'out'
}) })
} else { } else {
let params = { let params = {
to: props.currentConversation.conversationID, to: props.currentConversation.conversationID,
conversationType: TUIChatEngine.TYPES.CONV_C2C, conversationType: TUIChatEngine.TYPES.CONV_C2C,
payload: { payload: {
text: "拨打视频" text: '拨打视频'
} }
} }
// TUIChatService.sendTextMessage(params) // TUIChatService.sendTextMessage(params)
@@ -72,8 +75,9 @@
callType: 'out', callType: 'out',
mediaType: 'video', mediaType: 'video',
targetId: data.userID, targetId: data.userID,
callSelect: 'single', callSelect: 'single'
}); })
updateCallMode('1')
navigateTo('/pages/room/room') navigateTo('/pages/room/room')
} }
} }
@@ -93,9 +97,15 @@
<template> <template>
<!-- needBottomPopup --> <!-- needBottomPopup -->
<ToolbarItemContainer ref="container" :iconFile="evaluateIcon" :iconWidth="isUniFrameWork ? '34px' : '20px'" <ToolbarItemContainer
:iconHeight="isUniFrameWork ? '34px' : '20px'" :title="isType ? '语音通话' : '视频通话'" @onDialogShow="onDialogShow" ref="container"
@onDialogClose="onDialogClose"> :iconFile="evaluateIcon"
:iconWidth="isUniFrameWork ? '34px' : '20px'"
:iconHeight="isUniFrameWork ? '34px' : '20px'"
:title="isType ? '语音通话' : '视频通话'"
@onDialogShow="onDialogShow"
@onDialogClose="onDialogClose"
>
<!-- <view class="box-index"> <!-- <view class="box-index">
<view class="top-icon"> <view class="top-icon">
<uni-icons <uni-icons

View File

@@ -151,6 +151,25 @@
</view> </view>
</view> </view>
</template> </template>
<!-- 音视频通话 -->
<template
v-else-if="
customData.businessID === CHAT_MSG_CUSTOM_TYPE.VOICE_CALL ||
customData.businessID === CHAT_MSG_CUSTOM_TYPE.VIDEO_CALL
"
>
<view class="call-box" @click="onCall">
<text class="call-text">{{ goodsData.title }}</text>
<uni-icons
:type="
customData.businessID === CHAT_MSG_CUSTOM_TYPE.VOICE_CALL
? 'phone'
: 'videocam'
"
size="30rpx"
></uni-icons>
</view>
</template>
<template v-else> <template v-else>
<span v-html="content.custom" /> <span v-html="content.custom" />
</template> </template>
@@ -165,7 +184,7 @@
computed, computed,
reactive reactive
} from '../../../../adapter-vue' } from '../../../../adapter-vue'
import { import TUIChatEngine, {
TUITranslateService, TUITranslateService,
IMessageModel IMessageModel
} from '@tencentcloud/chat-uikit-engine-lite' } from '@tencentcloud/chat-uikit-engine-lite'
@@ -177,6 +196,7 @@
import unopenedEnvelope from '../../../../assets/icon/unopened-envelope.svg' import unopenedEnvelope from '../../../../assets/icon/unopened-envelope.svg'
import kaiEnvelope from '../../../../assets/icon/kai-unopened-envelope.svg' import kaiEnvelope from '../../../../assets/icon/kai-unopened-envelope.svg'
import { navigateTo } from '../../../../../utils/router' import { navigateTo } from '../../../../../utils/router'
import { useUserStore } from '../../../../../stores/user'
interface Props { interface Props {
messageItem: IMessageModel messageItem: IMessageModel
@@ -187,6 +207,8 @@
(key: 'claim'): void (key: 'claim'): void
} }
const { updateCallMode } = useUserStore()
const emits = defineEmits<IEmit>() const emits = defineEmits<IEmit>()
const props = withDefaults(defineProps<Props>(), { const props = withDefaults(defineProps<Props>(), {
@@ -230,6 +252,32 @@
return JSON.parse(props.messageItem.payload.data) return JSON.parse(props.messageItem.payload.data)
}) })
/** 点击拨打音视频电话 */
const onCall = () => {
if (props.messageItem.flow === 'out') {
if (
goodsData.value.businessID === CHAT_MSG_CUSTOM_TYPE.VOICE_CALL
) {
updateCallMode('0')
navigateTo('/pages/room/incom', {
type: 'call',
userID: goodsData.value.userID,
mediaType: 'audio',
callType: 'out'
})
} else {
uni.setStorageSync('room-parameters', {
callType: 'out',
mediaType: 'video',
targetId: goodsData.value.userID,
callSelect: 'single'
})
updateCallMode('1')
navigateTo('/pages/room/room')
}
}
}
/** 点击商品详情 */ /** 点击商品详情 */
const onGoods = () => { const onGoods = () => {
navigateTo('/pages/mall/detail', { productId: goodsData.value.id }) navigateTo('/pages/mall/detail', { productId: goodsData.value.id })
@@ -467,4 +515,12 @@
} }
} }
} }
.call-box {
display: flex;
align-items: center;
.call-text {
margin-right: 10rpx;
}
}
</style> </style>

View File

@@ -404,6 +404,20 @@
return `[直播信息]:${data.title}` return `[直播信息]:${data.title}`
} }
} }
if (data.businessID === CHAT_MSG_CUSTOM_TYPE.VOICE_CALL) {
if (isText) {
return `${text[0]}:[语音通话]`
} else {
return `[语音通话]`
}
}
if (data.businessID === CHAT_MSG_CUSTOM_TYPE.VIDEO_CALL) {
if (isText) {
return `${text[0]}:[视频通话]`
} else {
return `[视频通话]`
}
}
if (data.content === 'Create Group' && item.type === 'GROUP') { if (data.content === 'Create Group' && item.type === 'GROUP') {
return `${item.getLastMessage('text')?.split(':')[0]}:创建群聊` return `${item.getLastMessage('text')?.split(':')[0]}:创建群聊`
} }

View File

@@ -23,7 +23,11 @@ export const CHAT_MSG_CUSTOM_TYPE = {
/** 商品详情 */ /** 商品详情 */
GOODS: "goods", GOODS: "goods",
/** 直播 */ /** 直播 */
LIVE: "live" LIVE: "live",
/** 语音通话 */
VOICE_CALL: "voiceCall",
/** 视频通话 */
VIDEO_CALL: "videoCall",
}; };
export const DIALOG_CONTENT = { export const DIALOG_CONTENT = {

View File

@@ -11,6 +11,9 @@ export const useAuthUser = () => {
// 响应式状态state & getters // 响应式状态state & getters
const { const {
callMode,
callUserId,
callDuration,
imEngine, imEngine,
userInfo, userInfo,
tencentUserSig, tencentUserSig,
@@ -20,6 +23,9 @@ export const useAuthUser = () => {
const { token } = storeToRefs(tokenStore) const { token } = storeToRefs(tokenStore)
return { return {
callMode,
callUserId,
callDuration,
imEngine, imEngine,
integralData, integralData,
userInfo, userInfo,

View File

@@ -1,106 +1,15 @@
<template>
<!-- 来电接听界面 -->
<view class="incoming-call">
<!-- 背景模糊层 -->
<view class="blur-background" v-if="callBackground">
<image :src="callBackground" mode="aspectFill" class="bg-image"></image>
<view class="bg-overlay"></view>
</view>
<!-- 顶部栏 -->
<view class="top-bar">
<view class="top-left">
<!-- 通话时间显示 -->
<view v-if="callState === 'dialogue'" class="call-time-container">
<uni-icons type="sound" size="16" color="#fff"></uni-icons>
<text class="call-time">{{ formattedTime }}</text>
</view>
</view>
</view>
<!-- 主内容区 -->
<view class="caller-info">
<view class="caller-avatar-container">
<view class="caller-avatar" :class="{ 'avatar-ring': isRinging }">
<image v-if="callerInfo?.avatar" :src="callerInfo?.avatar" class="avatar-image"></image>
<uni-icons v-else type="contact-filled" size="50" color="#fff"></uni-icons>
</view>
</view>
<text class="caller-name">
{{ callerInfo?.nick || callerInfo?.userID }}
</text>
<text class="call-type">
{{ callState === 'call' ? '呼叫中,等待对方接受邀请...' : callState === 'answer' ? '等待接听...' : '对话中...' }}
</text>
<text class="call-status">{{ mediaType === 'audio' ? "语音通话" : "视频通话" }}</text>
</view>
<!-- 控制按钮 -->
<view class="incoming-controls">
<!-- 麦克风控制按钮仅在通话中显示 -->
<view v-if="callState === 'dialogue'" class="incoming-control" @click="toggleMicrophone">
<view class="call-btn mic-btn" :class="{ 'btn-active': activeBtn === 'mic', 'mic-muted': isMicMuted }">
<uni-icons v-if="!isMicMuted" type="mic" size="28" color="#fff"></uni-icons>
<uni-icons v-else type="micoff" size="28" color="#fff"></uni-icons>
</view>
<text class="btn-text">{{ isMicMuted ? '开启' : '静音' }}</text>
</view>
<!-- 挂断/拒绝按钮 -->
<view class="incoming-control" @click="cutFn(false)">
<view class="call-btn decline-btn" :class="{ 'btn-active': activeBtn === 'decline' }">
<uni-icons type="closeempty" size="32" color="#fff"></uni-icons>
</view>
<text class="btn-text">{{ callState === 'call' || callState == 'dialogue' ? "挂断" : "拒绝" }}</text>
</view>
<!-- 接听按钮 -->
<view v-if="callState === 'answer'" class="incoming-control" @click="cutFn(true)">
<view class="call-btn accept-btn" :class="{ 'btn-active': activeBtn === 'accept' }">
<uni-icons type="checkmarkempty" size="28" color="#fff"></uni-icons>
</view>
<text class="btn-text">接听</text>
</view>
<!-- 扬声器控制按钮仅在通话中显示 -->
<view v-if="callState === 'dialogue'" class="incoming-control" @click="toggleSpeaker">
<view class="call-btn speaker-btn" :class="{ 'btn-active': activeBtn === 'speaker', 'speaker-on': isSpeakerOn }">
<uni-icons v-if="!isSpeakerOn" type="sound" size="28" color="#fff"></uni-icons>
<uni-icons v-else type="sound-filled" size="28" color="#fff"></uni-icons>
</view>
<text class="btn-text">扬声器</text>
</view>
</view>
</view>
</template>
<script setup> <script setup>
import * as CallLib from '@/uni_modules/RongCloud-CallWrapper/lib/index' import * as CallLib from '@/uni_modules/RongCloud-CallWrapper/lib/index'
import { import { ref, computed, onUnmounted } from 'vue'
ref, import { onLoad, onUnload, onHide } from '@dcloudio/uni-app'
watch, import { TUIUserService } from '@tencentcloud/chat-uikit-engine-lite'
onUnmounted import { useUI } from '../../utils/use-ui'
} from 'vue' import { useAuthUser } from '../../composables/useAuthUser'
import { import { useUserStore } from '../../stores/user'
onLoad,
onUnload,
onHide
} from '@dcloudio/uni-app'
import {
TUIUserService
} from '@tencentcloud/chat-uikit-engine-lite'
import {
useUI
} from '../../utils/use-ui'
import {
navigateBack
} from '../../utils/router'
const { callUserId, callDuration } = useAuthUser()
const { const { startTimer, stopTimer } = useUserStore()
showLoading, const { showLoading, hideLoading } = useUI()
hideLoading
} = useUI()
const callBackground = ref('/static/images/public/random2.png') const callBackground = ref('/static/images/public/random2.png')
/** 呼叫用户信息 */ /** 呼叫用户信息 */
const callerInfo = ref({}) const callerInfo = ref({})
@@ -115,9 +24,9 @@
/** 通话计时器 */ /** 通话计时器 */
const timer = ref(null) const timer = ref(null)
/** 通话时长(秒) */ /** 通话时长(秒) */
const callDuration = ref(0) // const callDuration = ref(0)
/** 格式化后的时间 */ /** 好友ID */
const formattedTime = ref('00:00') const friendID = ref('')
/** /**
* 拨打状态 * 拨打状态
@@ -148,29 +57,14 @@
// console.log('通话过程中,发生异常,异常原因=>', res.data.reason) // console.log('通话过程中,发生异常,异常原因=>', res.data.reason)
// }) // })
/** 开始通话计时 */
const startTimer = () => {
stopTimer() // 先停止之前的计时器
timer.value = setInterval(() => {
callDuration.value++
formatTime()
}, 1000)
}
/** 停止通话计时 */
const stopTimer = () => {
if (timer.value) {
clearInterval(timer.value)
timer.value = null
}
}
/** 格式化时间显示 */ /** 格式化时间显示 */
const formatTime = () => { const formattedTime = computed(() => {
const minutes = Math.floor(callDuration.value / 60) const minutes = Math.floor(callDuration.value / 60)
const seconds = callDuration.value % 60 const seconds = callDuration.value % 60
formattedTime.value = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}` return `${minutes.toString().padStart(2, '0')}:${seconds
} .toString()
.padStart(2, '0')}`
})
/** 切换麦克风状态 */ /** 切换麦克风状态 */
const toggleMicrophone = () => { const toggleMicrophone = () => {
@@ -178,7 +72,7 @@
// 调用融云SDK的麦克风控制 // 调用融云SDK的麦克风控制
CallLib.enableMicrophone(!isMicMuted.value) CallLib.enableMicrophone(!isMicMuted.value)
activeBtn.value = 'mic' activeBtn.value = 'mic'
setTimeout(() => activeBtn.value = null, 200) setTimeout(() => (activeBtn.value = null), 200)
} }
/** 切换扬声器状态 */ /** 切换扬声器状态 */
@@ -187,10 +81,13 @@
// 调用融云SDK的扬声器控制 // 调用融云SDK的扬声器控制
CallLib.enableSpeaker(isSpeakerOn.value) CallLib.enableSpeaker(isSpeakerOn.value)
activeBtn.value = 'speaker' activeBtn.value = 'speaker'
setTimeout(() => activeBtn.value = null, 200) setTimeout(() => (activeBtn.value = null), 200)
} }
/** 按钮状态 */ /**
* 按钮状态
* @param show true: 接听电话 false: 拒接/挂断电话
*/
const cutFn = show => { const cutFn = show => {
if (show) { if (show) {
// 接听电话 dialogue // 接听电话 dialogue
@@ -203,7 +100,7 @@
startTimer() startTimer()
if (mediaType.value === 'video') { if (mediaType.value === 'video') {
uni.redirectTo({ uni.redirectTo({
url: "/pages/room/room" url: '/pages/room/room'
}) })
} }
} else { } else {
@@ -211,15 +108,16 @@
stopTimer() stopTimer()
// 取消接听,返回上一页 // 取消接听,返回上一页
CallLib.hangup() CallLib.hangup()
// navigateBack()
} }
} }
const mediaType = ref("audio") const mediaType = ref('audio')
onLoad(async e => { onLoad(async e => {
callState.value = e.type callState.value = e.type
mediaType.value = e.mediaType mediaType.value = e.mediaType
friendID.value = e.userID
callUserId.value = e.userID
console.log(e) console.log(e)
showLoading() showLoading()
const res = await TUIUserService.getUserProfile({ const res = await TUIUserService.getUserProfile({
@@ -231,11 +129,11 @@
CallLib.enableMicrophone(true) CallLib.enableMicrophone(true)
CallLib.startSingleCall(callerInfo.value.userID, 0, 'answer') CallLib.startSingleCall(callerInfo.value.userID, 0, 'answer')
} }
if (e.callType == "in") { if (e.callType == 'in') {
// 接听语音通话 // 接听语音通话
callState.value = 'answer' callState.value = 'answer'
} }
console.log('callState.value: ', callState.value); console.log('callState.value: ', callState.value)
console.log('===好友信息', res) console.log('===好友信息', res)
}) })
@@ -249,6 +147,163 @@
}) })
</script> </script>
<template>
<!-- 来电接听界面 -->
<view class="incoming-call">
<!-- 背景模糊层 -->
<view class="blur-background" v-if="callBackground">
<image
:src="callBackground"
mode="aspectFill"
class="bg-image"
></image>
<view class="bg-overlay"></view>
</view>
<!-- 顶部栏 -->
<view class="top-bar">
<view class="top-left">
<!-- 通话时间显示 -->
<view v-if="callState === 'dialogue'" class="call-time-container">
<uni-icons type="sound" size="16" color="#fff"></uni-icons>
<text class="call-time">{{ formattedTime }}</text>
</view>
</view>
</view>
<!-- 主内容区 -->
<view class="caller-info">
<view class="caller-avatar-container">
<view class="caller-avatar" :class="{ 'avatar-ring': isRinging }">
<image
v-if="callerInfo?.avatar"
:src="callerInfo?.avatar"
class="avatar-image"
></image>
<uni-icons
v-else
type="contact-filled"
size="50"
color="#fff"
></uni-icons>
</view>
</view>
<text class="caller-name">
{{ callerInfo?.nick || callerInfo?.userID }}
</text>
<text class="call-type">
{{
callState === 'call'
? '呼叫中,等待对方接受邀请...'
: callState === 'answer'
? '等待接听...'
: '对话中...'
}}
</text>
<text class="call-status">
{{ mediaType === 'audio' ? '语音通话' : '视频通话' }}
</text>
</view>
<!-- 控制按钮 -->
<view class="incoming-controls">
<!-- 麦克风控制按钮仅在通话中显示 -->
<view
v-if="callState === 'dialogue'"
class="incoming-control"
@click="toggleMicrophone"
>
<view
class="call-btn mic-btn"
:class="{
'btn-active': activeBtn === 'mic',
'mic-muted': isMicMuted
}"
>
<uni-icons
v-if="!isMicMuted"
type="mic"
size="28"
color="#fff"
></uni-icons>
<uni-icons
v-else
type="micoff"
size="28"
color="#fff"
></uni-icons>
</view>
<text class="btn-text">{{ isMicMuted ? '开启' : '静音' }}</text>
</view>
<!-- 挂断/拒绝按钮 -->
<view class="incoming-control" @click="cutFn(false)">
<view
class="call-btn decline-btn"
:class="{ 'btn-active': activeBtn === 'decline' }"
>
<uni-icons type="closeempty" size="32" color="#fff"></uni-icons>
</view>
<text class="btn-text">
{{
callState === 'call' || callState == 'dialogue'
? '挂断'
: '拒绝'
}}
</text>
</view>
<!-- 接听按钮 -->
<view
v-if="callState === 'answer'"
class="incoming-control"
@click="cutFn(true)"
>
<view
class="call-btn accept-btn"
:class="{ 'btn-active': activeBtn === 'accept' }"
>
<uni-icons
type="checkmarkempty"
size="28"
color="#fff"
></uni-icons>
</view>
<text class="btn-text">接听</text>
</view>
<!-- 扬声器控制按钮仅在通话中显示 -->
<view
v-if="callState === 'dialogue'"
class="incoming-control"
@click="toggleSpeaker"
>
<view
class="call-btn speaker-btn"
:class="{
'btn-active': activeBtn === 'speaker',
'speaker-on': isSpeakerOn
}"
>
<uni-icons
v-if="!isSpeakerOn"
type="sound"
size="28"
color="#fff"
></uni-icons>
<uni-icons
v-else
type="sound-filled"
size="28"
color="#fff"
></uni-icons>
</view>
<text class="btn-text">扬声器</text>
</view>
</view>
</view>
</template>
<style lang="scss" scoped> <style lang="scss" scoped>
.incoming-call { .incoming-call {
position: fixed; position: fixed;

View File

@@ -1,6 +1,4 @@
import { import { defineStore } from 'pinia'
defineStore
} from 'pinia'
import { import {
getToken, getToken,
getUserInfoData, getUserInfoData,
@@ -15,69 +13,32 @@ import {
} from '@/utils/storage' } from '@/utils/storage'
// #ifdef APP-PLUS // #ifdef APP-PLUS
import { import { useLoginState } from '@/uni_modules/tuikit-atomic-x/state/LoginState'
useLoginState
} from '@/uni_modules/tuikit-atomic-x/state/LoginState'
import * as CallLib from '@/uni_modules/RongCloud-CallWrapper/lib/index' import * as CallLib from '@/uni_modules/RongCloud-CallWrapper/lib/index'
import RCIMIWEngine from '@/uni_modules/RongCloud-IMWrapper-V2/js_sdk/RCIMEngine' import RCIMIWEngine from '@/uni_modules/RongCloud-IMWrapper-V2/js_sdk/RCIMEngine'
import { import { reasonDeal, errorDeal, imCode } from '@/utils/code.js'
reasonDeal,
errorDeal,
imCode
} from '@/utils/code.js'
// #endif // #endif
// #ifdef H5 // #ifdef H5
import { import { useLoginState } from 'tuikit-atomicx-vue3'
useLoginState
} from 'tuikit-atomicx-vue3'
// #endif // #endif
import { import { useTokenStore } from './token'
useTokenStore import { getUserData, userLogout, updateUserData } from '@/api'
} from './token' import { ref } from 'vue'
import { import { useUI } from '@/utils/use-ui'
getUserData, import { reLaunch } from '@/utils/router'
userLogout, import { getTencentUserSig } from '@/api'
updateUserData import { TUILogin } from '@tencentcloud/tui-core-lite'
} from '@/api' import { TUIChatEngine } from '@tencentcloud/chat-uikit-engine-lite'
import { import { getUserIntegral } from '@/api/my-index'
ref import { removeFriendList, removeGroupList } from '../utils/storage'
} from 'vue' import { getRongYunLoginInfo } from '../api'
import { import permision from '@/js_sdk/wa-permission/permission.js'
useUI
} from '@/utils/use-ui'
import {
reLaunch
} from '@/utils/router'
import {
getTencentUserSig
} from '@/api'
import {
TUILogin
} from '@tencentcloud/tui-core-lite'
import {
TUIChatEngine
} from '@tencentcloud/chat-uikit-engine-lite'
import {
getUserIntegral
} from '@/api/my-index'
import {
removeFriendList,
removeGroupList
} from '../utils/storage'
import {
getRongYunLoginInfo
} from '../api'
import permision from "@/js_sdk/wa-permission/permission.js"
import { navigateTo } from '@/utils/router' import { navigateTo } from '@/utils/router'
import { sendCallMsg } from '../utils/call-user'
export const useUserStore = defineStore('user', () => { export const useUserStore = defineStore('user', () => {
const { const { clearToken } = useTokenStore()
clearToken const { showDialog, showToast } = useUI()
} = useTokenStore()
const {
showDialog,
showToast
} = useUI()
const userInfo = ref( const userInfo = ref(
getUserInfoData() ? JSON?.parse(getUserInfoData()) : {} getUserInfoData() ? JSON?.parse(getUserInfoData()) : {}
@@ -92,6 +53,39 @@ export const useUserStore = defineStore('user', () => {
const integralData = ref(0) const integralData = ref(0)
/** 融云 IM 引擎 */ /** 融云 IM 引擎 */
const imEngine = ref(null) const imEngine = ref(null)
/** 发起通话用户id */
const callUserId = ref('')
/** 通话时长(秒) */
const callDuration = ref(0)
/** 通话模式 0语音通话 1视频通话 */
const callMode = ref('0')
/** 通话计时器 */
const timer = ref(null)
/** 开始通话计时 */
const startTimer = () => {
stopTimer() // 先停止之前的计时器
timer.value = setInterval(() => {
callDuration.value++
}, 1000)
}
/** 停止通话计时 */
const stopTimer = () => {
if (timer.value) {
clearInterval(timer.value)
timer.value = null
}
}
/** 重置时间 */
const resetTime = () => {
callDuration.value = 0
}
/** 通话模式更新 */
const updateCallMode = mode => {
callMode.value = mode
}
/** /**
* 获取用户信息(可从缓存或接口) * 获取用户信息(可从缓存或接口)
@@ -177,33 +171,42 @@ export const useUserStore = defineStore('user', () => {
//连接融云IM //连接融云IM
const connectIM = async () => { const connectIM = async () => {
let options = {} let options = {}
imEngine.value = await RCIMIWEngine.create(tencentUserSig.value.appKey, options) imEngine.value = await RCIMIWEngine.create(
imEngine.value.setOnConnectedListener((res) => { tencentUserSig.value.appKey,
options
)
imEngine.value.setOnConnectedListener(res => {
if (res.code != 0) { if (res.code != 0) {
uni.hideLoading(); uni.hideLoading()
// uni.showToast({ // uni.showToast({
// title: 'OnCon:' + res.code, // title: 'OnCon:' + res.code,
// icon: 'error' // icon: 'error'
// }) // })
console.log("连接已存在"); console.log('连接已存在')
// return // return
} }
//连接成功 //连接成功
CallLib.init({}); CallLib.init({})
console.log('call.init') console.log('call.init')
uni.hideLoading(); uni.hideLoading()
uni.showToast({ // uni.showToast({
title: res.userId // title: res.userId
}); // })
console.log('登录成功')
if (uni.getSystemInfoSync().platform === 'android') { if (uni.getSystemInfoSync().platform === 'android') {
permision.requestAndroidPermission('android.permission.CAMERA'); permision.requestAndroidPermission('android.permission.CAMERA')
permision.requestAndroidPermission('android.permission.RECORD_AUDIO'); permision.requestAndroidPermission(
'android.permission.RECORD_AUDIO'
)
} }
onAllListeners() onAllListeners()
}); })
let code = await imEngine.value.connect(tencentUserSig.value.ryToken, 10) let code = await imEngine.value.connect(
tencentUserSig.value.ryToken,
10
)
if (code != 0) { if (code != 0) {
uni.hideLoading(); uni.hideLoading()
uni.showToast({ uni.showToast({
title: 'connect:' + code, title: 'connect:' + code,
icon: 'error' icon: 'error'
@@ -211,92 +214,124 @@ export const useUserStore = defineStore('user', () => {
} }
} }
function onAllListeners () { function onAllListeners() {
CallLib.onCallReceived( (res)=> { CallLib.onCallReceived(res => {
console.log(res) console.log(res)
console.log("Engine:OnCallReceived=>"+"监听通话呼入, 目标id=>", res.data.targetId); console.log(
'Engine:OnCallReceived=>' + '监听通话呼入, 目标id=>',
res.data.targetId
)
if (res.data.targetId) { if (res.data.targetId) {
// let url = res.data.mediaType == 0 ? "" : "/pages/room/room" // let url = res.data.mediaType == 0 ? "" : "/pages/room/room"
uni.setStorageSync('room-parameters', { uni.setStorageSync('room-parameters', {
callType: 'in', callType: 'in',
mediaType: res.data.mediaType === 0 ? 'audio' : 'video' mediaType: res.data.mediaType === 0 ? 'audio' : 'video'
});
uni.showToast({
title:"有通话呼入该跳转了"+res.data.targetId,
duration:3000
}) })
navigateTo("/pages/room/incom", { uni.showToast({
title: '有通话呼入该跳转了' + res.data.targetId,
duration: 3000
})
navigateTo('/pages/room/incom', {
type: res.data.extra, type: res.data.extra,
callType: 'in', callType: 'in',
mediaType: res.data.mediaType == 0 ? "audio" : "video", mediaType: res.data.mediaType == 0 ? 'audio' : 'video',
userID: res.data.mine.userId // 对方的用户id userID: res.data.mine.userId // 对方的用户id
}) })
} }
}); })
CallLib.onCallDisconnected((res)=>{ CallLib.onCallDisconnected(res => {
console.log(res) console.log(res)
console.log("Engine:OnCallDisconnected=>"+"通话挂断/拒绝, 挂断原因=>", res.data.reason); console.log(
'Engine:OnCallDisconnected=>' + '通话挂断/拒绝, 挂断原因=>',
res.data.reason
)
console.log('=====通话用户id', callUserId.value)
sendCallMsg(res.data.reason)
// 重新渲染视频视图 // 重新渲染视频视图
// uni.$emit('OnCallDisconnected'); // uni.$emit('OnCallDisconnected');
uni.showToast({ uni.showToast({
title:reasonDeal(res.data.reason), title: reasonDeal(res.data.reason),
error:"error", error: 'error',
icon:'none', icon: 'none',
duration:2000 duration: 2000
}) })
goback() goback()
}); })
CallLib.onCallConnected((res)=>{ CallLib.onCallConnected(res => {
console.log(res) console.log(res)
console.log("Engine:OnCallConnected=>"+"已建立通话通话接通时,通过回调 onCallConnected 通知当前 call 的详细信息", res); console.log(
}); 'Engine:OnCallConnected=>' +
CallLib.onRemoteUserInvited((res)=>{ '已建立通话通话接通时,通过回调 onCallConnected 通知当前 call 的详细信息',
console.log("Engine:OnRemoteUserInvited=>"+"通话中的某一个参与者,邀请好友加入通话 ,远端Id为=>", res.data.userId); res
uni.$emit('OnCallConnected'); )
}) })
CallLib.onRemoteUserJoined((res)=>{ CallLib.onRemoteUserInvited(res => {
console.log("Engine:OnRemoteUserJoined=>"+"主叫端拨出电话被叫端收到请求后加入通话对端Id为=>", res.data.userId); console.log(
uni.$emit('OnCallConnected'); 'Engine:OnRemoteUserInvited=>' +
'通话中的某一个参与者,邀请好友加入通话 ,远端Id为=>',
res.data.userId
)
uni.$emit('OnCallConnected')
}) })
CallLib.onRemoteUserLeft((res)=>{ CallLib.onRemoteUserJoined(res => {
console.log("Engine:OnRemoteUserLeft=>"+"远端用户挂断(群聊触发)远端Id为=>", res.data.reason); console.log(
uni.$emit('OnCallConnected'); 'Engine:OnRemoteUserJoined=>' +
'主叫端拨出电话被叫端收到请求后加入通话对端Id为=>',
res.data.userId
)
uni.$emit('OnCallConnected')
})
CallLib.onRemoteUserLeft(res => {
console.log(
'Engine:OnRemoteUserLeft=>' +
'远端用户挂断(群聊触发)远端Id为=>',
res.data.reason
)
uni.$emit('OnCallConnected')
uni.showToast({ uni.showToast({
title:reasonDeal(res.data.reason), title: reasonDeal(res.data.reason),
error:"error", error: 'error',
icon:'none', icon: 'none',
duration:2000 duration: 2000
}) })
}) })
CallLib.onCallOutgoing((res)=>{ CallLib.onCallOutgoing(res => {
console.log('电话已拨出 主叫端拨出电话后,通过回调 onCallOutgoing 通知当前 call 的详细信息') console.log(
'电话已拨出 主叫端拨出电话后,通过回调 onCallOutgoing 通知当前 call 的详细信息'
)
}) })
CallLib.onRemoteUserRinging((res)=>{ CallLib.onRemoteUserRinging(res => {
console.log('被叫端正在振铃,主叫端拨出电话,被叫端收到请求,发出振铃响应时,回调 onRemoteUserRingin,对端Id为=>', res.data.userId) console.log(
'被叫端正在振铃,主叫端拨出电话,被叫端收到请求,发出振铃响应时,回调 onRemoteUserRingin,对端Id为=>',
res.data.userId
)
}) })
CallLib.onError((res)=>{ CallLib.onError(res => {
console.log('通话过程中,发生异常') console.log('通话过程中,发生异常')
uni.showToast({ uni.showToast({
title:errorDeal(res.data.reason), title: errorDeal(res.data.reason),
error:"error", error: 'error',
icon:'none', icon: 'none',
duration:2000 duration: 2000
}); })
goback() goback()
}) })
CallLib.onRemoteUserMediaTypeChanged((res)=>{ CallLib.onRemoteUserMediaTypeChanged(res => {
console.log('当通话中的某一个参与者切换通话类型,例如由 audio 切换至 video回调 onMediaTypeChanged,切换媒体类型的Id为=>',res.data.user.userId); console.log(
'当通话中的某一个参与者切换通话类型,例如由 audio 切换至 video回调 onMediaTypeChanged,切换媒体类型的Id为=>',
res.data.user.userId
)
}) })
} }
function goback () { function goback() {
const pages = getCurrentPages() const pages = getCurrentPages()
console.log('pages: ',pages); console.log('pages: ', pages)
if (pages.length > 1) { if (pages.length > 1) {
console.log("走返回"); console.log('走返回')
uni.showToast({ uni.showToast({
title:"走返回", title: '走返回',
duration:3000 duration: 3000
}) })
uni.navigateBack({ uni.navigateBack({
delta: 1 delta: 1
@@ -400,11 +435,18 @@ export const useUserStore = defineStore('user', () => {
} }
return { return {
callUserId,
callDuration,
imEngine, imEngine,
userInfo, userInfo,
integralData, integralData,
tencentUserSig, tencentUserSig,
fontSizeData, fontSizeData,
callMode,
startTimer,
stopTimer,
updateCallMode,
resetTime,
getIntegral, getIntegral,
clearAllUserInfo, clearAllUserInfo,
updateFontSize, updateFontSize,

59
utils/call-user.js Normal file
View File

@@ -0,0 +1,59 @@
import TUIChatEngine, {
TUIChatService
} from '@tencentcloud/chat-uikit-engine-lite'
import { CHAT_MSG_CUSTOM_TYPE } from '../TUIKit/constant'
import { useAuthUser } from '../composables/useAuthUser'
import { useUserStore } from '../stores/user'
/** 格式化时间显示 */
const formatTime = date => {
const minutes = Math.floor(date / 60)
const seconds = date % 60
return `${minutes.toString().padStart(2, '0')}:${seconds
.toString()
.padStart(2, '0')}`
}
/** 通话消息发送 */
export const sendCallMsg = async state => {
const { resetTime, stopTimer } = useUserStore()
const { callUserId, callMode, callDuration, tencentUserSig } =
useAuthUser()
const to = callUserId.value
const userID = tencentUserSig.value.userId
if (to !== userID) {
let title = ''
if ([0, 11].includes(state)) {
title = { 0: '已挂断', 11: '对方已拒绝' }[state]
} else {
title = `通话时长 ${formatTime(callDuration.value)}`
}
const payload = {
data: JSON.stringify({
businessID:
callMode.value == 0
? CHAT_MSG_CUSTOM_TYPE.VOICE_CALL
: CHAT_MSG_CUSTOM_TYPE.VIDEO_CALL,
title,
userID: to
}),
description: title,
extension: title
}
const options = {
to,
payload,
conversationType: TUIChatEngine.TYPES.CONV_C2C,
needReadReceipt: false
}
resetTime()
await TUIChatService.sendCustomMessage(options)
} else {
resetTime()
}
if (callMode.value == 1) {
stopTimer()
}
}