12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021 |
- <template>
- <div class="identity-verify-container">
- <div class="digital-human-container">
- <!-- AI数字人视频/图像显示区域 -->
- <div class="digital-human-video">
- <!-- <image v-if="!videoPlaying" src="/static/images/digital-human-placeholder.jpg" mode="aspectFit"></image> -->
- <video
- :src="videoUrl"
- id="myVideo"
- ref="videoPlayer"
- autoplay
- playsinline
- disablePictureInPicture
- controlsList="nodownload nofullscreen noremoteplayback"
- class="video-player"
- :controls="false"
- @error="handleVideoError"
- @ended="handleVideoEnded"
- @timeupdate="handleTimeUpdate">
- </video>
-
- <!-- 添加字幕覆盖层 -->
- <div class="subtitle-overlay" v-if="currentSubtitle">
- {{ currentSubtitle }}
- </div>
-
- <!-- 添加答题按钮 -->
- <div class="answer-button-container" v-if="showAnswerButton">
- <button class="answer-button" @click="handleAnswerButtonClick">
- 开始面试
- </button>
- </div>
- </div>
-
- <!-- 用户摄像头视频显示区域 -->
- <div class="user-camera-container">
- <!-- 在小程序环境中使用camera组件 -->
- <camera v-if="useMiniProgramCameraComponent"
- device-position="front"
- flash="off"
- class="user-camera-video"
- @error="handleCameraError"
- :record-audio="true">
- </camera>
- <!-- 在H5/App环境中使用video元素 -->
- <video v-else
- id="userCamera"
- ref="userCameraVideo"
- autoplay
- playsinline
- muted
- class="user-camera-video"
- :controls="false">
- </video>
- </div>
-
- <!-- 字幕/文本覆盖区域 -->
- <!-- <div class="subtitle-overlay" v-if="assistantResponse">
- {{ assistantResponse }}
- </div> -->
- </div>
- <!-- 加载状态 -->
- <div v-if="loading" class="loading">加载中...</div>
-
- <!-- 控制面板(可选,可以隐藏) -->
-
- <!-- 响应数据(可以设为隐藏,仅用于调试) -->
- <div v-if="showDebugInfo" class="response-container">
- <div v-if="assistantResponse" class="response-item">
- <div class="response-content">
- <span>助手回复: {{ assistantResponse }}</span>
- </div>
- </div>
- <div v-if="audioTranscript" class="response-item">
- <div class="response-content">
- <span>音频转写: {{ audioTranscript }}</span>
- </div>
- </div>
- <div v-for="(item, index) in processedResponses" :key="index" class="response-item">
- <div class="response-content">
- <span v-if="item.role">角色: {{ item.role }}</span>
- <span v-if="item.transcript">文本: {{ item.transcript }}</span>
- </div>
- </div>
- </div>
- <!-- 添加停止录制按钮 -->
- <div class="stop-recording-button-container" v-if="showStopRecordingButton">
- <button class="stop-recording-button" @click="stopRecordingAnswer">
- 完成作答
- </button>
- </div>
- <!-- 添加录制指示器 -->
- <div class="recording-indicator" v-if="isRecording">
- <div class="recording-dot"></div>
- <span class="recording-text">正在录制...</span>
- </div>
- <!-- 添加开始回答按钮 -->
- <div class="start-recording-button-container" v-if="showStartRecordingButton">
- <button class="start-recording-button" @click="handleStartRecordingClick">
- 开始作答
- </button>
- </div>
- <!-- 添加重试上传按钮 -->
- <div class="retry-button-container" v-if="showRetryButton">
- <button class="retry-button" @click="retryVideoUpload">
- 重新上传
- </button>
- </div>
- </div>
- </template>
- <script>
- import { apiBaseUrl } from '@/common/config.js';
- export default {
- name: 'IdentityVerify',
- data() {
- return {
- loading: false,
- responses: [],
- processedResponses: [],
- assistantResponse: '',
- audioTranscript: '',
- videoPlaying: false,
- showDebugInfo: false, // 设置为true可以显示调试信息
- videoUrl: 'http://121.36.251.245:9000/minlong/9c139c99-a613-49f2-986b-8a3ac20a9b1b.mp4', // 用于存储AI数字人视频URL
- showReplayButton: false,
- cameraStream: null, // 存储摄像头流
- cameraError: null, // 存储摄像头错误信息
- useMiniProgramCameraComponent: false, // 添加小程序相机组件标志
- cameraContext: null, // 添加相机上下文
- currentSubtitle: '',
- subtitles: [
- {
- startTime: 0, // 开始时间(秒)
- endTime: 5, // 结束时间(秒)
- text: '你好,我是本次面试的面试官,欢迎参加本公司的线上面试!'
- },
- {
- startTime: 5,
- endTime: 13,
- text: '面试预计需要15分钟,请你提前安排在网络良好、光线亮度合适、且相对安静的环境参加这次面试'
- },
- {
- startTime: 13,
- endTime: 20,
- text: '以免影响本次面试的结果。如果你在面试过程中遇到问题,请与我们的招聘人员联系。'
- }
- ],
- secondVideoSubtitles: [
- {
- startTime: 0,
- endTime: 10,
- text: '请结合您的基本信息与过往履历进行简单的自我介绍,并讲一讲您有哪些优势胜任本岗位:'
- }
- ],
- thirdVideoSubtitles: [
- {
- startTime: 0,
- endTime: 3,
- text: '在工作中,你如何确保个人防护装备的正确使用?'
- }
- ],
- fourthVideoSubtitles: [
- {
- startTime: 0,
- endTime: 3,
- text: '描述一次你与团队合作改善生产流程的经历。'
- }
- ],
- fifthVideoSubtitles: [
- {
- startTime: 0,
- endTime: 6,
- text: '你在团队合作中曾遇到过哪些挑战?如何解决团队内部的分歧?'
- }
- ],
- sixthVideoSubtitles: [
- {
- startTime: 0,
- endTime: 5,
- text: '您已完成本次面试全部题目,请问您对于这个岗位还有什么想要了解的吗?'
- }
- ],
- showAnswerButton: false, // 控制答题按钮显示
- currentVideoIndex: 0, // 当前播放的视频索引
- videoList: [
- 'http://121.36.251.245:9000/minlong/9c139c99-a613-49f2-986b-8a3ac20a9b1b.mp4', // 第一段视频
- 'http://121.36.251.245:9000/minlong/15467aca-2c1e-4d40-bebc-11fc984f0a24.mp4', // 第二段视频
- 'http://121.36.251.245:9000/minlong/a96f295c-ecba-4b08-b627-0ed0dc72d727.mp4', // 第三段视频
- 'http://121.36.251.245:9000/minlong/e152eb38-7e03-4bb0-8b8d-73d51342d2aa.mp4',
- 'http://121.36.251.245:9000/minlong/6381eec3-1373-400f-aa8c-e229b60522ea.mp4',
- 'http://121.36.251.245:9000/minlong/2a11fe78-38d5-4af3-91c8-a080feb122e0.mp4'//结束
- ],
- isRecording: false,
- recordingTimer: null,
- showStopRecordingButton: false,
- mediaRecorder: null,
- recordedChunks: [],
- recorder: null,
- lastUploadedVideoUrl: '',
- showStartRecordingButton: false,
- showRetryButton: false, // 控制重试按钮显示
- lastVideoToRetry: null, // 存储上次失败的视频URL,用于重试
- }
- },
- mounted() {
- /* this.fetchData() */
- this.playDigitalHumanVideo();
- this.checkAudioPermission();
- this.initCamera();
-
- // 添加音频测试
- setTimeout(() => {
- if (this.cameraStream && !this.useMiniProgramCameraComponent) {
- this.testAudioInput();
- }
- }, 3000);
- },
- beforeDestroy() {
- // 组件销毁前停止摄像头
- this.stopUserCamera();
- },
- methods: {
- // 初始化相机
- async initCamera() {
- // 检查平台
- const systemInfo = uni.getSystemInfoSync();
-
- // 判断是否在小程序环境中
- const isMiniProgram = systemInfo.uniPlatform === 'mp-weixin' ||
- systemInfo.uniPlatform === 'mp-alipay' ||
- systemInfo.uniPlatform === 'mp-baidu';
-
- if (isMiniProgram) {
- // 小程序环境使用小程序的相机API
- this.useMiniProgramCameraComponent = true;
-
- // 创建相机上下文
- this.cameraContext = uni.createCameraContext();
-
- // 确保已获取录音权限
- uni.getSetting({
- success: (res) => {
- if (!res.authSetting['scope.record']) {
- uni.authorize({
- scope: 'scope.record',
- success: () => {
- console.log('录音权限已获取');
- },
- fail: (err) => {
- console.error('录音权限获取失败:', err);
- this.showPermissionDialog('录音');
- }
- });
- }
-
- if (!res.authSetting['scope.camera']) {
- uni.authorize({
- scope: 'scope.camera',
- success: () => {
- console.log('相机权限已获取');
- },
- fail: (err) => {
- console.error('相机权限获取失败:', err);
- this.showPermissionDialog('相机');
- }
- });
- }
- }
- });
- } else {
- // H5/App环境使用浏览器的API
- try {
- // 请求摄像头和麦克风权限并获取媒体流
- const constraints = {
- audio: {
- echoCancellation: true,
- noiseSuppression: true,
- autoGainControl: true
- },
- video: {
- width: { ideal: 640 },
- height: { ideal: 480 },
- facingMode: 'user'
- }
- };
-
- const stream = await navigator.mediaDevices.getUserMedia(constraints);
-
- // 保存流以便后续使用
- this.cameraStream = stream;
-
- // 检查音频轨道
- const audioTracks = stream.getAudioTracks();
- console.log('音频轨道数量:', audioTracks.length);
- if (audioTracks.length > 0) {
- console.log('音频轨道已获取:', audioTracks[0].label);
- // 确保音频轨道已启用
- audioTracks[0].enabled = true;
- } else {
- console.warn('未检测到音频轨道,尝试单独获取音频');
- this.tryGetAudioOnly();
- }
-
- // 将流设置到视频元素
- const videoElement = this.$refs.userCameraVideo;
- if (videoElement) {
- videoElement.srcObject = stream;
- videoElement.muted = true; // 避免回声,但仍然录制声音
- }
- } catch (error) {
- console.error('获取摄像头失败:', error);
- this.cameraError = error.message || '无法访问摄像头';
-
- // 显示错误提示
- uni.showToast({
- title: '无法访问摄像头,请检查权限设置',
- icon: 'none'
- });
- }
- }
- },
-
- // 停止用户摄像头
- stopUserCamera() {
- if (this.cameraStream) {
- // 停止所有轨道
- this.cameraStream.getTracks().forEach(track => {
- track.stop();
- });
- this.cameraStream = null;
- }
- },
-
- async fetchData() {
- this.loading = true
- this.assistantResponse = ''
- this.audioTranscript = ''
- this.processedResponses = []
- try {
- // 使用uni.request代替fetch
- const requestTask = uni.request({
- url: 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions',
- method: 'POST',
- header: {
- 'Content-Type': 'application/json',
- 'Authorization': 'Bearer sk-9e1ec73a7d97493b8613c63f06b6110c'
- },
- data: {
- "model": "qwen-omni-turbo",
- "messages": [
- {
- "role": "user",
- "content": [
- {
- "type": "input_audio",
- "input_audio": {
- "data": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250211/tixcef/cherry.wav",
- "format": "wav"
- }
- },
- {
- "type": "text",
- "text": "这段音频在说什么"
- }
- ]
- }
- ],
- "stream":true,
- "stream_options":{
- "include_usage":true
- },
- "modalities":["text","audio"],
- "audio":{"voice":"Cherry","format":"wav"}
- },
- success: (res) => {
- console.log('请求成功,响应数据:', res.data);
- // 检查响应数据是否包含多个JSON对象
- if (typeof res.data === 'string' && res.data.includes('data: {')) {
- // 处理包含多个JSON对象的情况
- const chunks = res.data.split('data: ').filter(chunk => chunk.trim() !== '');
- chunks.forEach(chunk => {
- this.handleStreamResponse(chunk);
- });
- } else {
- // 处理单个响应对象的情况
- this.handleStreamResponse(res.data);
- }
-
- // 模拟获取到数字人视频并播放
- this.playDigitalHumanVideo();
- },
- fail: (err) => {
- console.error('请求失败:', err);
- },
- complete: () => {
- this.loading = false;
- }
- });
- } catch (error) {
- console.error('获取数据失败:', error);
- this.loading = false;
- }
- },
-
- handleStreamResponse(data) {
- // 处理流式响应数据
- if (typeof data === 'string') {
- // 处理字符串格式的响应
- if (data === '[DONE]') return;
-
- try {
- // 移除可能存在的换行符和多余空格
- const cleanData = data.trim();
- // 检查是否是有效的JSON字符串
- if (cleanData.startsWith('{') && cleanData.endsWith('}')) {
- const jsonData = JSON.parse(cleanData);
- this.processStreamChunk(jsonData);
- }
- } catch (e) {
- console.error('解析JSON失败:', e, '原始数据:', data);
- }
- } else {
- // 处理对象格式的响应
- this.processStreamChunk(data);
- }
- },
-
- processStreamChunk(chunk) {
- if (chunk.choices && chunk.choices.length > 0) {
- const choice = chunk.choices[0];
-
- // 处理助手回复内容
- if (choice.delta && choice.delta.content) {
- this.assistantResponse += choice.delta.content;
- }
-
- // 处理音频转写内容
- if (choice.delta && choice.delta.audio && choice.delta.audio.transcript) {
- this.audioTranscript += choice.delta.audio.transcript;
- }
-
- // 处理角色和音频转写
- if (choice.delta) {
- const result = {};
-
- if (choice.delta.role) {
- result.role = choice.delta.role;
- }
-
- if (choice.delta.audio && choice.delta.audio.transcript) {
- result.transcript = choice.delta.audio.transcript;
- }
-
- if (Object.keys(result).length > 0) {
- this.processedResponses.push(result);
- }
- }
- }
- },
-
- processResponseData() {
- // 处理返回的数据
- this.processedResponses = this.responses.map(item => {
- const result = {}
-
- // 处理角色信息
- if (item.delta && item.delta.role) {
- result.role = item.delta.role
- }
-
- // 处理音频转写文本
- if (item.delta && item.delta.audio && item.delta.audio.transcript) {
- result.transcript = item.delta.audio.transcript
- }
-
- return result
- }).filter(item => Object.keys(item).length > 0)
- },
-
- // 播放数字人视频
- playDigitalHumanVideo() {
- // 设置第一个视频
- this.videoUrl = this.videoList[this.currentVideoIndex];
- this.videoPlaying = true;
-
- // 使用 uni.createVideoContext 来控制视频
- this.$nextTick(() => {
- const videoContext = uni.createVideoContext('myVideo', this);
- if (videoContext) {
- videoContext.play();
-
- // 设置超时检查,确认视频是否真的在播放
- setTimeout(() => {
- if (this.videoPlaying && this.$refs.videoPlayer) {
- console.log('视频应该正在播放');
- } else {
- console.log('视频可能未成功播放,尝试替代方案');
- this.tryAlternativeVideoPath();
- }
- }, 1000);
- } else {
- console.error('无法创建视频上下文');
- this.tryAlternativeVideoPath();
- }
- });
- },
-
- // 修改 tryAlternativeVideoPath 方法
- tryAlternativeVideoPath() {
- console.log('尝试使用替代路径');
-
- // 尝试不同的路径格式
- const alternativePaths = [
- './static/demo.mp4',
- '../static/demo.mp4',
- 'static/demo.mp4',
- '/static/demo.mp4',
- // 添加绝对路径
- `${window.location.origin}/static/demo.mp4`
- ];
-
- // 获取当前路径索引
- const currentPathIndex = alternativePaths.indexOf(this.videoUrl);
- const nextPathIndex = (currentPathIndex + 1) % alternativePaths.length;
-
- // 设置下一个路径
- this.videoUrl = alternativePaths[nextPathIndex];
- console.log('尝试新路径:', this.videoUrl);
-
- this.$nextTick(() => {
- const videoContext = uni.createVideoContext('myVideo', this);
- if (videoContext) {
- videoContext.stop();
- videoContext.play();
-
- // 检查是否成功播放
- setTimeout(() => {
- if (nextPathIndex === alternativePaths.length - 1 && !this.videoPlaying) {
- console.log('所有路径均失败,尝试使用uni.getVideoInfo检查视频');
- this.checkVideoWithAPI();
- }
- }, 1000);
- }
- });
- },
-
- // 添加新方法:使用uni API检查视频
- checkVideoWithAPI() {
- // 尝试使用uni.getVideoInfo API检查视频是否可用
- uni.getVideoInfo({
- src: '/static/demo.mp4',
- success: (res) => {
- console.log('视频信息获取成功:', res);
- // 如果能获取到视频信息,再次尝试播放
- this.videoUrl = '/static/demo.mp4';
- this.$nextTick(() => {
- const videoContext = uni.createVideoContext('myVideo', this);
- if (videoContext) {
- videoContext.play();
- }
- });
- },
- fail: (err) => {
- console.error('视频信息获取失败:', err);
- // 最后尝试使用uni.chooseVideo API
- this.fallbackToLocalVideo();
- }
- });
- },
-
- // 添加新方法:回退到本地视频
- fallbackToLocalVideo() {
- console.log('尝试使用本地视频资源');
-
- // 检查平台
- const platform = uni.getSystemInfoSync().platform;
- if (platform === 'android' || platform === 'ios') {
- // 移动端可以尝试使用本地资源
- this.videoUrl = platform === 'android' ? 'android.resource://package_name/raw/demo' : 'file:///assets/demo.mp4';
- this.$nextTick(() => {
- const videoContext = uni.createVideoContext('myVideo', this);
- if (videoContext) {
- videoContext.play();
- }
- });
- } else {
- // 最终回退到静态图片
- this.videoPlaying = false;
- uni.showToast({
- title: '视频加载失败,显示静态图片',
- icon: 'none'
- });
- }
- },
-
- // 修改 handleVideoError 方法
- handleVideoError(e) {
- console.error('视频加载错误:', e);
-
- // 记录更详细的错误信息
- if (e && e.detail) {
- console.error('详细错误信息:', e.detail);
- }
-
- // 检查视频文件是否存在
- uni.getFileInfo({
- filePath: this.videoUrl.startsWith('/') ? this.videoUrl.substring(1) : this.videoUrl,
- success: (res) => {
- console.log('文件存在,大小:', res.size);
- // 文件存在但播放失败,可能是格式问题
- this.tryDifferentFormat();
- },
- fail: (err) => {
- console.error('文件不存在或无法访问:', err);
- // 尝试不同路径
- this.tryAlternativeVideoPath();
- }
- });
-
- // 如果多次尝试后仍然失败,显示错误信息
- uni.showToast({
- title: '视频加载失败,请检查文件是否存在',
- icon: 'none',
- duration: 2000
- });
- },
- // 添加新方法:尝试不同格式
- tryDifferentFormat() {
- console.log('尝试不同的视频格式');
-
- // 尝试不同的视频格式
- const formats = [
- { ext: 'mp4', mime: 'video/mp4' },
- { ext: 'webm', mime: 'video/webm' },
- { ext: 'ogg', mime: 'video/ogg' },
- { ext: 'mov', mime: 'video/quicktime' }
- ];
-
- // 获取当前文件名(不含扩展名)
- const currentPath = this.videoUrl;
- const basePath = currentPath.substring(0, currentPath.lastIndexOf('.')) || '/static/demo';
-
- // 尝试下一个格式
- let nextFormat = formats.find(f => !currentPath.endsWith(f.ext));
- if (nextFormat) {
- this.videoUrl = `${basePath}.${nextFormat.ext}`;
- console.log('尝试新格式:', this.videoUrl);
-
- this.$nextTick(() => {
- const videoContext = uni.createVideoContext('myVideo', this);
- if (videoContext) {
- videoContext.stop();
- videoContext.play();
- }
- });
- } else {
- // 所有格式都尝试过了,使用内置资源
- this.useBuiltInResource();
- }
- },
- // 添加新方法:使用内置资源
- useBuiltInResource() {
- console.log('尝试使用内置资源');
-
- // 检查平台
- const platform = uni.getSystemInfoSync().platform;
-
- // 根据平台选择合适的视频源
- if (platform === 'windows') {
- // Windows平台特定处理
- // 尝试使用相对于应用根目录的路径
- const appRoot = process.env.UNI_INPUT_DIR || '';
- this.videoUrl = `./static/demo.mp4`;
-
- // 或者尝试使用file://协议
- // this.videoUrl = `file:///${appRoot.replace(/\\/g, '/')}/static/demo.mp4`;
-
- console.log('Windows平台尝试路径:', this.videoUrl);
- } else if (platform === 'android' || platform === 'ios') {
- // 移动端
- this.useNativeVideo();
- } else {
- // Web平台
- // 尝试使用完整URL
- const baseUrl = window.location.origin;
- this.videoUrl = `${baseUrl}/static/demo.mp4`;
- console.log('Web平台尝试URL:', this.videoUrl);
- }
-
- this.$nextTick(() => {
- const videoContext = uni.createVideoContext('myVideo', this);
- if (videoContext) {
- videoContext.play();
- }
- });
- },
- // 添加新方法:使用原生视频能力
- useNativeVideo() {
- console.log('尝试使用原生视频能力');
-
- // 在移动端,可以尝试使用原生视频播放器
- uni.chooseVideo({
- sourceType: ['album'],
- success: (res) => {
- this.videoUrl = res.tempFilePath;
- this.$nextTick(() => {
- const videoContext = uni.createVideoContext('myVideo', this);
- if (videoContext) {
- videoContext.play();
- }
- });
- },
- fail: () => {
- // 如果用户取消选择,回退到静态图片
- this.videoPlaying = false;
- uni.showToast({
- title: '无法加载视频,显示静态图片',
- icon: 'none'
- });
- }
- });
- },
- // 处理视频结束事件
- handleVideoEnded() {
- console.log('视频播放结束');
- this.videoPlaying = false;
-
- // 对于所有视频,都显示相应的按钮
- if (this.currentVideoIndex >= 1) {
- // 对于问题视频,显示"开始回答"按钮
- this.showStartRecordingButton = true;
- } else {
- // 对于介绍视频(第一个视频),显示"开始面试"按钮
- this.showAnswerButton = true;
- }
- },
-
- // 添加新方法:开始录制用户回答
- startRecordingAnswer() {
- console.log('开始录制用户回答');
- this.isRecording = true;
-
- // 显示录制中的提示
- // uni.showLoading({
- // title: '正在录制...',
- // mask: true
- // });
-
- // 根据平台选择不同的录制方法
- const systemInfo = uni.getSystemInfoSync();
- const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
-
- if (isMiniProgram) {
- // 小程序环境使用小程序的录制API
- this.startMiniProgramRecording();
- } else {
- // H5/App环境使用MediaRecorder API
- this.startBrowserRecording();
- }
-
- // 显示停止录制按钮
- this.showStopRecordingButton = true;
- },
- // 修改小程序环境下的录制方法
- startMiniProgramRecording() {
- if (!this.cameraContext) {
- this.cameraContext = uni.createCameraContext();
- }
-
- // 确保有录音权限
- uni.getSetting({
- success: (res) => {
- const hasRecordAuth = res.authSetting['scope.record'];
- const hasCameraAuth = res.authSetting['scope.camera'];
-
- if (!hasRecordAuth || !hasCameraAuth) {
- console.warn('缺少必要权限,请求权限');
- this.requestMiniProgramPermissions();
- return;
- }
-
- // 开始录像,确保同时录制音频
- const options = {
- timeout: 60000, // 最长录制60秒
- success: () => {
- console.log('小程序录像开始成功');
- },
- fail: (err) => {
- console.error('小程序录像开始失败:', err);
- uni.showToast({
- title: '录制失败,请检查相机权限',
- icon: 'none'
- });
- this.proceedToNextQuestion();
- },
- timeoutCallback: () => {
- // 录制超时自动停止时的回调
- console.log('录制超时自动停止');
- this.stopRecordingAnswer();
- }
- };
-
- this.recorder = this.cameraContext.startRecord(options);
- }
- });
- },
- // 添加新方法:请求小程序权限
- requestMiniProgramPermissions() {
- // 请求录音权限
- uni.authorize({
- scope: 'scope.record',
- success: () => {
- console.log('录音权限已获取');
-
- // 请求相机权限
- uni.authorize({
- scope: 'scope.camera',
- success: () => {
- console.log('相机权限已获取');
- // 权限都获取到后,开始录制
- this.startMiniProgramRecording();
- },
- fail: (err) => {
- console.error('相机权限获取失败:', err);
- this.showPermissionDialog('相机');
- }
- });
- },
- fail: (err) => {
- console.error('录音权限获取失败:', err);
- this.showPermissionDialog('录音');
- }
- });
- },
- // 修改浏览器环境下的录制方法
- startBrowserRecording() {
- if (!this.cameraStream) {
- console.error('没有可用的摄像头流');
- uni.showToast({
- title: '录制失败,摄像头未就绪',
- icon: 'none'
- });
- this.proceedToNextQuestion();
- return;
- }
-
- try {
- // 检查流中是否包含音频轨道
- const hasAudio = this.cameraStream.getAudioTracks().length > 0;
- if (!hasAudio) {
- console.warn('警告:媒体流中没有音频轨道,尝试重新获取带音频的媒体流');
-
- // 尝试重新获取带音频的媒体流
- navigator.mediaDevices.getUserMedia({
- audio: {
- echoCancellation: true,
- noiseSuppression: true,
- autoGainControl: true
- },
- video: true
- })
- .then(newStream => {
- // 检查新流是否包含音频轨道
- const audioTracks = newStream.getAudioTracks();
- if (audioTracks.length > 0) {
- console.log('成功获取音频轨道:', audioTracks[0].label);
-
- // 合并视频和音频轨道
- const videoTrack = this.cameraStream.getVideoTracks()[0];
- const audioTrack = newStream.getAudioTracks()[0];
-
- // 创建新的媒体流,包含视频和音频轨道
- const combinedStream = new MediaStream();
- if (videoTrack) combinedStream.addTrack(videoTrack);
- if (audioTrack) combinedStream.addTrack(audioTrack);
-
- this.cameraStream = combinedStream;
-
- // 更新视频元素的源
- const videoElement = this.$refs.userCameraVideo;
- if (videoElement) {
- videoElement.srcObject = combinedStream;
- videoElement.muted = true; // 避免回声,但仍然录制声音
- }
-
- // 继续录制过程
- this.setupMediaRecorder(combinedStream);
- } else {
- console.warn('仍然无法获取音频轨道');
- // 使用现有流继续
- this.setupMediaRecorder(this.cameraStream);
- }
- })
- .catch(err => {
- console.error('获取音频失败:', err);
- // 使用现有流继续
- this.setupMediaRecorder(this.cameraStream);
- });
- } else {
- console.log('检测到音频轨道,直接使用');
- // 已有音频轨道,直接使用
- this.setupMediaRecorder(this.cameraStream);
- }
- } catch (error) {
- console.error('浏览器录制失败:', error);
- uni.showToast({
- title: '录制失败,浏览器可能不支持此功能',
- icon: 'none'
- });
- this.proceedToNextQuestion();
- }
- },
- // 修改 setupMediaRecorder 方法
- setupMediaRecorder(stream) {
- // 检查流中的轨道
- const videoTracks = stream.getVideoTracks();
- const audioTracks = stream.getAudioTracks();
-
- console.log('设置MediaRecorder - 视频轨道:', videoTracks.length, '音频轨道:', audioTracks.length);
-
- // 尝试使用支持度更广的编码格式
- let mimeType = '';
- const supportedTypes = [
- 'video/webm;codecs=vp9,opus',
- 'video/webm;codecs=vp8,opus',
- 'video/webm;codecs=h264,opus',
- 'video/mp4;codecs=h264,aac',
- 'video/webm',
- 'video/mp4'
- ];
-
- for (const type of supportedTypes) {
- if (MediaRecorder.isTypeSupported(type)) {
- mimeType = type;
- console.log('使用支持的MIME类型:', mimeType);
- break;
- }
- }
-
- // 创建MediaRecorder实例,设置较高的音频比特率
- const options = {
- mimeType: mimeType || '',
- audioBitsPerSecond: 128000,
- videoBitsPerSecond: 2500000
- };
-
- try {
- this.mediaRecorder = new MediaRecorder(stream, options);
- console.log('MediaRecorder创建成功,使用选项:', options);
- } catch (e) {
- console.warn('使用指定选项创建MediaRecorder失败,尝试使用默认选项');
- this.mediaRecorder = new MediaRecorder(stream);
- }
-
- // 存储录制的数据块
- this.recordedChunks = [];
-
- // 监听数据可用事件
- this.mediaRecorder.ondataavailable = (event) => {
- if (event.data && event.data.size > 0) {
- this.recordedChunks.push(event.data);
- console.log(`收到数据块: ${event.data.size} 字节`);
- }
- };
-
- // 监听录制停止事件
- this.mediaRecorder.onstop = () => {
- console.log('MediaRecorder停止,数据块数量:', this.recordedChunks.length);
-
- if (this.recordedChunks.length === 0) {
- console.error('没有录制到数据');
- uni.showToast({
- title: '录制失败,未捕获到数据',
- icon: 'none'
- });
- this.proceedToNextQuestion();
- return;
- }
-
- // 创建Blob对象
- const mimeType = this.mediaRecorder.mimeType || 'video/webm';
- const blob = new Blob(this.recordedChunks, { type: mimeType });
- console.log('创建Blob,大小:', blob.size, '类型:', mimeType);
-
- // 将Blob转换为File对象
- const fileName = `answer_${this.currentVideoIndex}_${Date.now()}.webm`;
- const file = new File([blob], fileName, { type: mimeType });
-
- // 上传文件
- this.uploadRecordedVideo(file);
- };
-
- // 监听错误
- this.mediaRecorder.onerror = (event) => {
- console.error('MediaRecorder错误:', event.error);
- };
-
- // 开始录制
- try {
- this.mediaRecorder.start(1000); // 每秒触发一次dataavailable事件
- console.log('MediaRecorder开始录制');
- } catch (e) {
- console.error('开始录制失败:', e);
- }
- },
- // 添加新方法:停止录制用户回答
- stopRecordingAnswer() {
- console.log('停止录制用户回答');
- this.isRecording = false;
-
- // 清除定时器
- if (this.recordingTimer) {
- clearTimeout(this.recordingTimer);
- this.recordingTimer = null;
- }
-
- // 隐藏录制中提示
- uni.hideLoading();
-
- // 隐藏停止录制按钮
- this.showStopRecordingButton = false;
-
- // 根据平台选择不同的停止录制方法
- const systemInfo = uni.getSystemInfoSync();
- const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
-
- if (isMiniProgram) {
- // 小程序环境停止录制
- this.stopMiniProgramRecording();
- } else {
- // H5/App环境停止录制
- this.stopBrowserRecording();
- }
- },
- // 添加新方法:停止小程序录制
- stopMiniProgramRecording() {
- if (!this.cameraContext) {
- console.error('相机上下文不存在');
- this.proceedToNextQuestion();
- return;
- }
-
- this.cameraContext.stopRecord({
- success: (res) => {
- console.log('小程序录像停止成功:', res);
- // 获取临时文件路径
- const tempFilePath = res.tempVideoPath;
- // 上传视频
- this.uploadRecordedVideo(tempFilePath);
- },
- fail: (err) => {
- console.error('小程序录像停止失败:', err);
- uni.showToast({
- title: '录制失败',
- icon: 'none'
- });
- this.proceedToNextQuestion();
- }
- });
- },
- // 添加新方法:停止浏览器录制
- stopBrowserRecording() {
- if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
- this.mediaRecorder.stop();
- console.log('浏览器录制停止成功');
- } else {
- console.error('MediaRecorder不存在或已经停止');
- this.proceedToNextQuestion();
- }
- },
- // 修改上传录制的视频方法
- uploadRecordedVideo(fileOrPath) {
- console.log('准备上传视频:', typeof fileOrPath === 'string' ? fileOrPath : fileOrPath.name);
-
- // 显示上传中提示
- uni.showLoading({
- title: '正在上传...',
- mask: true
- });
-
- // 获取用户信息
- const userInfo = uni.getStorageSync('userInfo');
- const openid = userInfo ? (JSON.parse(userInfo).openid || '') : '';
- const tenant_id = uni.getStorageSync('tenant_id') || '1';
-
- // 根据当前视频索引映射到正确的问题ID
- let questionId;
- switch(this.currentVideoIndex) {
- case 1: // 第一个问题
- questionId = 10;
- break;
- case 2: // 第二个问题
- questionId = 11;
- break;
- case 3: // 第三个问题
- questionId = 12;
- break;
- case 4: // 第四个问题
- questionId = 13;
- break;
- default:
- questionId = 10; // 默认值
- }
-
- // 检查是否在浏览器环境中使用File对象
- if (typeof fileOrPath !== 'string') {
- // 在浏览器环境中,我们需要将File对象转换为FormData
- const formData = new FormData();
- formData.append('file', fileOrPath);
- formData.append('openid', openid);
- formData.append('tenant_id', tenant_id);
- formData.append('application_id', 1);
- formData.append('question_id', questionId);
- formData.append('video_duration', 0);
- formData.append('has_audio', 'true'); // 明确标记视频包含音频
-
- // 使用XMLHttpRequest直接上传
- const xhr = new XMLHttpRequest();
- xhr.open('POST', `${apiBaseUrl}/api/system/upload/`, true);
-
- xhr.onload = () => {
- uni.hideLoading();
- if (xhr.status === 200) {
- try {
- const res = JSON.parse(xhr.responseText);
- console.log('上传响应:', res);
- if (res.code === 2000) {
- // 获取上传后的视频URL
- const videoUrl = res.data.url || res.data.photoUrl || '';
- if (videoUrl) {
- // 提交到面试接口
- this.submitVideoToInterview(videoUrl);
- } else {
- uni.showToast({
- title: '视频URL获取失败',
- icon: 'none'
- });
- }
- } else {
- uni.showToast({
- title: res.msg || '上传失败,请重试',
- icon: 'none'
- });
- }
- } catch (e) {
- console.error('解析响应失败:', e);
- uni.showToast({
- title: '解析响应失败',
- icon: 'none'
- });
- }
- } else {
- uni.showToast({
- title: '上传失败,HTTP状态: ' + xhr.status,
- icon: 'none'
- });
- }
- };
-
- xhr.onerror = () => {
- uni.hideLoading();
- console.error('上传网络错误');
- uni.showToast({
- title: '网络错误,请重试',
- icon: 'none'
- });
- };
-
- xhr.upload.onprogress = (event) => {
- if (event.lengthComputable) {
- const percentComplete = Math.round((event.loaded / event.total) * 100);
- console.log('上传进度:', percentComplete + '%');
- }
- };
-
- xhr.send(formData);
- return;
- }
-
- // 对于小程序环境,使用uni.uploadFile
- uni.uploadFile({
- url: `${apiBaseUrl}/api/system/upload/`,
- filePath: fileOrPath,
- name: 'file',
- formData: {
- openid: openid,
- tenant_id: tenant_id,
- application_id: 1,
- question_id: questionId,
- video_duration: 0,
- has_audio: 'true' // 明确标记视频包含音频
- },
- success: (uploadRes) => {
- try {
- const res = JSON.parse(uploadRes.data);
- console.log('上传响应:', res);
- if (res.code === 2000) {
- // 获取上传后的视频URL
- const videoUrl = res.data.permanent_link || res.data.url || '';
- if (videoUrl) {
- // 提交到面试接口
- this.submitVideoToInterview(videoUrl);
- } else {
- uni.showToast({
- title: '视频URL获取失败',
- icon: 'none'
- });
- }
- } else {
- uni.showToast({
- title: res.msg || '上传失败,请重试',
- icon: 'none'
- });
- }
- } catch (e) {
- console.error('解析响应失败:', e);
- uni.showToast({
- title: '解析响应失败',
- icon: 'none'
- });
- }
- },
- fail: (err) => {
- console.error('上传失败:', err);
- uni.showToast({
- title: '上传失败,请重试',
- icon: 'none'
- });
- },
- complete: () => {
- uni.hideLoading();
- }
- });
- },
- // 修改 submitVideoToInterview 方法
- submitVideoToInterview(videoUrl) {
- console.log('提交视频URL到面试接口:', videoUrl);
-
- // 显示加载提示
- uni.showLoading({
- title: '正在提交...',
- mask: true
- });
-
- // 根据当前视频索引映射到正确的问题ID
- let questionId;
- switch(this.currentVideoIndex) {
- case 1: // 第一个问题(索引1是第二个视频,第一个是介绍视频)
- questionId = 10;
- break;
- case 2: // 第二个问题
- questionId = 11;
- break;
- case 3: // 第三个问题
- questionId = 12;
- break;
- case 4: // 第四个问题
- questionId = 13;
- break;
- default:
- questionId = 10; // 默认值,以防万一
- }
-
- // 准备请求参数,使用映射后的问题ID
- const requestData = {
- application_id: 1,
- question_id: questionId,
- video_url: videoUrl,
- tenant_id: uni.getStorageSync('tenant_id') || '1'
- };
-
- // 发送请求到面试接口,使用form-data格式
- uni.request({
- url: `${apiBaseUrl}/api/job/upload_question_video`,
- method: 'POST',
- data: requestData, // 使用data而不是formData
- header: {
- 'content-type': 'application/x-www-form-urlencoded' // 修改为form-data格式的content-type
- },
- success: (res) => {
- console.log('面试接口提交成功:', res);
- uni.hideLoading();
-
- if (res.data.code === 0 || res.data.code === 2000) {
- // 提交成功
- uni.showToast({
- title: '回答已提交',
- icon: 'success'
- });
-
- // 保存最后上传的视频URL
- this.lastUploadedVideoUrl = videoUrl;
-
- // 隐藏重试按钮(如果之前显示了)
- this.showRetryButton = false;
- this.lastVideoToRetry = null;
-
- // 延迟一下再进入下一题,让用户看到成功提示
- setTimeout(() => {
- // 检查是否完成了第五个视频问题(索引为4)
- if (this.currentVideoIndex === 4) {
- // 完成第五个问题后,跳转到相机页面
- uni.navigateTo({
- url: '/pages/camera/camera'
- });
- } else {
- // 否则继续正常流程
- this.proceedToNextQuestion();
- }
- }, 1500);
- } else {
- // 提交失败
- uni.showToast({
- title: res.data.msg || '提交失败,请重试',
- icon: 'none'
- });
-
- // 保存失败的视频URL,用于重试
- this.lastVideoToRetry = videoUrl;
-
- // 显示重试按钮
- this.showRetryButton = true;
- }
- },
- fail: (err) => {
- console.error('面试接口提交失败:', err);
- uni.hideLoading();
- uni.showToast({
- title: '网络错误,请重试',
- icon: 'none'
- });
-
- // 保存失败的视频URL,用于重试
- this.lastVideoToRetry = videoUrl;
-
- // 显示重试按钮
- this.showRetryButton = true;
- }
- });
- },
- // 修改 proceedToNextQuestion 方法
- proceedToNextQuestion() {
- // 检查是否完成了第五个视频问题(索引为4)
- if (this.currentVideoIndex === 4) {
- // 完成第五个问题后,跳转到相机页面
- uni.navigateTo({
- url: '/pages/camera/camera'
- });
- return;
- }
-
- // 切换到下一个视频
- this.currentVideoIndex++;
- if (this.currentVideoIndex < this.videoList.length) {
- // 还有下一段视频,播放它
- this.videoUrl = this.videoList[this.currentVideoIndex];
- this.videoPlaying = true;
-
- // 重置当前字幕
- this.currentSubtitle = '';
-
- // 使用 nextTick 确保 DOM 更新后再播放视频
- this.$nextTick(() => {
- const videoContext = uni.createVideoContext('myVideo', this);
- if (videoContext) {
- videoContext.play();
- }
- });
- } else {
- // 所有视频都播放完毕,可以进行下一步操作
- uni.showToast({
- title: '面试完成',
- icon: 'success',
- duration: 2000
- });
-
- // 可以在这里添加面试完成后的逻辑,比如跳转到下一个页面
- setTimeout(() => {
- uni.navigateTo({
- url: '/pages/interview-result/interview-result'
- });
- }, 2000);
- }
- },
- // 修改 handleAnswerButtonClick 方法
- handleAnswerButtonClick() {
- // 隐藏答题按钮
- this.showAnswerButton = false;
-
- // 直接进入下一个问题
- this.proceedToNextQuestion();
- },
- // 处理相机错误
- handleCameraError(e) {
- console.error('相机错误:', e);
-
- // 显示错误提示
- uni.showToast({
- title: '相机初始化失败,请检查权限设置',
- icon: 'none'
- });
-
- // 尝试备用选项
- this.tryFallbackOptions();
- },
- // 添加新方法:尝试备用选项
- tryFallbackOptions() {
- // 检查环境
- const systemInfo = uni.getSystemInfoSync();
-
- // 在小程序环境中使用小程序API
- if (systemInfo.uniPlatform === 'mp-weixin' || systemInfo.uniPlatform === 'mp-alipay') {
- this.useMiniProgramCamera();
- }
- // 在H5环境中显示静态图像
- else {
- this.showStaticCameraPlaceholder();
- }
- },
- // 添加新方法:使用小程序相机API
- useMiniProgramCamera() {
- console.log('尝试使用小程序相机组件');
- // 这里需要在模板中添加小程序相机组件
- // 并设置一个标志来控制显示
- this.useMiniProgramCameraComponent = true;
- },
- // 添加新方法:显示静态图像
- showStaticCameraPlaceholder() {
- console.log('显示静态摄像头占位图');
- // 创建一个图像元素
- const img = document.createElement('img');
- img.src = '/static/images/camera-placeholder.png'; // 确保有这个图片资源
- img.className = 'static-camera-image';
- img.style.width = '100%';
- img.style.height = '100%';
- img.style.objectFit = 'cover';
-
- // 获取容器并添加图像
- const container = this.$refs.userCameraVideo.parentNode;
- container.appendChild(img);
- },
- // 处理视频时间更新事件
- handleTimeUpdate(e) {
- // 获取当前视频播放时间
- const currentTime = e.target.currentTime;
-
- // 根据当前播放的视频索引选择对应的字幕数组
- let currentSubtitles;
- if (this.currentVideoIndex === 0) {
- currentSubtitles = this.subtitles;
- } else if (this.currentVideoIndex === 1) {
- currentSubtitles = this.secondVideoSubtitles;
- }else if (this.currentVideoIndex === 2) {
- currentSubtitles = this.thirdVideoSubtitles;
- }else if (this.currentVideoIndex === 3) {
- currentSubtitles = this.fourthVideoSubtitles;
- }else if (this.currentVideoIndex === 4) {
- currentSubtitles = this.fifthVideoSubtitles;
- }else if (this.currentVideoIndex === 5) {
- currentSubtitles = this.sixthVideoSubtitles;
- }else {
- // 如果有更多视频,可以继续添加条件
- currentSubtitles = [];
- }
-
- // 查找当前时间应该显示的字幕
- const subtitle = currentSubtitles.find(
- sub => currentTime >= sub.startTime && currentTime < sub.endTime
- );
-
- // 更新当前字幕
- this.currentSubtitle = subtitle ? subtitle.text : '';
- },
- // Add a new method to handle the "Start Recording" button click
- handleStartRecordingClick() {
- // 隐藏"开始回答"按钮
- this.showStartRecordingButton = false;
-
- // 开始录制
- this.startRecordingAnswer();
- },
- // 修改 checkAudioPermission 方法,确保在录制前获取音频权限
- checkAudioPermission() {
- // 在小程序环境中
- const systemInfo = uni.getSystemInfoSync();
- const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
-
- if (isMiniProgram) {
- // 小程序环境下的权限请求
- uni.getSetting({
- success: (res) => {
- if (!res.authSetting['scope.record']) {
- uni.authorize({
- scope: 'scope.record',
- success: () => {
- console.log('录音权限已获取');
- },
- fail: (err) => {
- console.error('录音权限获取失败:', err);
- this.showPermissionDialog('录音');
- }
- });
- }
-
- if (!res.authSetting['scope.camera']) {
- uni.authorize({
- scope: 'scope.camera',
- success: () => {
- console.log('相机权限已获取');
- },
- fail: (err) => {
- console.error('相机权限获取失败:', err);
- this.showPermissionDialog('相机');
- }
- });
- }
- }
- });
- } else {
- // 浏览器环境下的权限请求
- // ... 保持原有代码不变
- }
- },
- // 添加新方法:测试音频输入
- testAudioInput() {
- if (!this.cameraStream) {
- console.warn('没有可用的媒体流,无法测试音频');
- return;
- }
-
- const audioTracks = this.cameraStream.getAudioTracks();
- if (audioTracks.length === 0) {
- console.warn('没有检测到音频轨道,尝试重新获取');
- this.tryGetAudioOnly();
- return;
- }
-
- console.log('音频轨道信息:', audioTracks[0].getSettings());
-
- // 创建音频上下文和分析器
- try {
- const AudioContext = window.AudioContext || window.webkitAudioContext;
- if (!AudioContext) {
- console.warn('浏览器不支持AudioContext');
- return;
- }
-
- const audioContext = new AudioContext();
- const analyser = audioContext.createAnalyser();
- const microphone = audioContext.createMediaStreamSource(this.cameraStream);
- microphone.connect(analyser);
-
- // 设置分析器
- analyser.fftSize = 256;
- const bufferLength = analyser.frequencyBinCount;
- const dataArray = new Uint8Array(bufferLength);
-
- // 检测音频输入
- let silenceCounter = 0;
- const checkAudio = () => {
- if (this.isRecording) return; // 如果正在录制,停止检测
-
- analyser.getByteFrequencyData(dataArray);
-
- // 计算平均音量
- let sum = 0;
- for (let i = 0; i < bufferLength; i++) {
- sum += dataArray[i];
- }
- const average = sum / bufferLength;
-
- if (average > 10) {
- console.log('检测到音频输入,音量:', average);
- silenceCounter = 0;
- } else {
- silenceCounter++;
- if (silenceCounter > 10) {
- console.warn('持续检测不到音频输入,可能麦克风未正常工作');
- silenceCounter = 0;
- }
- }
-
- // 继续检测
- requestAnimationFrame(checkAudio);
- };
-
- // 开始检测
- checkAudio();
- } catch (e) {
- console.error('音频测试失败:', e);
- }
- },
- // 添加新方法:尝试单独获取音频
- tryGetAudioOnly() {
- navigator.mediaDevices.getUserMedia({ audio: true })
- .then(audioStream => {
- // 如果已有视频流,合并音频和视频轨道
- if (this.cameraStream) {
- const videoTrack = this.cameraStream.getVideoTracks()[0];
- const audioTrack = audioStream.getAudioTracks()[0];
-
- // 创建新的媒体流,包含视频和音频轨道
- const combinedStream = new MediaStream();
- if (videoTrack) combinedStream.addTrack(videoTrack);
- if (audioTrack) combinedStream.addTrack(audioTrack);
-
- // 更新摄像头流
- this.cameraStream = combinedStream;
-
- // 更新视频元素的源
- const videoElement = this.$refs.userCameraVideo;
- if (videoElement) {
- videoElement.srcObject = combinedStream;
- videoElement.muted = true; // 避免回声,但仍然录制声音
- }
-
- console.log('成功合并音频和视频轨道');
- } else {
- console.warn('没有视频流可合并');
- }
- })
- .catch(err => {
- console.error('单独获取音频失败:', err);
- });
- },
- // 添加新方法:显示权限对话框
- showPermissionDialog(permissionType) {
- uni.showModal({
- title: '需要权限',
- content: `请允许使用${permissionType}权限,否则可能影响面试功能`,
- confirmText: '去设置',
- success: (res) => {
- if (res.confirm) {
- uni.openSetting({
- success: (settingRes) => {
- console.log('设置页面打开成功', settingRes);
- }
- });
- }
- }
- });
- },
- // 添加重试上传方法
- retryVideoUpload() {
- if (this.lastVideoToRetry) {
- // 隐藏重试按钮
- this.showRetryButton = false;
-
- // 显示加载提示
- uni.showLoading({
- title: '正在重新提交...',
- mask: true
- });
-
- // 重新提交视频
- this.submitVideoToInterview(this.lastVideoToRetry);
- } else {
- uni.showToast({
- title: '没有可重试的视频',
- icon: 'none'
- });
- }
- }
- }
- }
- </script>
- <style scoped>
- .identity-verify-container {
- padding: 0;
- max-width: 100%;
- margin: 0 auto;
- height: 100vh;
- display: flex;
- flex-direction: column;
- background-color: #f5f5f5;
- }
- .digital-human-container {
- position: relative;
- width: 100%;
- height: 100vh;
- overflow: hidden;
- background-color: #f0f0f0;
- }
- .digital-human-video {
- width: 100%;
- height: 100%;
- display: flex;
- justify-content: center;
- align-items: center;
- }
- /* 用户摄像头容器样式 */
- .user-camera-container {
- position: absolute;
- top: 20px;
- right: 20px;
- width: 100px;
- height: 150px;
- border-radius: 8px;
- overflow: hidden;
- box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
- z-index: 20;
- border: 1px solid #fff;
- }
- /* 用户摄像头视频样式 */
- .user-camera-video {
- width: 100%;
- height: 100%;
- object-fit: cover;
- background-color: #333;
- }
- .video-player {
- width: 100%;
- height: 100%;
- object-fit: cover;
- outline: none; /* 移除视频获得焦点时的轮廓 */
- -webkit-tap-highlight-color: transparent; /* 移除移动设备上的点击高亮 */
- }
- /* 隐藏视频控制条 */
- video::-webkit-media-controls {
- display: none !important;
- }
- video::-webkit-media-controls-enclosure {
- display: none !important;
- }
- video::-webkit-media-controls-panel {
- display: none !important;
- }
- video::-webkit-media-controls-play-button {
- display: none !important;
- }
- video::-webkit-media-controls-timeline {
- display: none !important;
- }
- video::-webkit-media-controls-current-time-display {
- display: none !important;
- }
- video::-webkit-media-controls-time-remaining-display {
- display: none !important;
- }
- video::-webkit-media-controls-mute-button {
- display: none !important;
- }
- video::-webkit-media-controls-volume-slider {
- display: none !important;
- }
- video::-webkit-media-controls-fullscreen-button {
- display: none !important;
- }
- .subtitle-overlay {
- position: absolute;
- bottom: 50px;
- left: 0;
- width: 100%;
- padding: 15px;
- background-color: rgba(0, 0, 0, 0.7);
- color: white;
- text-align: center;
- font-size: 16px;
- line-height: 1.5;
- z-index: 10;
- border-radius: 4px;
- max-width: 90%;
- margin: 0 auto;
- left: 5%;
- right: 5%;
- }
- .control-panel {
- padding: 15px;
- display: flex;
- justify-content: center;
- }
- .control-button {
- padding: 10px 20px;
- background-color: #4CAF50;
- color: white;
- border: none;
- border-radius: 4px;
- cursor: pointer;
- }
- .loading {
- text-align: center;
- margin: 20px 0;
- font-size: 16px;
- }
- .response-container {
- margin-top: 20px;
- padding: 0 20px;
- display: none; /* 默认隐藏调试信息 */
- }
- /* 当showDebugInfo为true时显示 */
- .showDebugInfo .response-container {
- display: block;
- }
- .response-item {
- padding: 10px;
- border: 1px solid #eee;
- border-radius: 4px;
- margin-bottom: 10px;
- background-color: #f9f9f9;
- }
- .response-content {
- display: flex;
- flex-direction: column;
- }
- .answer-button-container {
- position: absolute;
- top: 75%;
- left: 50%;
- transform: translate(-50%, -50%);
- z-index: 20;
- }
- .answer-button {
- width: 120px;
- height: 120px;
- border-radius: 50%;
- background-color: #6c5ce7; /* 绿色背景,与图片中的颜色类似 */
- color: white;
- font-size: 18px;
- border: none;
- box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
- display: flex;
- justify-content: center;
- align-items: center;
- cursor: pointer;
- animation: pulse 2s infinite;
- }
- @keyframes pulse {
- 0% {
- transform: scale(1);
- box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
- }
- 50% {
- transform: scale(1.05);
- box-shadow: 0 8px 15px rgba(0, 0, 0, 0.4);
- }
- 100% {
- transform: scale(1);
- box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
- }
- }
- .stop-recording-button-container {
- position: absolute;
- top: 75%;
- left: 50%;
- transform: translate(-50%, -50%);
- z-index: 20;
- }
- .stop-recording-button {
- width: 120px;
- height: 120px;
- border-radius: 50%;
- background-color: #e74c3c; /* 红色背景 */
- color: white;
- font-size: 18px;
- border: none;
- box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
- display: flex;
- justify-content: center;
- align-items: center;
- cursor: pointer;
- animation: pulse 2s infinite;
- }
- @keyframes pulse {
- 0% {
- transform: scale(1);
- box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
- }
- 50% {
- transform: scale(1.05);
- box-shadow: 0 8px 15px rgba(0, 0, 0, 0.4);
- }
- 100% {
- transform: scale(1);
- box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
- }
- }
- /* 录制中的指示器 */
- .recording-indicator {
- position: absolute;
- top: 20px;
- left: 20px;
- display: flex;
- align-items: center;
- background-color: rgba(0, 0, 0, 0.6);
- padding: 5px 10px;
- border-radius: 15px;
- z-index: 20;
- }
- .recording-dot {
- width: 12px;
- height: 12px;
- background-color: #e74c3c;
- border-radius: 50%;
- margin-right: 8px;
- animation: blink 1s infinite;
- }
- .recording-text {
- color: white;
- font-size: 14px;
- }
- @keyframes blink {
- 0% { opacity: 1; }
- 50% { opacity: 0.3; }
- 100% { opacity: 1; }
- }
- .start-recording-button-container {
- position: absolute;
- top: 75%;
- left: 50%;
- transform: translate(-50%, -50%);
- z-index: 20;
- }
- .start-recording-button {
- width: 120px;
- height: 120px;
- border-radius: 50%;
- background-color: #6c5ce7; /* 与开始面试按钮颜色保持一致 */
- color: white;
- font-size: 18px;
- border: none;
- box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
- display: flex;
- justify-content: center;
- align-items: center;
- cursor: pointer;
- animation: pulse 2s infinite; /* 使用相同的动画 */
- }
- /* 可以删除pulse-green动画,直接使用与开始面试按钮相同的pulse动画 */
- .retry-button-container {
- position: absolute;
- bottom: 50px;
- left: 50%;
- transform: translateX(-50%);
- z-index: 20;
- }
- .retry-button {
- padding: 10px 20px;
- background-color: #3498db; /* 蓝色背景 */
- color: white;
- font-size: 16px;
- border: none;
- border-radius: 4px;
- box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
- cursor: pointer;
- }
- .retry-button:hover {
- background-color: #2980b9;
- }
- </style>
|