identity-verify.vue 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021
  1. <template>
  2. <div class="identity-verify-container">
  3. <div class="digital-human-container">
  4. <!-- AI数字人视频/图像显示区域 -->
  5. <div class="digital-human-video">
  6. <!-- <image v-if="!videoPlaying" src="/static/images/digital-human-placeholder.jpg" mode="aspectFit"></image> -->
  7. <video
  8. :src="videoUrl"
  9. id="myVideo"
  10. ref="videoPlayer"
  11. autoplay
  12. playsinline
  13. disablePictureInPicture
  14. controlsList="nodownload nofullscreen noremoteplayback"
  15. class="video-player"
  16. :controls="false"
  17. @error="handleVideoError"
  18. @ended="handleVideoEnded"
  19. @timeupdate="handleTimeUpdate">
  20. </video>
  21. <!-- 添加字幕覆盖层 -->
  22. <div class="subtitle-overlay" v-if="currentSubtitle">
  23. {{ currentSubtitle }}
  24. </div>
  25. <!-- 添加答题按钮 -->
  26. <div class="answer-button-container" v-if="showAnswerButton">
  27. <button class="answer-button" @click="handleAnswerButtonClick">
  28. 开始面试
  29. </button>
  30. </div>
  31. </div>
  32. <!-- 用户摄像头视频显示区域 -->
  33. <div class="user-camera-container">
  34. <!-- 在小程序环境中使用camera组件 -->
  35. <camera v-if="useMiniProgramCameraComponent"
  36. device-position="front"
  37. flash="off"
  38. class="user-camera-video"
  39. @error="handleCameraError"
  40. :record-audio="true">
  41. </camera>
  42. <!-- 在H5/App环境中使用video元素 -->
  43. <video v-else
  44. id="userCamera"
  45. ref="userCameraVideo"
  46. autoplay
  47. playsinline
  48. muted
  49. class="user-camera-video"
  50. :controls="false">
  51. </video>
  52. </div>
  53. <!-- 字幕/文本覆盖区域 -->
  54. <!-- <div class="subtitle-overlay" v-if="assistantResponse">
  55. {{ assistantResponse }}
  56. </div> -->
  57. </div>
  58. <!-- 加载状态 -->
  59. <div v-if="loading" class="loading">加载中...</div>
  60. <!-- 控制面板(可选,可以隐藏) -->
  61. <!-- 响应数据(可以设为隐藏,仅用于调试) -->
  62. <div v-if="showDebugInfo" class="response-container">
  63. <div v-if="assistantResponse" class="response-item">
  64. <div class="response-content">
  65. <span>助手回复: {{ assistantResponse }}</span>
  66. </div>
  67. </div>
  68. <div v-if="audioTranscript" class="response-item">
  69. <div class="response-content">
  70. <span>音频转写: {{ audioTranscript }}</span>
  71. </div>
  72. </div>
  73. <div v-for="(item, index) in processedResponses" :key="index" class="response-item">
  74. <div class="response-content">
  75. <span v-if="item.role">角色: {{ item.role }}</span>
  76. <span v-if="item.transcript">文本: {{ item.transcript }}</span>
  77. </div>
  78. </div>
  79. </div>
  80. <!-- 添加停止录制按钮 -->
  81. <div class="stop-recording-button-container" v-if="showStopRecordingButton">
  82. <button class="stop-recording-button" @click="stopRecordingAnswer">
  83. 完成作答
  84. </button>
  85. </div>
  86. <!-- 添加录制指示器 -->
  87. <div class="recording-indicator" v-if="isRecording">
  88. <div class="recording-dot"></div>
  89. <span class="recording-text">正在录制...</span>
  90. </div>
  91. <!-- 添加开始回答按钮 -->
  92. <div class="start-recording-button-container" v-if="showStartRecordingButton">
  93. <button class="start-recording-button" @click="handleStartRecordingClick">
  94. 开始作答
  95. </button>
  96. </div>
  97. <!-- 添加重试上传按钮 -->
  98. <div class="retry-button-container" v-if="showRetryButton">
  99. <button class="retry-button" @click="retryVideoUpload">
  100. 重新上传
  101. </button>
  102. </div>
  103. </div>
  104. </template>
  105. <script>
  106. import { apiBaseUrl } from '@/common/config.js';
  107. export default {
  108. name: 'IdentityVerify',
  109. data() {
  110. return {
  111. loading: false,
  112. responses: [],
  113. processedResponses: [],
  114. assistantResponse: '',
  115. audioTranscript: '',
  116. videoPlaying: false,
  117. showDebugInfo: false, // 设置为true可以显示调试信息
  118. videoUrl: 'http://121.36.251.245:9000/minlong/9c139c99-a613-49f2-986b-8a3ac20a9b1b.mp4', // 用于存储AI数字人视频URL
  119. showReplayButton: false,
  120. cameraStream: null, // 存储摄像头流
  121. cameraError: null, // 存储摄像头错误信息
  122. useMiniProgramCameraComponent: false, // 添加小程序相机组件标志
  123. cameraContext: null, // 添加相机上下文
  124. currentSubtitle: '',
  125. subtitles: [
  126. {
  127. startTime: 0, // 开始时间(秒)
  128. endTime: 5, // 结束时间(秒)
  129. text: '你好,我是本次面试的面试官,欢迎参加本公司的线上面试!'
  130. },
  131. {
  132. startTime: 5,
  133. endTime: 13,
  134. text: '面试预计需要15分钟,请你提前安排在网络良好、光线亮度合适、且相对安静的环境参加这次面试'
  135. },
  136. {
  137. startTime: 13,
  138. endTime: 20,
  139. text: '以免影响本次面试的结果。如果你在面试过程中遇到问题,请与我们的招聘人员联系。'
  140. }
  141. ],
  142. secondVideoSubtitles: [
  143. {
  144. startTime: 0,
  145. endTime: 10,
  146. text: '请结合您的基本信息与过往履历进行简单的自我介绍,并讲一讲您有哪些优势胜任本岗位:'
  147. }
  148. ],
  149. thirdVideoSubtitles: [
  150. {
  151. startTime: 0,
  152. endTime: 3,
  153. text: '在工作中,你如何确保个人防护装备的正确使用?'
  154. }
  155. ],
  156. fourthVideoSubtitles: [
  157. {
  158. startTime: 0,
  159. endTime: 3,
  160. text: '描述一次你与团队合作改善生产流程的经历。'
  161. }
  162. ],
  163. fifthVideoSubtitles: [
  164. {
  165. startTime: 0,
  166. endTime: 6,
  167. text: '你在团队合作中曾遇到过哪些挑战?如何解决团队内部的分歧?'
  168. }
  169. ],
  170. sixthVideoSubtitles: [
  171. {
  172. startTime: 0,
  173. endTime: 5,
  174. text: '您已完成本次面试全部题目,请问您对于这个岗位还有什么想要了解的吗?'
  175. }
  176. ],
  177. showAnswerButton: false, // 控制答题按钮显示
  178. currentVideoIndex: 0, // 当前播放的视频索引
  179. videoList: [
  180. 'http://121.36.251.245:9000/minlong/9c139c99-a613-49f2-986b-8a3ac20a9b1b.mp4', // 第一段视频
  181. 'http://121.36.251.245:9000/minlong/15467aca-2c1e-4d40-bebc-11fc984f0a24.mp4', // 第二段视频
  182. 'http://121.36.251.245:9000/minlong/a96f295c-ecba-4b08-b627-0ed0dc72d727.mp4', // 第三段视频
  183. 'http://121.36.251.245:9000/minlong/e152eb38-7e03-4bb0-8b8d-73d51342d2aa.mp4',
  184. 'http://121.36.251.245:9000/minlong/6381eec3-1373-400f-aa8c-e229b60522ea.mp4',
  185. 'http://121.36.251.245:9000/minlong/2a11fe78-38d5-4af3-91c8-a080feb122e0.mp4'//结束
  186. ],
  187. isRecording: false,
  188. recordingTimer: null,
  189. showStopRecordingButton: false,
  190. mediaRecorder: null,
  191. recordedChunks: [],
  192. recorder: null,
  193. lastUploadedVideoUrl: '',
  194. showStartRecordingButton: false,
  195. showRetryButton: false, // 控制重试按钮显示
  196. lastVideoToRetry: null, // 存储上次失败的视频URL,用于重试
  197. }
  198. },
  199. mounted() {
  200. /* this.fetchData() */
  201. this.playDigitalHumanVideo();
  202. this.checkAudioPermission();
  203. this.initCamera();
  204. // 添加音频测试
  205. setTimeout(() => {
  206. if (this.cameraStream && !this.useMiniProgramCameraComponent) {
  207. this.testAudioInput();
  208. }
  209. }, 3000);
  210. },
  211. beforeDestroy() {
  212. // 组件销毁前停止摄像头
  213. this.stopUserCamera();
  214. },
  215. methods: {
  216. // 初始化相机
  217. async initCamera() {
  218. // 检查平台
  219. const systemInfo = uni.getSystemInfoSync();
  220. // 判断是否在小程序环境中
  221. const isMiniProgram = systemInfo.uniPlatform === 'mp-weixin' ||
  222. systemInfo.uniPlatform === 'mp-alipay' ||
  223. systemInfo.uniPlatform === 'mp-baidu';
  224. if (isMiniProgram) {
  225. // 小程序环境使用小程序的相机API
  226. this.useMiniProgramCameraComponent = true;
  227. // 创建相机上下文
  228. this.cameraContext = uni.createCameraContext();
  229. // 确保已获取录音权限
  230. uni.getSetting({
  231. success: (res) => {
  232. if (!res.authSetting['scope.record']) {
  233. uni.authorize({
  234. scope: 'scope.record',
  235. success: () => {
  236. console.log('录音权限已获取');
  237. },
  238. fail: (err) => {
  239. console.error('录音权限获取失败:', err);
  240. this.showPermissionDialog('录音');
  241. }
  242. });
  243. }
  244. if (!res.authSetting['scope.camera']) {
  245. uni.authorize({
  246. scope: 'scope.camera',
  247. success: () => {
  248. console.log('相机权限已获取');
  249. },
  250. fail: (err) => {
  251. console.error('相机权限获取失败:', err);
  252. this.showPermissionDialog('相机');
  253. }
  254. });
  255. }
  256. }
  257. });
  258. } else {
  259. // H5/App环境使用浏览器的API
  260. try {
  261. // 请求摄像头和麦克风权限并获取媒体流
  262. const constraints = {
  263. audio: {
  264. echoCancellation: true,
  265. noiseSuppression: true,
  266. autoGainControl: true
  267. },
  268. video: {
  269. width: { ideal: 640 },
  270. height: { ideal: 480 },
  271. facingMode: 'user'
  272. }
  273. };
  274. const stream = await navigator.mediaDevices.getUserMedia(constraints);
  275. // 保存流以便后续使用
  276. this.cameraStream = stream;
  277. // 检查音频轨道
  278. const audioTracks = stream.getAudioTracks();
  279. console.log('音频轨道数量:', audioTracks.length);
  280. if (audioTracks.length > 0) {
  281. console.log('音频轨道已获取:', audioTracks[0].label);
  282. // 确保音频轨道已启用
  283. audioTracks[0].enabled = true;
  284. } else {
  285. console.warn('未检测到音频轨道,尝试单独获取音频');
  286. this.tryGetAudioOnly();
  287. }
  288. // 将流设置到视频元素
  289. const videoElement = this.$refs.userCameraVideo;
  290. if (videoElement) {
  291. videoElement.srcObject = stream;
  292. videoElement.muted = true; // 避免回声,但仍然录制声音
  293. }
  294. } catch (error) {
  295. console.error('获取摄像头失败:', error);
  296. this.cameraError = error.message || '无法访问摄像头';
  297. // 显示错误提示
  298. uni.showToast({
  299. title: '无法访问摄像头,请检查权限设置',
  300. icon: 'none'
  301. });
  302. }
  303. }
  304. },
  305. // 停止用户摄像头
  306. stopUserCamera() {
  307. if (this.cameraStream) {
  308. // 停止所有轨道
  309. this.cameraStream.getTracks().forEach(track => {
  310. track.stop();
  311. });
  312. this.cameraStream = null;
  313. }
  314. },
  315. async fetchData() {
  316. this.loading = true
  317. this.assistantResponse = ''
  318. this.audioTranscript = ''
  319. this.processedResponses = []
  320. try {
  321. // 使用uni.request代替fetch
  322. const requestTask = uni.request({
  323. url: 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions',
  324. method: 'POST',
  325. header: {
  326. 'Content-Type': 'application/json',
  327. 'Authorization': 'Bearer sk-9e1ec73a7d97493b8613c63f06b6110c'
  328. },
  329. data: {
  330. "model": "qwen-omni-turbo",
  331. "messages": [
  332. {
  333. "role": "user",
  334. "content": [
  335. {
  336. "type": "input_audio",
  337. "input_audio": {
  338. "data": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250211/tixcef/cherry.wav",
  339. "format": "wav"
  340. }
  341. },
  342. {
  343. "type": "text",
  344. "text": "这段音频在说什么"
  345. }
  346. ]
  347. }
  348. ],
  349. "stream":true,
  350. "stream_options":{
  351. "include_usage":true
  352. },
  353. "modalities":["text","audio"],
  354. "audio":{"voice":"Cherry","format":"wav"}
  355. },
  356. success: (res) => {
  357. console.log('请求成功,响应数据:', res.data);
  358. // 检查响应数据是否包含多个JSON对象
  359. if (typeof res.data === 'string' && res.data.includes('data: {')) {
  360. // 处理包含多个JSON对象的情况
  361. const chunks = res.data.split('data: ').filter(chunk => chunk.trim() !== '');
  362. chunks.forEach(chunk => {
  363. this.handleStreamResponse(chunk);
  364. });
  365. } else {
  366. // 处理单个响应对象的情况
  367. this.handleStreamResponse(res.data);
  368. }
  369. // 模拟获取到数字人视频并播放
  370. this.playDigitalHumanVideo();
  371. },
  372. fail: (err) => {
  373. console.error('请求失败:', err);
  374. },
  375. complete: () => {
  376. this.loading = false;
  377. }
  378. });
  379. } catch (error) {
  380. console.error('获取数据失败:', error);
  381. this.loading = false;
  382. }
  383. },
  384. handleStreamResponse(data) {
  385. // 处理流式响应数据
  386. if (typeof data === 'string') {
  387. // 处理字符串格式的响应
  388. if (data === '[DONE]') return;
  389. try {
  390. // 移除可能存在的换行符和多余空格
  391. const cleanData = data.trim();
  392. // 检查是否是有效的JSON字符串
  393. if (cleanData.startsWith('{') && cleanData.endsWith('}')) {
  394. const jsonData = JSON.parse(cleanData);
  395. this.processStreamChunk(jsonData);
  396. }
  397. } catch (e) {
  398. console.error('解析JSON失败:', e, '原始数据:', data);
  399. }
  400. } else {
  401. // 处理对象格式的响应
  402. this.processStreamChunk(data);
  403. }
  404. },
  405. processStreamChunk(chunk) {
  406. if (chunk.choices && chunk.choices.length > 0) {
  407. const choice = chunk.choices[0];
  408. // 处理助手回复内容
  409. if (choice.delta && choice.delta.content) {
  410. this.assistantResponse += choice.delta.content;
  411. }
  412. // 处理音频转写内容
  413. if (choice.delta && choice.delta.audio && choice.delta.audio.transcript) {
  414. this.audioTranscript += choice.delta.audio.transcript;
  415. }
  416. // 处理角色和音频转写
  417. if (choice.delta) {
  418. const result = {};
  419. if (choice.delta.role) {
  420. result.role = choice.delta.role;
  421. }
  422. if (choice.delta.audio && choice.delta.audio.transcript) {
  423. result.transcript = choice.delta.audio.transcript;
  424. }
  425. if (Object.keys(result).length > 0) {
  426. this.processedResponses.push(result);
  427. }
  428. }
  429. }
  430. },
  431. processResponseData() {
  432. // 处理返回的数据
  433. this.processedResponses = this.responses.map(item => {
  434. const result = {}
  435. // 处理角色信息
  436. if (item.delta && item.delta.role) {
  437. result.role = item.delta.role
  438. }
  439. // 处理音频转写文本
  440. if (item.delta && item.delta.audio && item.delta.audio.transcript) {
  441. result.transcript = item.delta.audio.transcript
  442. }
  443. return result
  444. }).filter(item => Object.keys(item).length > 0)
  445. },
  446. // 播放数字人视频
  447. playDigitalHumanVideo() {
  448. // 设置第一个视频
  449. this.videoUrl = this.videoList[this.currentVideoIndex];
  450. this.videoPlaying = true;
  451. // 使用 uni.createVideoContext 来控制视频
  452. this.$nextTick(() => {
  453. const videoContext = uni.createVideoContext('myVideo', this);
  454. if (videoContext) {
  455. videoContext.play();
  456. // 设置超时检查,确认视频是否真的在播放
  457. setTimeout(() => {
  458. if (this.videoPlaying && this.$refs.videoPlayer) {
  459. console.log('视频应该正在播放');
  460. } else {
  461. console.log('视频可能未成功播放,尝试替代方案');
  462. this.tryAlternativeVideoPath();
  463. }
  464. }, 1000);
  465. } else {
  466. console.error('无法创建视频上下文');
  467. this.tryAlternativeVideoPath();
  468. }
  469. });
  470. },
  471. // 修改 tryAlternativeVideoPath 方法
  472. tryAlternativeVideoPath() {
  473. console.log('尝试使用替代路径');
  474. // 尝试不同的路径格式
  475. const alternativePaths = [
  476. './static/demo.mp4',
  477. '../static/demo.mp4',
  478. 'static/demo.mp4',
  479. '/static/demo.mp4',
  480. // 添加绝对路径
  481. `${window.location.origin}/static/demo.mp4`
  482. ];
  483. // 获取当前路径索引
  484. const currentPathIndex = alternativePaths.indexOf(this.videoUrl);
  485. const nextPathIndex = (currentPathIndex + 1) % alternativePaths.length;
  486. // 设置下一个路径
  487. this.videoUrl = alternativePaths[nextPathIndex];
  488. console.log('尝试新路径:', this.videoUrl);
  489. this.$nextTick(() => {
  490. const videoContext = uni.createVideoContext('myVideo', this);
  491. if (videoContext) {
  492. videoContext.stop();
  493. videoContext.play();
  494. // 检查是否成功播放
  495. setTimeout(() => {
  496. if (nextPathIndex === alternativePaths.length - 1 && !this.videoPlaying) {
  497. console.log('所有路径均失败,尝试使用uni.getVideoInfo检查视频');
  498. this.checkVideoWithAPI();
  499. }
  500. }, 1000);
  501. }
  502. });
  503. },
  504. // 添加新方法:使用uni API检查视频
  505. checkVideoWithAPI() {
  506. // 尝试使用uni.getVideoInfo API检查视频是否可用
  507. uni.getVideoInfo({
  508. src: '/static/demo.mp4',
  509. success: (res) => {
  510. console.log('视频信息获取成功:', res);
  511. // 如果能获取到视频信息,再次尝试播放
  512. this.videoUrl = '/static/demo.mp4';
  513. this.$nextTick(() => {
  514. const videoContext = uni.createVideoContext('myVideo', this);
  515. if (videoContext) {
  516. videoContext.play();
  517. }
  518. });
  519. },
  520. fail: (err) => {
  521. console.error('视频信息获取失败:', err);
  522. // 最后尝试使用uni.chooseVideo API
  523. this.fallbackToLocalVideo();
  524. }
  525. });
  526. },
  527. // 添加新方法:回退到本地视频
  528. fallbackToLocalVideo() {
  529. console.log('尝试使用本地视频资源');
  530. // 检查平台
  531. const platform = uni.getSystemInfoSync().platform;
  532. if (platform === 'android' || platform === 'ios') {
  533. // 移动端可以尝试使用本地资源
  534. this.videoUrl = platform === 'android' ? 'android.resource://package_name/raw/demo' : 'file:///assets/demo.mp4';
  535. this.$nextTick(() => {
  536. const videoContext = uni.createVideoContext('myVideo', this);
  537. if (videoContext) {
  538. videoContext.play();
  539. }
  540. });
  541. } else {
  542. // 最终回退到静态图片
  543. this.videoPlaying = false;
  544. uni.showToast({
  545. title: '视频加载失败,显示静态图片',
  546. icon: 'none'
  547. });
  548. }
  549. },
  550. // 修改 handleVideoError 方法
  551. handleVideoError(e) {
  552. console.error('视频加载错误:', e);
  553. // 记录更详细的错误信息
  554. if (e && e.detail) {
  555. console.error('详细错误信息:', e.detail);
  556. }
  557. // 检查视频文件是否存在
  558. uni.getFileInfo({
  559. filePath: this.videoUrl.startsWith('/') ? this.videoUrl.substring(1) : this.videoUrl,
  560. success: (res) => {
  561. console.log('文件存在,大小:', res.size);
  562. // 文件存在但播放失败,可能是格式问题
  563. this.tryDifferentFormat();
  564. },
  565. fail: (err) => {
  566. console.error('文件不存在或无法访问:', err);
  567. // 尝试不同路径
  568. this.tryAlternativeVideoPath();
  569. }
  570. });
  571. // 如果多次尝试后仍然失败,显示错误信息
  572. uni.showToast({
  573. title: '视频加载失败,请检查文件是否存在',
  574. icon: 'none',
  575. duration: 2000
  576. });
  577. },
  578. // 添加新方法:尝试不同格式
  579. tryDifferentFormat() {
  580. console.log('尝试不同的视频格式');
  581. // 尝试不同的视频格式
  582. const formats = [
  583. { ext: 'mp4', mime: 'video/mp4' },
  584. { ext: 'webm', mime: 'video/webm' },
  585. { ext: 'ogg', mime: 'video/ogg' },
  586. { ext: 'mov', mime: 'video/quicktime' }
  587. ];
  588. // 获取当前文件名(不含扩展名)
  589. const currentPath = this.videoUrl;
  590. const basePath = currentPath.substring(0, currentPath.lastIndexOf('.')) || '/static/demo';
  591. // 尝试下一个格式
  592. let nextFormat = formats.find(f => !currentPath.endsWith(f.ext));
  593. if (nextFormat) {
  594. this.videoUrl = `${basePath}.${nextFormat.ext}`;
  595. console.log('尝试新格式:', this.videoUrl);
  596. this.$nextTick(() => {
  597. const videoContext = uni.createVideoContext('myVideo', this);
  598. if (videoContext) {
  599. videoContext.stop();
  600. videoContext.play();
  601. }
  602. });
  603. } else {
  604. // 所有格式都尝试过了,使用内置资源
  605. this.useBuiltInResource();
  606. }
  607. },
  608. // 添加新方法:使用内置资源
  609. useBuiltInResource() {
  610. console.log('尝试使用内置资源');
  611. // 检查平台
  612. const platform = uni.getSystemInfoSync().platform;
  613. // 根据平台选择合适的视频源
  614. if (platform === 'windows') {
  615. // Windows平台特定处理
  616. // 尝试使用相对于应用根目录的路径
  617. const appRoot = process.env.UNI_INPUT_DIR || '';
  618. this.videoUrl = `./static/demo.mp4`;
  619. // 或者尝试使用file://协议
  620. // this.videoUrl = `file:///${appRoot.replace(/\\/g, '/')}/static/demo.mp4`;
  621. console.log('Windows平台尝试路径:', this.videoUrl);
  622. } else if (platform === 'android' || platform === 'ios') {
  623. // 移动端
  624. this.useNativeVideo();
  625. } else {
  626. // Web平台
  627. // 尝试使用完整URL
  628. const baseUrl = window.location.origin;
  629. this.videoUrl = `${baseUrl}/static/demo.mp4`;
  630. console.log('Web平台尝试URL:', this.videoUrl);
  631. }
  632. this.$nextTick(() => {
  633. const videoContext = uni.createVideoContext('myVideo', this);
  634. if (videoContext) {
  635. videoContext.play();
  636. }
  637. });
  638. },
  639. // 添加新方法:使用原生视频能力
  640. useNativeVideo() {
  641. console.log('尝试使用原生视频能力');
  642. // 在移动端,可以尝试使用原生视频播放器
  643. uni.chooseVideo({
  644. sourceType: ['album'],
  645. success: (res) => {
  646. this.videoUrl = res.tempFilePath;
  647. this.$nextTick(() => {
  648. const videoContext = uni.createVideoContext('myVideo', this);
  649. if (videoContext) {
  650. videoContext.play();
  651. }
  652. });
  653. },
  654. fail: () => {
  655. // 如果用户取消选择,回退到静态图片
  656. this.videoPlaying = false;
  657. uni.showToast({
  658. title: '无法加载视频,显示静态图片',
  659. icon: 'none'
  660. });
  661. }
  662. });
  663. },
  664. // 处理视频结束事件
  665. handleVideoEnded() {
  666. console.log('视频播放结束');
  667. this.videoPlaying = false;
  668. // 对于所有视频,都显示相应的按钮
  669. if (this.currentVideoIndex >= 1) {
  670. // 对于问题视频,显示"开始回答"按钮
  671. this.showStartRecordingButton = true;
  672. } else {
  673. // 对于介绍视频(第一个视频),显示"开始面试"按钮
  674. this.showAnswerButton = true;
  675. }
  676. },
  677. // 添加新方法:开始录制用户回答
  678. startRecordingAnswer() {
  679. console.log('开始录制用户回答');
  680. this.isRecording = true;
  681. // 显示录制中的提示
  682. // uni.showLoading({
  683. // title: '正在录制...',
  684. // mask: true
  685. // });
  686. // 根据平台选择不同的录制方法
  687. const systemInfo = uni.getSystemInfoSync();
  688. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
  689. if (isMiniProgram) {
  690. // 小程序环境使用小程序的录制API
  691. this.startMiniProgramRecording();
  692. } else {
  693. // H5/App环境使用MediaRecorder API
  694. this.startBrowserRecording();
  695. }
  696. // 显示停止录制按钮
  697. this.showStopRecordingButton = true;
  698. },
  699. // 修改小程序环境下的录制方法
  700. startMiniProgramRecording() {
  701. if (!this.cameraContext) {
  702. this.cameraContext = uni.createCameraContext();
  703. }
  704. // 确保有录音权限
  705. uni.getSetting({
  706. success: (res) => {
  707. const hasRecordAuth = res.authSetting['scope.record'];
  708. const hasCameraAuth = res.authSetting['scope.camera'];
  709. if (!hasRecordAuth || !hasCameraAuth) {
  710. console.warn('缺少必要权限,请求权限');
  711. this.requestMiniProgramPermissions();
  712. return;
  713. }
  714. // 开始录像,确保同时录制音频
  715. const options = {
  716. timeout: 60000, // 最长录制60秒
  717. success: () => {
  718. console.log('小程序录像开始成功');
  719. },
  720. fail: (err) => {
  721. console.error('小程序录像开始失败:', err);
  722. uni.showToast({
  723. title: '录制失败,请检查相机权限',
  724. icon: 'none'
  725. });
  726. this.proceedToNextQuestion();
  727. },
  728. timeoutCallback: () => {
  729. // 录制超时自动停止时的回调
  730. console.log('录制超时自动停止');
  731. this.stopRecordingAnswer();
  732. }
  733. };
  734. this.recorder = this.cameraContext.startRecord(options);
  735. }
  736. });
  737. },
  738. // 添加新方法:请求小程序权限
  739. requestMiniProgramPermissions() {
  740. // 请求录音权限
  741. uni.authorize({
  742. scope: 'scope.record',
  743. success: () => {
  744. console.log('录音权限已获取');
  745. // 请求相机权限
  746. uni.authorize({
  747. scope: 'scope.camera',
  748. success: () => {
  749. console.log('相机权限已获取');
  750. // 权限都获取到后,开始录制
  751. this.startMiniProgramRecording();
  752. },
  753. fail: (err) => {
  754. console.error('相机权限获取失败:', err);
  755. this.showPermissionDialog('相机');
  756. }
  757. });
  758. },
  759. fail: (err) => {
  760. console.error('录音权限获取失败:', err);
  761. this.showPermissionDialog('录音');
  762. }
  763. });
  764. },
  765. // 修改浏览器环境下的录制方法
  766. startBrowserRecording() {
  767. if (!this.cameraStream) {
  768. console.error('没有可用的摄像头流');
  769. uni.showToast({
  770. title: '录制失败,摄像头未就绪',
  771. icon: 'none'
  772. });
  773. this.proceedToNextQuestion();
  774. return;
  775. }
  776. try {
  777. // 检查流中是否包含音频轨道
  778. const hasAudio = this.cameraStream.getAudioTracks().length > 0;
  779. if (!hasAudio) {
  780. console.warn('警告:媒体流中没有音频轨道,尝试重新获取带音频的媒体流');
  781. // 尝试重新获取带音频的媒体流
  782. navigator.mediaDevices.getUserMedia({
  783. audio: {
  784. echoCancellation: true,
  785. noiseSuppression: true,
  786. autoGainControl: true
  787. },
  788. video: true
  789. })
  790. .then(newStream => {
  791. // 检查新流是否包含音频轨道
  792. const audioTracks = newStream.getAudioTracks();
  793. if (audioTracks.length > 0) {
  794. console.log('成功获取音频轨道:', audioTracks[0].label);
  795. // 合并视频和音频轨道
  796. const videoTrack = this.cameraStream.getVideoTracks()[0];
  797. const audioTrack = newStream.getAudioTracks()[0];
  798. // 创建新的媒体流,包含视频和音频轨道
  799. const combinedStream = new MediaStream();
  800. if (videoTrack) combinedStream.addTrack(videoTrack);
  801. if (audioTrack) combinedStream.addTrack(audioTrack);
  802. this.cameraStream = combinedStream;
  803. // 更新视频元素的源
  804. const videoElement = this.$refs.userCameraVideo;
  805. if (videoElement) {
  806. videoElement.srcObject = combinedStream;
  807. videoElement.muted = true; // 避免回声,但仍然录制声音
  808. }
  809. // 继续录制过程
  810. this.setupMediaRecorder(combinedStream);
  811. } else {
  812. console.warn('仍然无法获取音频轨道');
  813. // 使用现有流继续
  814. this.setupMediaRecorder(this.cameraStream);
  815. }
  816. })
  817. .catch(err => {
  818. console.error('获取音频失败:', err);
  819. // 使用现有流继续
  820. this.setupMediaRecorder(this.cameraStream);
  821. });
  822. } else {
  823. console.log('检测到音频轨道,直接使用');
  824. // 已有音频轨道,直接使用
  825. this.setupMediaRecorder(this.cameraStream);
  826. }
  827. } catch (error) {
  828. console.error('浏览器录制失败:', error);
  829. uni.showToast({
  830. title: '录制失败,浏览器可能不支持此功能',
  831. icon: 'none'
  832. });
  833. this.proceedToNextQuestion();
  834. }
  835. },
  836. // 修改 setupMediaRecorder 方法
  837. setupMediaRecorder(stream) {
  838. // 检查流中的轨道
  839. const videoTracks = stream.getVideoTracks();
  840. const audioTracks = stream.getAudioTracks();
  841. console.log('设置MediaRecorder - 视频轨道:', videoTracks.length, '音频轨道:', audioTracks.length);
  842. // 尝试使用支持度更广的编码格式
  843. let mimeType = '';
  844. const supportedTypes = [
  845. 'video/webm;codecs=vp9,opus',
  846. 'video/webm;codecs=vp8,opus',
  847. 'video/webm;codecs=h264,opus',
  848. 'video/mp4;codecs=h264,aac',
  849. 'video/webm',
  850. 'video/mp4'
  851. ];
  852. for (const type of supportedTypes) {
  853. if (MediaRecorder.isTypeSupported(type)) {
  854. mimeType = type;
  855. console.log('使用支持的MIME类型:', mimeType);
  856. break;
  857. }
  858. }
  859. // 创建MediaRecorder实例,设置较高的音频比特率
  860. const options = {
  861. mimeType: mimeType || '',
  862. audioBitsPerSecond: 128000,
  863. videoBitsPerSecond: 2500000
  864. };
  865. try {
  866. this.mediaRecorder = new MediaRecorder(stream, options);
  867. console.log('MediaRecorder创建成功,使用选项:', options);
  868. } catch (e) {
  869. console.warn('使用指定选项创建MediaRecorder失败,尝试使用默认选项');
  870. this.mediaRecorder = new MediaRecorder(stream);
  871. }
  872. // 存储录制的数据块
  873. this.recordedChunks = [];
  874. // 监听数据可用事件
  875. this.mediaRecorder.ondataavailable = (event) => {
  876. if (event.data && event.data.size > 0) {
  877. this.recordedChunks.push(event.data);
  878. console.log(`收到数据块: ${event.data.size} 字节`);
  879. }
  880. };
  881. // 监听录制停止事件
  882. this.mediaRecorder.onstop = () => {
  883. console.log('MediaRecorder停止,数据块数量:', this.recordedChunks.length);
  884. if (this.recordedChunks.length === 0) {
  885. console.error('没有录制到数据');
  886. uni.showToast({
  887. title: '录制失败,未捕获到数据',
  888. icon: 'none'
  889. });
  890. this.proceedToNextQuestion();
  891. return;
  892. }
  893. // 创建Blob对象
  894. const mimeType = this.mediaRecorder.mimeType || 'video/webm';
  895. const blob = new Blob(this.recordedChunks, { type: mimeType });
  896. console.log('创建Blob,大小:', blob.size, '类型:', mimeType);
  897. // 将Blob转换为File对象
  898. const fileName = `answer_${this.currentVideoIndex}_${Date.now()}.webm`;
  899. const file = new File([blob], fileName, { type: mimeType });
  900. // 上传文件
  901. this.uploadRecordedVideo(file);
  902. };
  903. // 监听错误
  904. this.mediaRecorder.onerror = (event) => {
  905. console.error('MediaRecorder错误:', event.error);
  906. };
  907. // 开始录制
  908. try {
  909. this.mediaRecorder.start(1000); // 每秒触发一次dataavailable事件
  910. console.log('MediaRecorder开始录制');
  911. } catch (e) {
  912. console.error('开始录制失败:', e);
  913. }
  914. },
  915. // 添加新方法:停止录制用户回答
  916. stopRecordingAnswer() {
  917. console.log('停止录制用户回答');
  918. this.isRecording = false;
  919. // 清除定时器
  920. if (this.recordingTimer) {
  921. clearTimeout(this.recordingTimer);
  922. this.recordingTimer = null;
  923. }
  924. // 隐藏录制中提示
  925. uni.hideLoading();
  926. // 隐藏停止录制按钮
  927. this.showStopRecordingButton = false;
  928. // 根据平台选择不同的停止录制方法
  929. const systemInfo = uni.getSystemInfoSync();
  930. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
  931. if (isMiniProgram) {
  932. // 小程序环境停止录制
  933. this.stopMiniProgramRecording();
  934. } else {
  935. // H5/App环境停止录制
  936. this.stopBrowserRecording();
  937. }
  938. },
  939. // 添加新方法:停止小程序录制
  940. stopMiniProgramRecording() {
  941. if (!this.cameraContext) {
  942. console.error('相机上下文不存在');
  943. this.proceedToNextQuestion();
  944. return;
  945. }
  946. this.cameraContext.stopRecord({
  947. success: (res) => {
  948. console.log('小程序录像停止成功:', res);
  949. // 获取临时文件路径
  950. const tempFilePath = res.tempVideoPath;
  951. // 上传视频
  952. this.uploadRecordedVideo(tempFilePath);
  953. },
  954. fail: (err) => {
  955. console.error('小程序录像停止失败:', err);
  956. uni.showToast({
  957. title: '录制失败',
  958. icon: 'none'
  959. });
  960. this.proceedToNextQuestion();
  961. }
  962. });
  963. },
  964. // 添加新方法:停止浏览器录制
  965. stopBrowserRecording() {
  966. if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
  967. this.mediaRecorder.stop();
  968. console.log('浏览器录制停止成功');
  969. } else {
  970. console.error('MediaRecorder不存在或已经停止');
  971. this.proceedToNextQuestion();
  972. }
  973. },
  974. // 修改上传录制的视频方法
  975. uploadRecordedVideo(fileOrPath) {
  976. console.log('准备上传视频:', typeof fileOrPath === 'string' ? fileOrPath : fileOrPath.name);
  977. // 显示上传中提示
  978. uni.showLoading({
  979. title: '正在上传...',
  980. mask: true
  981. });
  982. // 获取用户信息
  983. const userInfo = uni.getStorageSync('userInfo');
  984. const openid = userInfo ? (JSON.parse(userInfo).openid || '') : '';
  985. const tenant_id = uni.getStorageSync('tenant_id') || '1';
  986. // 根据当前视频索引映射到正确的问题ID
  987. let questionId;
  988. switch(this.currentVideoIndex) {
  989. case 1: // 第一个问题
  990. questionId = 10;
  991. break;
  992. case 2: // 第二个问题
  993. questionId = 11;
  994. break;
  995. case 3: // 第三个问题
  996. questionId = 12;
  997. break;
  998. case 4: // 第四个问题
  999. questionId = 13;
  1000. break;
  1001. default:
  1002. questionId = 10; // 默认值
  1003. }
  1004. // 检查是否在浏览器环境中使用File对象
  1005. if (typeof fileOrPath !== 'string') {
  1006. // 在浏览器环境中,我们需要将File对象转换为FormData
  1007. const formData = new FormData();
  1008. formData.append('file', fileOrPath);
  1009. formData.append('openid', openid);
  1010. formData.append('tenant_id', tenant_id);
  1011. formData.append('application_id', 1);
  1012. formData.append('question_id', questionId);
  1013. formData.append('video_duration', 0);
  1014. formData.append('has_audio', 'true'); // 明确标记视频包含音频
  1015. // 使用XMLHttpRequest直接上传
  1016. const xhr = new XMLHttpRequest();
  1017. xhr.open('POST', `${apiBaseUrl}/api/system/upload/`, true);
  1018. xhr.onload = () => {
  1019. uni.hideLoading();
  1020. if (xhr.status === 200) {
  1021. try {
  1022. const res = JSON.parse(xhr.responseText);
  1023. console.log('上传响应:', res);
  1024. if (res.code === 2000) {
  1025. // 获取上传后的视频URL
  1026. const videoUrl = res.data.url || res.data.photoUrl || '';
  1027. if (videoUrl) {
  1028. // 提交到面试接口
  1029. this.submitVideoToInterview(videoUrl);
  1030. } else {
  1031. uni.showToast({
  1032. title: '视频URL获取失败',
  1033. icon: 'none'
  1034. });
  1035. }
  1036. } else {
  1037. uni.showToast({
  1038. title: res.msg || '上传失败,请重试',
  1039. icon: 'none'
  1040. });
  1041. }
  1042. } catch (e) {
  1043. console.error('解析响应失败:', e);
  1044. uni.showToast({
  1045. title: '解析响应失败',
  1046. icon: 'none'
  1047. });
  1048. }
  1049. } else {
  1050. uni.showToast({
  1051. title: '上传失败,HTTP状态: ' + xhr.status,
  1052. icon: 'none'
  1053. });
  1054. }
  1055. };
  1056. xhr.onerror = () => {
  1057. uni.hideLoading();
  1058. console.error('上传网络错误');
  1059. uni.showToast({
  1060. title: '网络错误,请重试',
  1061. icon: 'none'
  1062. });
  1063. };
  1064. xhr.upload.onprogress = (event) => {
  1065. if (event.lengthComputable) {
  1066. const percentComplete = Math.round((event.loaded / event.total) * 100);
  1067. console.log('上传进度:', percentComplete + '%');
  1068. }
  1069. };
  1070. xhr.send(formData);
  1071. return;
  1072. }
  1073. // 对于小程序环境,使用uni.uploadFile
  1074. uni.uploadFile({
  1075. url: `${apiBaseUrl}/api/system/upload/`,
  1076. filePath: fileOrPath,
  1077. name: 'file',
  1078. formData: {
  1079. openid: openid,
  1080. tenant_id: tenant_id,
  1081. application_id: 1,
  1082. question_id: questionId,
  1083. video_duration: 0,
  1084. has_audio: 'true' // 明确标记视频包含音频
  1085. },
  1086. success: (uploadRes) => {
  1087. try {
  1088. const res = JSON.parse(uploadRes.data);
  1089. console.log('上传响应:', res);
  1090. if (res.code === 2000) {
  1091. // 获取上传后的视频URL
  1092. const videoUrl = res.data.permanent_link || res.data.url || '';
  1093. if (videoUrl) {
  1094. // 提交到面试接口
  1095. this.submitVideoToInterview(videoUrl);
  1096. } else {
  1097. uni.showToast({
  1098. title: '视频URL获取失败',
  1099. icon: 'none'
  1100. });
  1101. }
  1102. } else {
  1103. uni.showToast({
  1104. title: res.msg || '上传失败,请重试',
  1105. icon: 'none'
  1106. });
  1107. }
  1108. } catch (e) {
  1109. console.error('解析响应失败:', e);
  1110. uni.showToast({
  1111. title: '解析响应失败',
  1112. icon: 'none'
  1113. });
  1114. }
  1115. },
  1116. fail: (err) => {
  1117. console.error('上传失败:', err);
  1118. uni.showToast({
  1119. title: '上传失败,请重试',
  1120. icon: 'none'
  1121. });
  1122. },
  1123. complete: () => {
  1124. uni.hideLoading();
  1125. }
  1126. });
  1127. },
  1128. // 修改 submitVideoToInterview 方法
  1129. submitVideoToInterview(videoUrl) {
  1130. console.log('提交视频URL到面试接口:', videoUrl);
  1131. // 显示加载提示
  1132. uni.showLoading({
  1133. title: '正在提交...',
  1134. mask: true
  1135. });
  1136. // 根据当前视频索引映射到正确的问题ID
  1137. let questionId;
  1138. switch(this.currentVideoIndex) {
  1139. case 1: // 第一个问题(索引1是第二个视频,第一个是介绍视频)
  1140. questionId = 10;
  1141. break;
  1142. case 2: // 第二个问题
  1143. questionId = 11;
  1144. break;
  1145. case 3: // 第三个问题
  1146. questionId = 12;
  1147. break;
  1148. case 4: // 第四个问题
  1149. questionId = 13;
  1150. break;
  1151. default:
  1152. questionId = 10; // 默认值,以防万一
  1153. }
  1154. // 准备请求参数,使用映射后的问题ID
  1155. const requestData = {
  1156. application_id: 1,
  1157. question_id: questionId,
  1158. video_url: videoUrl,
  1159. tenant_id: uni.getStorageSync('tenant_id') || '1'
  1160. };
  1161. // 发送请求到面试接口,使用form-data格式
  1162. uni.request({
  1163. url: `${apiBaseUrl}/api/job/upload_question_video`,
  1164. method: 'POST',
  1165. data: requestData, // 使用data而不是formData
  1166. header: {
  1167. 'content-type': 'application/x-www-form-urlencoded' // 修改为form-data格式的content-type
  1168. },
  1169. success: (res) => {
  1170. console.log('面试接口提交成功:', res);
  1171. uni.hideLoading();
  1172. if (res.data.code === 0 || res.data.code === 2000) {
  1173. // 提交成功
  1174. uni.showToast({
  1175. title: '回答已提交',
  1176. icon: 'success'
  1177. });
  1178. // 保存最后上传的视频URL
  1179. this.lastUploadedVideoUrl = videoUrl;
  1180. // 隐藏重试按钮(如果之前显示了)
  1181. this.showRetryButton = false;
  1182. this.lastVideoToRetry = null;
  1183. // 延迟一下再进入下一题,让用户看到成功提示
  1184. setTimeout(() => {
  1185. // 检查是否完成了第五个视频问题(索引为4)
  1186. if (this.currentVideoIndex === 4) {
  1187. // 完成第五个问题后,跳转到相机页面
  1188. uni.navigateTo({
  1189. url: '/pages/camera/camera'
  1190. });
  1191. } else {
  1192. // 否则继续正常流程
  1193. this.proceedToNextQuestion();
  1194. }
  1195. }, 1500);
  1196. } else {
  1197. // 提交失败
  1198. uni.showToast({
  1199. title: res.data.msg || '提交失败,请重试',
  1200. icon: 'none'
  1201. });
  1202. // 保存失败的视频URL,用于重试
  1203. this.lastVideoToRetry = videoUrl;
  1204. // 显示重试按钮
  1205. this.showRetryButton = true;
  1206. }
  1207. },
  1208. fail: (err) => {
  1209. console.error('面试接口提交失败:', err);
  1210. uni.hideLoading();
  1211. uni.showToast({
  1212. title: '网络错误,请重试',
  1213. icon: 'none'
  1214. });
  1215. // 保存失败的视频URL,用于重试
  1216. this.lastVideoToRetry = videoUrl;
  1217. // 显示重试按钮
  1218. this.showRetryButton = true;
  1219. }
  1220. });
  1221. },
  1222. // 修改 proceedToNextQuestion 方法
  1223. proceedToNextQuestion() {
  1224. // 检查是否完成了第五个视频问题(索引为4)
  1225. if (this.currentVideoIndex === 4) {
  1226. // 完成第五个问题后,跳转到相机页面
  1227. uni.navigateTo({
  1228. url: '/pages/camera/camera'
  1229. });
  1230. return;
  1231. }
  1232. // 切换到下一个视频
  1233. this.currentVideoIndex++;
  1234. if (this.currentVideoIndex < this.videoList.length) {
  1235. // 还有下一段视频,播放它
  1236. this.videoUrl = this.videoList[this.currentVideoIndex];
  1237. this.videoPlaying = true;
  1238. // 重置当前字幕
  1239. this.currentSubtitle = '';
  1240. // 使用 nextTick 确保 DOM 更新后再播放视频
  1241. this.$nextTick(() => {
  1242. const videoContext = uni.createVideoContext('myVideo', this);
  1243. if (videoContext) {
  1244. videoContext.play();
  1245. }
  1246. });
  1247. } else {
  1248. // 所有视频都播放完毕,可以进行下一步操作
  1249. uni.showToast({
  1250. title: '面试完成',
  1251. icon: 'success',
  1252. duration: 2000
  1253. });
  1254. // 可以在这里添加面试完成后的逻辑,比如跳转到下一个页面
  1255. setTimeout(() => {
  1256. uni.navigateTo({
  1257. url: '/pages/interview-result/interview-result'
  1258. });
  1259. }, 2000);
  1260. }
  1261. },
  1262. // 修改 handleAnswerButtonClick 方法
  1263. handleAnswerButtonClick() {
  1264. // 隐藏答题按钮
  1265. this.showAnswerButton = false;
  1266. // 直接进入下一个问题
  1267. this.proceedToNextQuestion();
  1268. },
  1269. // 处理相机错误
  1270. handleCameraError(e) {
  1271. console.error('相机错误:', e);
  1272. // 显示错误提示
  1273. uni.showToast({
  1274. title: '相机初始化失败,请检查权限设置',
  1275. icon: 'none'
  1276. });
  1277. // 尝试备用选项
  1278. this.tryFallbackOptions();
  1279. },
  1280. // 添加新方法:尝试备用选项
  1281. tryFallbackOptions() {
  1282. // 检查环境
  1283. const systemInfo = uni.getSystemInfoSync();
  1284. // 在小程序环境中使用小程序API
  1285. if (systemInfo.uniPlatform === 'mp-weixin' || systemInfo.uniPlatform === 'mp-alipay') {
  1286. this.useMiniProgramCamera();
  1287. }
  1288. // 在H5环境中显示静态图像
  1289. else {
  1290. this.showStaticCameraPlaceholder();
  1291. }
  1292. },
  1293. // 添加新方法:使用小程序相机API
  1294. useMiniProgramCamera() {
  1295. console.log('尝试使用小程序相机组件');
  1296. // 这里需要在模板中添加小程序相机组件
  1297. // 并设置一个标志来控制显示
  1298. this.useMiniProgramCameraComponent = true;
  1299. },
  1300. // 添加新方法:显示静态图像
  1301. showStaticCameraPlaceholder() {
  1302. console.log('显示静态摄像头占位图');
  1303. // 创建一个图像元素
  1304. const img = document.createElement('img');
  1305. img.src = '/static/images/camera-placeholder.png'; // 确保有这个图片资源
  1306. img.className = 'static-camera-image';
  1307. img.style.width = '100%';
  1308. img.style.height = '100%';
  1309. img.style.objectFit = 'cover';
  1310. // 获取容器并添加图像
  1311. const container = this.$refs.userCameraVideo.parentNode;
  1312. container.appendChild(img);
  1313. },
  1314. // 处理视频时间更新事件
  1315. handleTimeUpdate(e) {
  1316. // 获取当前视频播放时间
  1317. const currentTime = e.target.currentTime;
  1318. // 根据当前播放的视频索引选择对应的字幕数组
  1319. let currentSubtitles;
  1320. if (this.currentVideoIndex === 0) {
  1321. currentSubtitles = this.subtitles;
  1322. } else if (this.currentVideoIndex === 1) {
  1323. currentSubtitles = this.secondVideoSubtitles;
  1324. }else if (this.currentVideoIndex === 2) {
  1325. currentSubtitles = this.thirdVideoSubtitles;
  1326. }else if (this.currentVideoIndex === 3) {
  1327. currentSubtitles = this.fourthVideoSubtitles;
  1328. }else if (this.currentVideoIndex === 4) {
  1329. currentSubtitles = this.fifthVideoSubtitles;
  1330. }else if (this.currentVideoIndex === 5) {
  1331. currentSubtitles = this.sixthVideoSubtitles;
  1332. }else {
  1333. // 如果有更多视频,可以继续添加条件
  1334. currentSubtitles = [];
  1335. }
  1336. // 查找当前时间应该显示的字幕
  1337. const subtitle = currentSubtitles.find(
  1338. sub => currentTime >= sub.startTime && currentTime < sub.endTime
  1339. );
  1340. // 更新当前字幕
  1341. this.currentSubtitle = subtitle ? subtitle.text : '';
  1342. },
  1343. // Add a new method to handle the "Start Recording" button click
  1344. handleStartRecordingClick() {
  1345. // 隐藏"开始回答"按钮
  1346. this.showStartRecordingButton = false;
  1347. // 开始录制
  1348. this.startRecordingAnswer();
  1349. },
  1350. // 修改 checkAudioPermission 方法,确保在录制前获取音频权限
  1351. checkAudioPermission() {
  1352. // 在小程序环境中
  1353. const systemInfo = uni.getSystemInfoSync();
  1354. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
  1355. if (isMiniProgram) {
  1356. // 小程序环境下的权限请求
  1357. uni.getSetting({
  1358. success: (res) => {
  1359. if (!res.authSetting['scope.record']) {
  1360. uni.authorize({
  1361. scope: 'scope.record',
  1362. success: () => {
  1363. console.log('录音权限已获取');
  1364. },
  1365. fail: (err) => {
  1366. console.error('录音权限获取失败:', err);
  1367. this.showPermissionDialog('录音');
  1368. }
  1369. });
  1370. }
  1371. if (!res.authSetting['scope.camera']) {
  1372. uni.authorize({
  1373. scope: 'scope.camera',
  1374. success: () => {
  1375. console.log('相机权限已获取');
  1376. },
  1377. fail: (err) => {
  1378. console.error('相机权限获取失败:', err);
  1379. this.showPermissionDialog('相机');
  1380. }
  1381. });
  1382. }
  1383. }
  1384. });
  1385. } else {
  1386. // 浏览器环境下的权限请求
  1387. // ... 保持原有代码不变
  1388. }
  1389. },
  1390. // 添加新方法:测试音频输入
  1391. testAudioInput() {
  1392. if (!this.cameraStream) {
  1393. console.warn('没有可用的媒体流,无法测试音频');
  1394. return;
  1395. }
  1396. const audioTracks = this.cameraStream.getAudioTracks();
  1397. if (audioTracks.length === 0) {
  1398. console.warn('没有检测到音频轨道,尝试重新获取');
  1399. this.tryGetAudioOnly();
  1400. return;
  1401. }
  1402. console.log('音频轨道信息:', audioTracks[0].getSettings());
  1403. // 创建音频上下文和分析器
  1404. try {
  1405. const AudioContext = window.AudioContext || window.webkitAudioContext;
  1406. if (!AudioContext) {
  1407. console.warn('浏览器不支持AudioContext');
  1408. return;
  1409. }
  1410. const audioContext = new AudioContext();
  1411. const analyser = audioContext.createAnalyser();
  1412. const microphone = audioContext.createMediaStreamSource(this.cameraStream);
  1413. microphone.connect(analyser);
  1414. // 设置分析器
  1415. analyser.fftSize = 256;
  1416. const bufferLength = analyser.frequencyBinCount;
  1417. const dataArray = new Uint8Array(bufferLength);
  1418. // 检测音频输入
  1419. let silenceCounter = 0;
  1420. const checkAudio = () => {
  1421. if (this.isRecording) return; // 如果正在录制,停止检测
  1422. analyser.getByteFrequencyData(dataArray);
  1423. // 计算平均音量
  1424. let sum = 0;
  1425. for (let i = 0; i < bufferLength; i++) {
  1426. sum += dataArray[i];
  1427. }
  1428. const average = sum / bufferLength;
  1429. if (average > 10) {
  1430. console.log('检测到音频输入,音量:', average);
  1431. silenceCounter = 0;
  1432. } else {
  1433. silenceCounter++;
  1434. if (silenceCounter > 10) {
  1435. console.warn('持续检测不到音频输入,可能麦克风未正常工作');
  1436. silenceCounter = 0;
  1437. }
  1438. }
  1439. // 继续检测
  1440. requestAnimationFrame(checkAudio);
  1441. };
  1442. // 开始检测
  1443. checkAudio();
  1444. } catch (e) {
  1445. console.error('音频测试失败:', e);
  1446. }
  1447. },
  1448. // 添加新方法:尝试单独获取音频
  1449. tryGetAudioOnly() {
  1450. navigator.mediaDevices.getUserMedia({ audio: true })
  1451. .then(audioStream => {
  1452. // 如果已有视频流,合并音频和视频轨道
  1453. if (this.cameraStream) {
  1454. const videoTrack = this.cameraStream.getVideoTracks()[0];
  1455. const audioTrack = audioStream.getAudioTracks()[0];
  1456. // 创建新的媒体流,包含视频和音频轨道
  1457. const combinedStream = new MediaStream();
  1458. if (videoTrack) combinedStream.addTrack(videoTrack);
  1459. if (audioTrack) combinedStream.addTrack(audioTrack);
  1460. // 更新摄像头流
  1461. this.cameraStream = combinedStream;
  1462. // 更新视频元素的源
  1463. const videoElement = this.$refs.userCameraVideo;
  1464. if (videoElement) {
  1465. videoElement.srcObject = combinedStream;
  1466. videoElement.muted = true; // 避免回声,但仍然录制声音
  1467. }
  1468. console.log('成功合并音频和视频轨道');
  1469. } else {
  1470. console.warn('没有视频流可合并');
  1471. }
  1472. })
  1473. .catch(err => {
  1474. console.error('单独获取音频失败:', err);
  1475. });
  1476. },
  1477. // 添加新方法:显示权限对话框
  1478. showPermissionDialog(permissionType) {
  1479. uni.showModal({
  1480. title: '需要权限',
  1481. content: `请允许使用${permissionType}权限,否则可能影响面试功能`,
  1482. confirmText: '去设置',
  1483. success: (res) => {
  1484. if (res.confirm) {
  1485. uni.openSetting({
  1486. success: (settingRes) => {
  1487. console.log('设置页面打开成功', settingRes);
  1488. }
  1489. });
  1490. }
  1491. }
  1492. });
  1493. },
  1494. // 添加重试上传方法
  1495. retryVideoUpload() {
  1496. if (this.lastVideoToRetry) {
  1497. // 隐藏重试按钮
  1498. this.showRetryButton = false;
  1499. // 显示加载提示
  1500. uni.showLoading({
  1501. title: '正在重新提交...',
  1502. mask: true
  1503. });
  1504. // 重新提交视频
  1505. this.submitVideoToInterview(this.lastVideoToRetry);
  1506. } else {
  1507. uni.showToast({
  1508. title: '没有可重试的视频',
  1509. icon: 'none'
  1510. });
  1511. }
  1512. }
  1513. }
  1514. }
  1515. </script>
  1516. <style scoped>
  1517. .identity-verify-container {
  1518. padding: 0;
  1519. max-width: 100%;
  1520. margin: 0 auto;
  1521. height: 100vh;
  1522. display: flex;
  1523. flex-direction: column;
  1524. background-color: #f5f5f5;
  1525. }
  1526. .digital-human-container {
  1527. position: relative;
  1528. width: 100%;
  1529. height: 100vh;
  1530. overflow: hidden;
  1531. background-color: #f0f0f0;
  1532. }
  1533. .digital-human-video {
  1534. width: 100%;
  1535. height: 100%;
  1536. display: flex;
  1537. justify-content: center;
  1538. align-items: center;
  1539. }
  1540. /* 用户摄像头容器样式 */
  1541. .user-camera-container {
  1542. position: absolute;
  1543. top: 20px;
  1544. right: 20px;
  1545. width: 100px;
  1546. height: 150px;
  1547. border-radius: 8px;
  1548. overflow: hidden;
  1549. box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  1550. z-index: 20;
  1551. border: 1px solid #fff;
  1552. }
  1553. /* 用户摄像头视频样式 */
  1554. .user-camera-video {
  1555. width: 100%;
  1556. height: 100%;
  1557. object-fit: cover;
  1558. background-color: #333;
  1559. }
  1560. .video-player {
  1561. width: 100%;
  1562. height: 100%;
  1563. object-fit: cover;
  1564. outline: none; /* 移除视频获得焦点时的轮廓 */
  1565. -webkit-tap-highlight-color: transparent; /* 移除移动设备上的点击高亮 */
  1566. }
  1567. /* 隐藏视频控制条 */
  1568. video::-webkit-media-controls {
  1569. display: none !important;
  1570. }
  1571. video::-webkit-media-controls-enclosure {
  1572. display: none !important;
  1573. }
  1574. video::-webkit-media-controls-panel {
  1575. display: none !important;
  1576. }
  1577. video::-webkit-media-controls-play-button {
  1578. display: none !important;
  1579. }
  1580. video::-webkit-media-controls-timeline {
  1581. display: none !important;
  1582. }
  1583. video::-webkit-media-controls-current-time-display {
  1584. display: none !important;
  1585. }
  1586. video::-webkit-media-controls-time-remaining-display {
  1587. display: none !important;
  1588. }
  1589. video::-webkit-media-controls-mute-button {
  1590. display: none !important;
  1591. }
  1592. video::-webkit-media-controls-volume-slider {
  1593. display: none !important;
  1594. }
  1595. video::-webkit-media-controls-fullscreen-button {
  1596. display: none !important;
  1597. }
  1598. .subtitle-overlay {
  1599. position: absolute;
  1600. bottom: 50px;
  1601. left: 0;
  1602. width: 100%;
  1603. padding: 15px;
  1604. background-color: rgba(0, 0, 0, 0.7);
  1605. color: white;
  1606. text-align: center;
  1607. font-size: 16px;
  1608. line-height: 1.5;
  1609. z-index: 10;
  1610. border-radius: 4px;
  1611. max-width: 90%;
  1612. margin: 0 auto;
  1613. left: 5%;
  1614. right: 5%;
  1615. }
  1616. .control-panel {
  1617. padding: 15px;
  1618. display: flex;
  1619. justify-content: center;
  1620. }
  1621. .control-button {
  1622. padding: 10px 20px;
  1623. background-color: #4CAF50;
  1624. color: white;
  1625. border: none;
  1626. border-radius: 4px;
  1627. cursor: pointer;
  1628. }
  1629. .loading {
  1630. text-align: center;
  1631. margin: 20px 0;
  1632. font-size: 16px;
  1633. }
  1634. .response-container {
  1635. margin-top: 20px;
  1636. padding: 0 20px;
  1637. display: none; /* 默认隐藏调试信息 */
  1638. }
  1639. /* 当showDebugInfo为true时显示 */
  1640. .showDebugInfo .response-container {
  1641. display: block;
  1642. }
  1643. .response-item {
  1644. padding: 10px;
  1645. border: 1px solid #eee;
  1646. border-radius: 4px;
  1647. margin-bottom: 10px;
  1648. background-color: #f9f9f9;
  1649. }
  1650. .response-content {
  1651. display: flex;
  1652. flex-direction: column;
  1653. }
  1654. .answer-button-container {
  1655. position: absolute;
  1656. top: 75%;
  1657. left: 50%;
  1658. transform: translate(-50%, -50%);
  1659. z-index: 20;
  1660. }
  1661. .answer-button {
  1662. width: 120px;
  1663. height: 120px;
  1664. border-radius: 50%;
  1665. background-color: #6c5ce7; /* 绿色背景,与图片中的颜色类似 */
  1666. color: white;
  1667. font-size: 18px;
  1668. border: none;
  1669. box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
  1670. display: flex;
  1671. justify-content: center;
  1672. align-items: center;
  1673. cursor: pointer;
  1674. animation: pulse 2s infinite;
  1675. }
  1676. @keyframes pulse {
  1677. 0% {
  1678. transform: scale(1);
  1679. box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
  1680. }
  1681. 50% {
  1682. transform: scale(1.05);
  1683. box-shadow: 0 8px 15px rgba(0, 0, 0, 0.4);
  1684. }
  1685. 100% {
  1686. transform: scale(1);
  1687. box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
  1688. }
  1689. }
  1690. .stop-recording-button-container {
  1691. position: absolute;
  1692. top: 75%;
  1693. left: 50%;
  1694. transform: translate(-50%, -50%);
  1695. z-index: 20;
  1696. }
  1697. .stop-recording-button {
  1698. width: 120px;
  1699. height: 120px;
  1700. border-radius: 50%;
  1701. background-color: #e74c3c; /* 红色背景 */
  1702. color: white;
  1703. font-size: 18px;
  1704. border: none;
  1705. box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
  1706. display: flex;
  1707. justify-content: center;
  1708. align-items: center;
  1709. cursor: pointer;
  1710. animation: pulse 2s infinite;
  1711. }
  1712. @keyframes pulse {
  1713. 0% {
  1714. transform: scale(1);
  1715. box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
  1716. }
  1717. 50% {
  1718. transform: scale(1.05);
  1719. box-shadow: 0 8px 15px rgba(0, 0, 0, 0.4);
  1720. }
  1721. 100% {
  1722. transform: scale(1);
  1723. box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
  1724. }
  1725. }
  1726. /* 录制中的指示器 */
  1727. .recording-indicator {
  1728. position: absolute;
  1729. top: 20px;
  1730. left: 20px;
  1731. display: flex;
  1732. align-items: center;
  1733. background-color: rgba(0, 0, 0, 0.6);
  1734. padding: 5px 10px;
  1735. border-radius: 15px;
  1736. z-index: 20;
  1737. }
  1738. .recording-dot {
  1739. width: 12px;
  1740. height: 12px;
  1741. background-color: #e74c3c;
  1742. border-radius: 50%;
  1743. margin-right: 8px;
  1744. animation: blink 1s infinite;
  1745. }
  1746. .recording-text {
  1747. color: white;
  1748. font-size: 14px;
  1749. }
  1750. @keyframes blink {
  1751. 0% { opacity: 1; }
  1752. 50% { opacity: 0.3; }
  1753. 100% { opacity: 1; }
  1754. }
  1755. .start-recording-button-container {
  1756. position: absolute;
  1757. top: 75%;
  1758. left: 50%;
  1759. transform: translate(-50%, -50%);
  1760. z-index: 20;
  1761. }
  1762. .start-recording-button {
  1763. width: 120px;
  1764. height: 120px;
  1765. border-radius: 50%;
  1766. background-color: #6c5ce7; /* 与开始面试按钮颜色保持一致 */
  1767. color: white;
  1768. font-size: 18px;
  1769. border: none;
  1770. box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
  1771. display: flex;
  1772. justify-content: center;
  1773. align-items: center;
  1774. cursor: pointer;
  1775. animation: pulse 2s infinite; /* 使用相同的动画 */
  1776. }
  1777. /* 可以删除pulse-green动画,直接使用与开始面试按钮相同的pulse动画 */
  1778. .retry-button-container {
  1779. position: absolute;
  1780. bottom: 50px;
  1781. left: 50%;
  1782. transform: translateX(-50%);
  1783. z-index: 20;
  1784. }
  1785. .retry-button {
  1786. padding: 10px 20px;
  1787. background-color: #3498db; /* 蓝色背景 */
  1788. color: white;
  1789. font-size: 16px;
  1790. border: none;
  1791. border-radius: 4px;
  1792. box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  1793. cursor: pointer;
  1794. }
  1795. .retry-button:hover {
  1796. background-color: #2980b9;
  1797. }
  1798. </style>