开发视频通话,修改两个bug

This commit is contained in:
田岩
2025-12-11 10:36:29 +08:00
parent f1517d088c
commit bb1cfdbf33
15 changed files with 1319 additions and 116 deletions
+3 -3
View File
@@ -6,7 +6,7 @@ ENV = 'development'
# VITE_APP_BASE_API_Url = 'https://aits.jlbank.com.cn:7001'
VITE_APP_BASE_API_Url = 'https://aitstest.jlbank.com.cn:7002'
VITE_APP_BASE_API_Url = 'https://aitstest.jlbank.com.cn:7001'
# VITE_APP_BASE_API_Url = 'https://aitstest.jlbank.com.cn:7002'
@@ -17,7 +17,7 @@ VITE_APP_BASE_API_Url = 'https://aitstest.jlbank.com.cn:7002'
#VITE_APP_BASE_API_Url = 'http://25.18.122.65:7001'
# sit
# VITE_APP_BASE_API_Url = 'http://25.18.122.91:9786'
#VITE_APP_BASE_API_Url = 'http://25.18.122.91:9786'
# UAT
@@ -33,7 +33,7 @@ VITE_APP_BASE_API_Url = 'https://aitstest.jlbank.com.cn:7002'
# h5专用地址x2
# VITE_APP_BASE_H5_API_Url_TRAAPP = 'http://25.64.32.150:9601'
# dev
# VITE_APP_BASE_H5_API_Url = 'http://25.18.122.65:7001'
VITE_APP_BASE_H5_API_Url = 'http://25.18.122.65:7001'
# sit
#VITE_APP_BASE_H5_API_Url = 'http://25.18.122.91:9786'
+1 -1
View File
@@ -2,7 +2,7 @@
"version" : "1.0",
"configurations" : [
{
"playground" : "custom",
"playground" : "standard",
"type" : "uni-app:app-android"
},
{
Binary file not shown.
+11 -1
View File
@@ -65,7 +65,17 @@
},
/* ios */
"ios" : {
"dSYMs" : false
"dSYMs" : false,
"deploymentTarget": "11.0",
"privacyDescription": {
"NSCameraUsageDescription": "此应用需要访问您的摄像头来进行视频录制和拍照功能",
"NSMicrophoneUsageDescription": "此应用需要访问您的麦克风来录制音频"
},
"capabilities": {
"entitlements": {
"com.apple.developer.avfoundation.multitasking-camera-access": true
}
}
},
/* SDK */
"sdkConfigs" : {},
@@ -64,6 +64,7 @@
traId: item.traId
}).then(res=>{
if(res.body.inRange){
// todo
common.navigateTo('/pages/sparring/detail?traId=' + item.traId + '&isPreview=1')
}else{
common.show(res.body.message)
@@ -0,0 +1,102 @@
<template>
<view>
<view v-if="isPreviewing" class="live-container">
<cover-view class="pusher-container">
<live-pusher
id="livePusher"
class="livePusher"
:muted="true"
:enable-camera="true"
:auto-focus="true"
:beauty="0"
:whiteness="0"
aspect="9:16"
mode="SD"
device-position="front"
orientation
></live-pusher>
</cover-view>
<!-- <cover-view class="corner-mask"></cover-view> -->
</view>
</view>
</template>
<script setup>
import { getPhoneEnvBool } from '@/common/common';
import { onMounted, ref, reactive, nextTick } from 'vue';
const livePusherContext = ref(null);
const isPreviewing = ref(false);
const init = (componentProxy) => {
console.log('init');
livePusherContext.value = uni.createLivePusherContext('livePusher', componentProxy);
};
// 切换摄像头
const switchCamera = () => {
livePusherContext.value?.switchCamera({
success: (res) => {
console.log('livePusher.switchCamera:', JSON.stringify(res));
},
fail: (err) => {
console.error('切换摄像头失败:', err);
}
});
};
// 开启预览
const startPreview = () => {
console.log('摄像头开启预览');
isPreviewing.value = true;
nextTick(() => {
livePusherContext.value?.startPreview({
success: (res) => {
console.log('摄像头开启成功');
},
fail: (err) => {
console.error('开启预览失败:', err);
},
complete: (err) => {
console.error('complete预览:', err);
}
});
if (getPhoneEnvBool('AND')) {
console.log('切换前置');
setTimeout(() =>{
switchCamera()
}, 1000)
}
});
};
// 关闭预览
const stopPreview = () => {
console.log('关闭预览');
livePusherContext.value?.stopPreview({
success: (res) => {
console.log('livePusher.stopPreview:', JSON.stringify(res));
},
fail: (err) => {
console.error('关闭预览失败:', err);
},
complete: (err) => {
console.error('complete预览:', err);
}
});
isPreviewing.value = false;
};
defineExpose({ init, switchCamera, stopPreview, startPreview });
</script>
<style scoped>
.live-container {
position: absolute;
right: 0;
top: 150rpx;
overflow: hidden;
border-radius: 20rpx;
width: 270rpx;
height: 480rpx;
}
</style>
+24 -7
View File
@@ -36,7 +36,8 @@ export default function useWebSocket(aaas = null, options = {}) {
onStartRecord,
playPcmCallback,
setPlayNumber = () => {}, //设置当前播放的音频的id,用于播放完成回调
onError = () => {}
onError = () => {},
onClose = () => {},
}) => {
const wsUrl = _baseUrl + url + '?summary=' + getToken()
const finalAuthParams = {
@@ -53,10 +54,20 @@ export default function useWebSocket(aaas = null, options = {}) {
}
});
ws.value.onOpen((res) => {
console.log('onOpen', finalAuthParams);
ws.value.send({
data: ProtocolCodec.pack(MessageType.IDENTITY, finalAuthParams)
});
});
ws.value.onError((err) => onError(err))
ws.value.onClose((err) => {
console.log('onClose', err);
onClose(err)
});
ws.value.onMessage((res) => {
const {
msgType,
@@ -76,19 +87,27 @@ export default function useWebSocket(aaas = null, options = {}) {
playPcmCallback(numArray)
break;
case MessageType.ERROR:
switch (body.errCode) {
case 1:
// ASR或TTS初始化出错
console.log('后端返回的错误', body.errMsg);
case 4:
console.log('通话接通失败', body.errMsg);
// 通话接通失败,请稍后再试!
ws.value.close({
code: 4001,
reason: body.errMsg
})
break;
default:
// 其他错误码的默认处理(如果需要)
// ws.value.close({
// code: 1001,
// reason: body.errMsg
// })
break;
}
console.log('错误', body);
// this.handleErrorMessage(body);
break;
case MessageType.CONTROL_CMD:
// 控制消息
@@ -96,11 +115,8 @@ export default function useWebSocket(aaas = null, options = {}) {
if (body.type === 1) { // 开始播放,记录当前播放的语音id
console.log('开始播放,记录当前播放的语音id', body.lock);
setPlayNumber(body.lock)
}
break;
default:
console.log('其他消息', msgType, body);
break;
@@ -112,6 +128,7 @@ export default function useWebSocket(aaas = null, options = {}) {
data
});
}
const close = () => {
ws.value.close({
code: 1000,
+130 -70
View File
@@ -1,6 +1,6 @@
<template>
<view>
<cached-avatar class="show-box-avatar"></cached-avatar>
<image-preview :src="dataInfo.ossAddr" class="show-box-avatar"></image-preview>
<view class="show-box">
<nav-bar :is_seat="true"></nav-bar>
<view class="switch-div">
@@ -9,8 +9,8 @@
</view>
<view class="fl1-div-1"></view>
<view class="role-info">
<cached-avatar class="role-avatar"></cached-avatar>
<view class="role-name">{{ dataInfo.userName }}</view>
<image-preview :src="dataInfo.ossAddr" class="role-avatar"></image-preview>
<view class="role-name">{{ dataInfo.chaName }}</view>
<view class="title-time" v-if="isRecording">{{ formattedTime }}</view>
<view class="title-tip" v-if="!isRecording">正在接通中</view>
</view>
@@ -22,80 +22,91 @@
</view>
<talk-microphone ref="talkMicrophoneRef"></talk-microphone>
<talk-speaker ref="talkSpeakerRef" @playOver="playOver"></talk-speaker>
<talk-camera ref="talkCameraRef" v-if="isVideo"></talk-camera>
</view>
</template>
<script setup>
import { getUserInfo,getToken } from '@/common/common';
import { queryTraPartnerCharacterInfoById, partnerChatReportTrigger } from '@/api/sparring.js';
import { ref, reactive, onMounted, onUnmounted, computed, getCurrentInstance, nextTick } from 'vue';
import { onShow, onLoad, onUnload, onBackPress, onReady } from '@dcloudio/uni-app';
import { ProtocolCodec, MessageType, CompressionType, ControlCommand } from './js/ProtocolCodec';
import common from '@/common/common';
import talkMicrophone from './components/talk-microphone.vue';
import talkSpeaker from './components/talk-speaker.vue';
import talkCamera from './components/talk-camera';
import useWebSocket from './js/useWebSocket';
import useMicrophone from './js/useMicrophone';
const talkMicrophoneRef = ref(null);
const talkSpeakerRef = ref(null);
const talkCameraRef = ref(null);
const { initConnection, close, send, isRecording } = useWebSocket();
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { onShow, onLoad, onUnload, onBackPress } from '@dcloudio/uni-app';
import {
ProtocolCodec,
MessageType,
SerializationType,
CompressionType,
ControlCommand,
ProtocolConst
} from './js/ProtocolCodec';
const isVideo = ref(false);
const dataInfo = reactive({
traId: '',
chaId: '',
traType: '',
traInterType: '',
traInterTyp: '',
execId: '',
sceneDesc: '',
userName: '',
preview: false // 是否是预览
preview: false, // 是否是预览
traInterTypDesc: '', // 类型的文字提示,例如 语音通话
ossAddr: '', //用户头像
chaName: '' //用户名称
});
const sceneDescShow = ref(false);
const switchChange = () => {sceneDescShow.value = !sceneDescShow.value};
const switchChange = () => {
sceneDescShow.value = !sceneDescShow.value;
};
// 关闭通话
const closeTalking = async () => {
common.show('', '挂断电话将结束训练,是否确认?').then((res) => {
if (res) {
talkMicrophoneRef.value.stop();
talkSpeakerRef.value.close();
close();
common.navigateBack(1, () => {
partnerChatReportTrigger({
execId: dataInfo.execId,
traId: dataInfo.traId,
talkingType: dataInfo.isPreview ? 'preview' : 'practice'
}).then((res) => {
common.redirectTo(
'/pages/sparring/result?isOver=1&traId=' +
dataInfo.traId +
'&execId=' +
dataInfo.execId +
'&type=' +
dataInfo.traType +
'&isPreview=' +
(dataInfo.isPreview ? '1' : '')
);
});
});
destroy(); // 走关闭销毁流程
}
});
};
// 关闭销毁流程,逐层清理
const destroy = (type = 0) => {
if (type <= 0) {
isVideo.value && talkCameraRef.value.stopPreview();
talkMicrophoneRef.value.stop();
talkSpeakerRef.value.close();
}
if (type <= 1) {
close();
}
if (type <= 2) {
nextTick(() => {
setTimeout(() => {
common.redirectTo(
'/pages/sparring/result?isOver=1&traId=' +
dataInfo.traId +
'&execId=' +
dataInfo.execId +
'&type=' +
dataInfo.traType +
'&isPreview=' +
(dataInfo.isPreview ? '1' : '')
);
}, 300);
});
}
};
// 未接通时候报错处理,仅返回和少量销毁
const noConnectDestroy = () => {
console.log('未接通');
setTimeout(() => {
common.show('', '当前服务器繁忙,请稍后在试!', false).then((res) => {
if (res) common.navigateBack();
});
}, 500);
};
const onCurrentDecibels = (res) => {
console.log('res', res);
console.log('当前分贝', res);
};
//
const targetTimestamp = ref(0);
// 定时器实例
let timer = null;
@@ -103,7 +114,9 @@
// 2. 格式化函数:总秒数 → mm:ss(分钟无上限,不进位小时)
const formatTime = (totalSeconds) => {
if (totalSeconds <= 0) return '00:00'; // 过期显示0:00
const minutes = Math.floor(totalSeconds / 60).toString().padStart(2, '0'); // 分钟无上限
const minutes = Math.floor(totalSeconds / 60)
.toString()
.padStart(2, '0'); // 分钟无上限
const seconds = totalSeconds % 60; // 秒数
return `${minutes}:${seconds.toString().padStart(2, '0')}`; // 秒补零
};
@@ -116,13 +129,14 @@
const diff = now - targetTimestamp.value;
formattedTime.value = formatTime(Math.max(0, Math.floor(diff / 1000)));
};
const onStartRecord = (body) => {
dataInfo.execId = body.execId;
targetTimestamp.value = Date.now();
// 当ws连接成功时候
console.log('连接成功开始录音');
console.log('连接成功开始' + dataInfo.traInterTypDesc);
isRecording.value = true;
isVideo.value && talkCameraRef.value.startPreview();
timer = setInterval(updateRemaining, 1000);
// 立即执行一次
updateRemaining();
@@ -136,40 +150,86 @@
};
const playOver = (id) => {
console.log('播放完毕talk通知后端', id);
if(id) {
if (id) {
setTimeout(() => {
send(ProtocolCodec.pack(MessageType.CONTROL_CMD, {
type:2,
lock:id
}))
}, 300)
send(
ProtocolCodec.pack(MessageType.CONTROL_CMD, {
type: 2,
lock: id
})
);
}, 300);
}
};
const onError = (body) => {
const onError = (error) => {
// websocket错误处理
console.log('websocket错误处理', error);
common.show('', '系统网络异常,通话结束!', false).then((res) => {
if (res) {
destroy();
}
});
};
const onClose = (error) => {
// 未接通
// websocket错误处理
console.log('websocketonClose关闭', error);
if (error?.code === 1002) {
// 在后端服务失败的时候连接不上
if (dataInfo.execId !== '') {
// 有execId说明通话过程中
destroy();
} else {
// 否则是未接通
noConnectDestroy()
}
} else if (error?.code === 1001) {
// 正常运行中后端掉线了
onError({});
} else if (error?.code === 1000) {
// 用户主动挂断
} else if (error?.code === 4001) {
// 自定义异常挂断,参数错误
noConnectDestroy()
}
};
onLoad((e) => {
dataInfo.traId = e.traId ?? '';
dataInfo.chaId = e.chaId ?? '';
dataInfo.traType = '02'; // 陪练类型 01-练习 02-考试
dataInfo.traInterType = e.traInterType ?? '02'; // 陪练交互类型 01 对话 02 语音 03 视频
dataInfo.preview = e.isPreview === '1';
const userInfo = getUserInfo();
dataInfo.userName = userInfo.userName;
const pageData = common.getPageCache('tipMsgsceneDesc')
dataInfo.sceneDesc = pageData.sceneDesc
dataInfo.traInterTyp = e.traInterTyp ?? '02'; // 陪练交互类型 01 对话 02 语音 03 视频
// dataInfo.traInterType = '02'; // 陪练交互类型 01 对话 02 语音 03 视频
//#ifdef APP-PLUS
// 只有app才能打开摄像头
isVideo.value = dataInfo.traInterTyp === '03';
//#endif
console.log('isVideo.value', isVideo.value);
dataInfo.preview = e.isPreview === '1'; // 是否是预览
const pageData = common.getPageCache('tipMsgsceneDesc');
dataInfo.ossAddr = pageData.ossAddr;
dataInfo.chaName = pageData.chaName;
dataInfo.traInterTypDesc = pageData.traInterTypDesc;
});
onMounted(() => {
initConnection({
authParams:Object.assign({}, dataInfo),
onStartRecord:onStartRecord,
playPcmCallback:(res) => talkSpeakerRef.value.playPCM(res),
setPlayNumber:(id) => talkSpeakerRef.value.setPlayNumber(id),
onError:onError
authParams: Object.assign({}, dataInfo),
onStartRecord: onStartRecord,
playPcmCallback: (res) => talkSpeakerRef.value.playPCM(res),
setPlayNumber: (id) => talkSpeakerRef.value.setPlayNumber(id),
onError,
onClose
});
});
onReady(() => {
if (isVideo.value) {
const instance = getCurrentInstance();
const componentProxy = instance.ctx;
nextTick(() => {
talkCameraRef.value.init(componentProxy);
});
}
});
onUnmounted(() => {
console.log('组件卸载');
if (timer) clearInterval(timer);
+28 -27
View File
@@ -70,9 +70,7 @@
{{ detailInfo.sceneDesc }}
</view>
<view class="talking-box" v-if="detailInfo.traInterTyp !== '01'">
<view class="tip-text">
-请点击下方按钮开始{{ detailInfo.traInterTypDesc }}
</view>
<view class="tip-text">-请点击下方按钮开始{{ detailInfo.traInterTypDesc }}</view>
</view>
<view class="talking-box" v-else>
<TalkingItem
@@ -129,10 +127,10 @@
import { ref, unref, onMounted, computed, nextTick } from 'vue';
import { onShow, onHide, onLoad, onUnload, onLaunch, onBackPress } from '@dcloudio/uni-app';
import common from '@/common/common';
import {getPhoneEnvBool} from '@/common/common';
import { getPhoneEnvBool } from '@/common/common';
import TouchBtn from './components/touchBtn.vue';
import ImagePreview from '@/components/image-preview/image-preview.vue';
import { commonUploadVoiceFile} from '@/api/common.js';
import { commonUploadVoiceFile } from '@/api/common.js';
import { queryTraPartnerCharacterInfoById, partnerChatReportTrigger } from '@/api/sparring.js';
import { useSocketStore } from '@/store/socket.js';
import { useStorageStore } from '@/store/storage.js';
@@ -244,19 +242,22 @@
});
// #endif
};
const toTalking = async () => {
try {
console.log('申请权限',getPhoneEnvBool('AND'));
if(getPhoneEnvBool('AND')){
//#ifdef APP-PLUS
console.log('申请权限', getPhoneEnvBool('AND'));
if (getPhoneEnvBool('AND')) {
console.log('申请权限');
await initRecord();
}
//#endif
common.setPageCache('tipMsgsceneDesc', {
sceneDesc: detailInfo.value.sceneDesc
ossAddr: detailInfo.value.ossAddr,
chaName: detailInfo.value.chaName,
traInterTyp: detailInfo.value.traInterTyp,
traInterTypDesc: detailInfo.value.traInterTypDesc,
});
common.navigateTo(
'/pages/sparring/talk?traId=' +
@@ -265,14 +266,14 @@
chaId.value +
'&type=' +
talkingType.value +
'&traInterTyp=' +
detailInfo.value.traInterTyp +
'&isPreview=' +
(isPreview.value ? '1' : '0')
);
} catch (err) {
console.error('申请权限失败');
}
};
const activeVoiceTalkingItemId = ref('');
// 关闭播放状态
@@ -298,7 +299,7 @@
const reconcatNum = ref(0);
const answerText = ref('');
const touchBtnCallBack = ref(null);
let isLeave = false
let isLeave = false;
const initsocketTask = () => {
let _src = isPreview.value ? '/trapractice/previewsocket/open' : '/trapractice/partnersocket/open';
socketStore.creatSocket(_src + '?summary=');
@@ -367,7 +368,7 @@
body: {
execId: execId.value || ''
}
})
});
return;
}
if (commond === 'ASK-START') {
@@ -478,16 +479,16 @@
return;
}
if (commond === 'ASK-PONG') {
console.log('PONG')
if(isLeave) return
setTimeout(()=>{
console.log('PONG');
if (isLeave) return;
setTimeout(() => {
sendMessage({
commond: 'ASK-PING',
body: {
execId: execId.value || ''
}
})
}, 30000)
});
}, 30000);
}
} else {
if (['0005', 'QQ0005'].includes(res.rtnCode)) {
@@ -547,14 +548,14 @@
};
const sendMessage = (data) => {
unref(SocketObj).send(data);
if(data.commond == 'ASK-PING'){
console.log('PING')
if (data.commond == 'ASK-PING') {
console.log('PING');
}
};
// let timer = null
//#ifdef APP-PLUS
onShow(() => {
isLeave = false
isLeave = false;
// timer = setInterval(() => {
// sendMessage({
// commond: 'ASK-PING',
@@ -565,10 +566,10 @@
// })
});
onHide(() => {
isLeave = true
isLeave = true;
// clearInterval(timer)
// timer = null
})
});
// #endif
onLoad((params) => {
traId.value = params.traId;
@@ -892,7 +893,7 @@
.talking-box {
padding-top: 24rpx;
.tip-text{
.tip-text {
color: #7295cb;
text-align: center;
font-size: 29rpx;
+103
View File
@@ -0,0 +1,103 @@
<template>
<view>
<view v-if="isPreviewing" class="live-container">
<cover-view class="pusher-container">
<live-pusher
id="livePusher"
class="livePusher"
:muted="true"
:enable-camera="true"
:auto-focus="true"
:beauty="0"
:whiteness="0"
aspect="9:16"
mode="SD"
orientation
></live-pusher>
</cover-view>
<!-- <cover-view class="corner-mask"></cover-view> -->
</view>
</view>
</template>
<script setup>
import { onMounted, ref, reactive, nextTick } from 'vue';
const livePusherContext = reactive({
value: null
});
const isPreviewing = ref(false);
const init = (componentProxy) => {
console.log('init');
livePusherContext.value = uni.createLivePusherContext('livePusher', componentProxy);
};
// 切换摄像头
const switchCamera = () => {
livePusherContext.value?.switchCamera({
success: (res) => {
console.log('livePusher.switchCamera:', JSON.stringify(res));
},
fail: (err) => {
console.error('切换摄像头失败:', err);
}
});
};
const rebuildContext = () => {
clearTimeout(contextTimer);
contextTimer = setTimeout(() => {
try {
// 先销毁旧上下文,再重建
cameraContext.value = null;
cameraContext.value = uni.createLivePusherContext('customCamera', instance);
} catch (err) {
console.error('重建上下文失败:', err);
}
}, 100);
};
// 开启预览
const startPreview = () => {
isPreviewing.value = true;
nextTick(() => {
livePusherContext.value?.startPreview({
success: (res) => {
console.log('摄像头开启成功');
},
fail: (err) => {
console.error('开启预览失败:', err);
},
complete: (err) => {
console.error('complete预览:', err);
}
});
});
};
// 关闭预览
const stopPreview = () => {
console.log('关闭预览');
livePusherContext.value?.stopPreview({
success: (res) => {
console.log('livePusher.stopPreview:', JSON.stringify(res));
},
fail: (err) => {
console.error('关闭预览失败:', err);
},
complete: (err) => {
console.error('complete预览:', err);
}
});
isPreviewing.value = false;
};
defineExpose({ init, switchCamera, stopPreview, startPreview });
</script>
<style scoped>
.live-container {
position: absolute;
right: 0;
top: 150rpx;
overflow: hidden;
border-radius: 20rpx;
width: 270rpx;
height: 480rpx;
}
</style>
+102
View File
@@ -0,0 +1,102 @@
<template>
<view >
<view v-if="isPreviewing">
<live-pusher
id="livePusher"
class="livePusher"
:muted="true"
:enable-camera="true"
:auto-focus="true"
:beauty="1"
whiteness="2"
aspect="9:16"
mode="SD"
></live-pusher>
</view>
<button class="btn" @click="startPreview">开启摄像头预览</button>
<button class="btn" @click="stopPreview">关闭摄像头预览</button>
<button class="btn" @click="switchCamera">切换摄像头</button>
</view>
</template>
<script setup>
import { onMounted, ref, reactive, nextTick } from 'vue';
const livePusherContext = reactive({
value: null
});
const isPreviewing = ref(false);
const init = (componentProxy) => {
console.log('init');
livePusherContext.value = uni.createLivePusherContext('livePusher', componentProxy);
};
// 切换摄像头
const switchCamera = () => {
livePusherContext.value?.switchCamera({
success: (res) => {
console.log('livePusher.switchCamera:', JSON.stringify(res));
},
fail: (err) => {
console.error('切换摄像头失败:', err);
}
});
};
const rebuildContext = () => {
clearTimeout(contextTimer);
contextTimer = setTimeout(() => {
try {
// 先销毁旧上下文,再重建
cameraContext.value = null;
cameraContext.value = uni.createLivePusherContext('customCamera', instance);
} catch (err) {
console.error('重建上下文失败:', err);
}
}, 100);
};
// 开启预览
const startPreview = () => {
isPreviewing.value = true;
nextTick(() => {
livePusherContext.value?.startPreview({
success: (res) => {
console.log('摄像头开启成功');
},
fail: (err) => {
console.error('开启预览失败:', err);
},
complete: (err) => {
console.error('complete预览:', err);
}
});
});
};
// 关闭预览
const stopPreview = () => {
console.log('关闭预览');
livePusherContext.value?.stopPreview({
success: (res) => {
console.log('livePusher.stopPreview:', JSON.stringify(res));
},
fail: (err) => {
console.error('关闭预览失败:', err);
},
complete: (err) => {
console.error('complete预览:', err);
}
});
isPreviewing.value = false;
};
defineExpose({ init, switchCamera, stopPreview, startPreview });
</script>
<style scoped>
/* 可根据需要添加样式 */
.livePusher {
width: 100%;
height: 400px;
}
.btn {
margin: 10px;
padding: 10px 20px;
}
</style>
+32 -7
View File
@@ -1,13 +1,38 @@
<template>
<view class="hidden">
<view class="">
<view class="cssss">
<CameraPreview ref="CameraPreviewRef"></CameraPreview>
</view>
<view style="margin-top: 400rpx">
<button class="btn" @click="startPreview">开启摄像头预览</button>
<button class="btn" @click="stopPreview">关闭摄像头预览</button>
<button class="btn" @click="switchCamera">切换摄像头</button>
</view>
</view>
</template>
<script>
</script>
<script setup>
import CameraPreview from './CameraPreview';
import { onReady } from '@dcloudio/uni-app';
import { ref, getCurrentInstance } from 'vue';
const CameraPreviewRef = ref(null);
const instance = getCurrentInstance();
const componentProxy = instance.ctx;
const startPreview = () => {
CameraPreviewRef.value.startPreview();
};
const stopPreview = () => {
CameraPreviewRef.value.stopPreview();
};
const switchCamera = () => {
CameraPreviewRef.value.switchCamera();
};
onReady(() => {
CameraPreviewRef.value.init(componentProxy);
});
</script>
<style>
</style>
</style>
View File
+762
View File
@@ -0,0 +1,762 @@
<template>
<view class="page-container">
<!-- 头部标题栏 -->
<view class="header">
<text class="title">摄像头预览</text>
</view>
<!-- 主要内容区域 -->
<view class="main-content">
<!-- 预览窗口容器 -->
<view class="preview-section" v-if="isPreviewing">
<view class="section-title">
<text>摄像头预览</text>
<text class="preview-status">● 预览中</text>
</view>
<!-- 预览窗口 -->
<view class="preview-box">
<live-pusher
id="livePusher"
ref="livePusher"
class="live-preview"
:url="''"
mode="SD"
:autopush="false"
:muted="true"
:enable-camera="true"
:auto-focus="true"
:orientation="orientation"
:beauty="beautyLevel"
:whiteness="whiteLevel"
:aspect="aspectRatio"
:min-bitrate="300"
:max-bitrate="1000"
@statechange="onStateChange"
@error="onError"
@netstatus="onNetStatus"
/>
<!-- 预览窗口边框装饰 -->
<view class="preview-frame"></view>
</view>
<!-- 预览控制按钮 -->
<view class="preview-controls">
<button
class="control-btn switch-btn"
@click="switchCamera"
:disabled="!isPreviewing"
>
🔄 切换摄像头
</button>
<button
class="control-btn close-btn"
@click="closePreview"
>
❌ 关闭预览
</button>
</view>
</view>
<!-- 未预览时的占位区域 -->
<view class="placeholder-section" v-else>
<view class="section-title">
<text>预览功能</text>
</view>
<view class="placeholder-box">
<text class="placeholder-icon">📷</text>
<text class="placeholder-text">点击开始预览体验摄像头功能</text>
</view>
<button class="start-btn" @click="startPreview">
🎥 开始预览
</button>
</view>
<!-- 设置面板 -->
<view class="settings-section" v-if="showSettings">
<view class="section-title">
<text>预览设置</text>
<text class="close-settings" @click="closeSettings">✕</text>
</view>
<view class="settings-content">
<view class="setting-group">
<text class="group-title">显示设置</text>
<view class="setting-item">
<text class="setting-label">方向模式</text>
<picker
@change="onOrientationChange"
:value="orientationIndex"
:range="orientationOptions"
class="setting-picker"
>
<view class="picker-display">
{{ orientationOptions[orientationIndex] }}
<text class="arrow">▼</text>
</view>
</picker>
</view>
<view class="setting-item">
<text class="setting-label">画面比例</text>
<picker
@change="onAspectChange"
:value="aspectIndex"
:range="aspectOptions"
class="setting-picker"
>
<view class="picker-display">
{{ aspectOptions[aspectIndex] }}
<text class="arrow">▼</text>
</view>
</picker>
</view>
</view>
<view class="setting-group">
<text class="group-title">美化设置</text>
<view class="setting-item">
<text class="setting-label">美颜等级: {{ beautyLevel }}</text>
<slider
:value="beautyLevel"
min="0"
max="9"
step="1"
@change="onBeautyChange"
activeColor="#007AFF"
class="setting-slider"
/>
</view>
<view class="setting-item">
<text class="setting-label">美白等级: {{ whiteLevel }}</text>
<slider
:value="whiteLevel"
min="0"
max="9"
step="1"
@change="onWhiteChange"
activeColor="#007AFF"
class="setting-slider"
/>
</view>
</view>
<button class="apply-btn" @click="applySettings">应用设置</button>
</view>
</view>
</view>
<!-- 底部功能区 -->
<view class="bottom-section">
<!-- 快捷设置按钮 -->
<view class="quick-actions" v-if="isPreviewing">
<button class="action-btn settings-action" @click="openSettings">
⚙️ 设置
</button>
<button class="action-btn capture-action" @click="captureFrame">
📸 截图
</button>
</view>
<!-- 功能说明 -->
<view class="info-section">
<text class="info-text">
💡 提示:预览功能仅用于查看摄像头画面,不会产生任何推流或录制
</text>
</view>
</view>
<!-- 遮罩层 -->
<view
class="overlay"
v-if="showSettings"
@click="closeSettings"
></view>
</view>
</template>
<script>
export default {
data() {
return {
// 预览状态
isPreviewing: false,
showSettings: false,
sssssssss: true,
// 预览配置
orientation: 'vertical',
orientationOptions: ['竖屏', '横屏'],
orientationIndex: 0,
aspectRatio: '9:16',
aspectOptions: ['9:16', '3:4', '1:1'],
aspectIndex: 0,
beautyLevel: 0,
whiteLevel: 0,
// LivePusher 上下文
livePusherCtx: null
}
},
methods: {
// 开始预览
async startPreview() {
try {
console.log('开始启动预览...');
// 创建 live-pusher 上下文
this.livePusherCtx = uni.createLivePusherContext('livePusher', this);
// 显示预览界面
this.isPreviewing = true;
// 启动预览(不推流)
this.$nextTick(() => {
if (this.livePusherCtx) {
this.livePusherCtx.startPreview({
success: () => {
console.log('预览启动成功');
uni.showToast({
title: '预览已开始',
icon: 'success'
});
},
fail: (err) => {
console.error('预览启动失败:', err);
this.handlePreviewError(err);
}
});
}
});
} catch (error) {
console.error('启动预览异常:', error);
uni.showToast({
title: '预览启动失败',
icon: 'error'
});
}
},
// 关闭预览
closePreview() {
uni.showModal({
title: '确认关闭',
content: '确定要关闭摄像头预览吗?',
success: (res) => {
if (res.confirm) {
this.doClosePreview();
}
}
});
},
// 执行关闭预览
doClosePreview() {
try {
console.log('正在关闭预览...');
// 停止预览
if (this.livePusherCtx) {
this.livePusherCtx.stopPreview({
success: () => {
console.log('预览已停止');
},
fail: (err) => {
console.error('停止预览失败:', err);
}
});
}
// 重置状态
this.isPreviewing = false;
this.showSettings = false;
uni.showToast({
title: '预览已关闭1',
icon: 'success'
});
// this.sssssssss = false;
} catch (error) {
console.error('关闭预览异常:', error);
// 强制更新状态
this.isPreviewing = false;
this.showSettings = false;
}
},
// 切换摄像头
switchCamera() {
if (!this.livePusherCtx || !this.isPreviewing) return;
uni.showLoading({
title: '切换中...'
});
this.livePusherCtx.switchCamera({
success: () => {
console.log('摄像头切换成功');
uni.hideLoading();
uni.showToast({
title: '摄像头已切换',
icon: 'success'
});
},
fail: (err) => {
console.error('摄像头切换失败:', err);
uni.hideLoading();
uni.showToast({
title: '切换失败',
icon: 'error'
});
}
});
},
// 打开设置面板
openSettings() {
this.showSettings = true;
},
// 关闭设置面板
closeSettings() {
this.showSettings = false;
},
// 应用设置
applySettings() {
uni.showToast({
title: '设置已应用',
icon: 'success'
});
this.closeSettings();
},
// 方向改变
onOrientationChange(e) {
this.orientationIndex = e.detail.value;
this.orientation = this.orientationIndex === 0 ? 'vertical' : 'horizontal';
},
// 宽高比改变
onAspectChange(e) {
this.aspectIndex = e.detail.value;
this.aspectRatio = this.aspectOptions[this.aspectIndex];
},
// 美颜等级改变
onBeautyChange(e) {
this.beautyLevel = e.detail.value;
},
// 美白等级改变
onWhiteChange(e) {
this.whiteLevel = e.detail.value;
},
// 截图功能(可选)
captureFrame() {
uni.showToast({
title: '截图功能开发中',
icon: 'none'
});
},
// 预览状态变化
onStateChange(e) {
console.log('预览状态变化:', e.detail);
},
// 错误处理
onError(e) {
console.error('预览错误:', e.detail);
const error = e.detail;
let errorMsg = '预览出现错误';
switch(error.errCode) {
case 1001:
errorMsg = '摄像头权限被拒绝';
break;
case 1002:
errorMsg = '麦克风权限被拒绝';
break;
case 1003:
errorMsg = '摄像头被其他应用占用';
break;
case 1004:
errorMsg = '设备不支持';
break;
}
uni.showModal({
title: '预览错误',
content: errorMsg,
showCancel: false,
success: () => {
this.closePreview();
}
});
},
// 网络状态
onNetStatus(e) {
console.log('预览网络状态:', e.detail);
},
// 处理预览错误
handlePreviewError(err) {
uni.showModal({
title: '预览启动失败',
content: '请检查摄像头权限或稍后重试',
showCancel: false,
success: () => {
this.isPreviewing = false;
}
});
}
},
beforeDestroy() {
if (this.isPreviewing) {
this.doClosePreview();
}
}
}
</script>
<style scoped>
.page-container {
min-height: 100vh;
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
display: flex;
flex-direction: column;
}
/* 头部样式 */
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 20px;
text-align: center;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
.title {
color: white;
font-size: 20px;
font-weight: bold;
}
/* 主要内容区域 */
.main-content {
flex: 1;
padding: 20px;
display: flex;
flex-direction: column;
gap: 20px;
}
/* 区域标题 */
.section-title {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 15px;
padding: 0 10px;
}
.section-title text:first-child {
font-size: 18px;
font-weight: bold;
color: #333;
}
.preview-status {
font-size: 14px;
color: #4CAF50;
}
.close-settings {
font-size: 20px;
color: #999;
padding: 5px 10px;
cursor: pointer;
}
/* 预览区域 */
.preview-section, .placeholder-section {
background: white;
border-radius: 15px;
padding: 20px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}
/* 预览窗口盒子 */
.preview-box {
position: relative;
width: 280px;
height: 373px; /* 9:16 比例 */
margin: 0 auto 20px;
border-radius: 12px;
overflow: hidden;
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}
.live-preview {
width: 100%;
height: 100%;
background-color: #000;
}
/* 预览窗口边框装饰 */
.preview-frame {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
border: 3px solid rgba(0, 122, 255, 0.3);
border-radius: 12px;
pointer-events: none;
}
/* 占位符样式 */
.placeholder-box {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 200px;
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
border-radius: 12px;
margin-bottom: 20px;
}
.placeholder-icon {
font-size: 48px;
margin-bottom: 15px;
}
.placeholder-text {
color: white;
font-size: 16px;
text-align: center;
}
/* 按钮样式 */
.control-btn, .start-btn {
padding: 12px 24px;
border: none;
border-radius: 25px;
font-size: 16px;
font-weight: 500;
cursor: pointer;
transition: all 0.3s ease;
}
.control-btn {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
margin: 0 10px;
}
.control-btn:disabled {
background: #ccc;
cursor: not-allowed;
}
.close-btn {
background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
color: white;
}
.start-btn {
background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
color: white;
width: 200px;
}
.preview-controls {
display: flex;
justify-content: center;
align-items: center;
}
/* 设置区域 */
.settings-section {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: white;
border-radius: 20px;
padding: 25px;
width: 90%;
max-width: 450px;
max-height: 80vh;
overflow-y: auto;
z-index: 1000;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}
.settings-content {
margin-top: 15px;
}
.setting-group {
margin-bottom: 25px;
}
.group-title {
display: block;
font-size: 16px;
font-weight: bold;
color: #333;
margin-bottom: 15px;
padding-bottom: 8px;
border-bottom: 2px solid #f0f0f0;
}
.setting-item {
margin-bottom: 20px;
}
.setting-label {
display: block;
font-size: 14px;
color: #555;
margin-bottom: 8px;
font-weight: 500;
}
.setting-picker {
width: 100%;
}
.picker-display {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 15px;
background: #f8f9fa;
border: 1px solid #e9ecef;
border-radius: 8px;
font-size: 14px;
}
.arrow {
color: #999;
font-size: 12px;
}
.setting-slider {
width: 100%;
margin: 10px 0;
}
.apply-btn {
width: 100%;
padding: 15px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
border-radius: 10px;
font-size: 16px;
font-weight: 500;
margin-top: 10px;
}
/* 底部区域 */
.bottom-section {
background: white;
padding: 20px;
box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}
.quick-actions {
display: flex;
justify-content: center;
gap: 20px;
margin-bottom: 20px;
}
.action-btn {
padding: 10px 20px;
border: none;
border-radius: 20px;
font-size: 14px;
cursor: pointer;
transition: all 0.3s ease;
}
.settings-action {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.capture-action {
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
color: white;
}
.info-section {
text-align: center;
padding: 15px;
background: #f8f9fa;
border-radius: 10px;
}
.info-text {
font-size: 13px;
color: #666;
line-height: 1.5;
}
/* 遮罩层 */
.overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.5);
z-index: 999;
}
/* 响应式设计 */
@media (max-width: 480px) {
.main-content {
padding: 15px;
}
.preview-box {
width: 240px;
height: 320px;
}
.preview-controls {
flex-direction: column;
gap: 10px;
}
.control-btn {
margin: 5px 0;
}
.quick-actions {
flex-direction: column;
align-items: center;
}
.action-btn {
width: 200px;
}
}
</style>
+20
View File
@@ -0,0 +1,20 @@
<template>
<view class="">
<CameraPreview ref="CameraPreviewRef"></CameraPreview>
</view>
</template>
<script setup>
import CameraPreview from './CameraPreview'
import { onReady } from '@dcloudio/uni-app';
import { ref , getCurrentInstance} from 'vue';
const CameraPreviewRef = ref(null);
const instance = getCurrentInstance();
const componentProxy = instance.ctx
onReady(() => {
CameraPreviewRef.value.init(componentProxy)
})
</script>