identity-verify.js 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569
  1. "use strict";
  2. const common_vendor = require("../../common/vendor.js");
  3. const common_config = require("../../common/config.js");
  4. const _sfc_main = {
  5. name: "IdentityVerify",
  6. data() {
  7. return {
  8. loading: false,
  9. responses: [],
  10. processedResponses: [],
  11. assistantResponse: "",
  12. audioTranscript: "",
  13. videoPlaying: false,
  14. showDebugInfo: false,
  15. // 设置为true可以显示调试信息
  16. videoUrl: "",
  17. // 修改为空字符串,将通过API获取
  18. showReplayButton: false,
  19. cameraStream: null,
  20. // 存储摄像头流
  21. cameraError: null,
  22. // 存储摄像头错误信息
  23. useMiniProgramCameraComponent: false,
  24. // 添加小程序相机组件标志
  25. cameraContext: null,
  26. // 添加相机上下文
  27. currentSubtitle: "",
  28. currentTranslation: "",
  29. // 添加翻译文本
  30. subtitles: [],
  31. // 修改为空数组,将通过API获取
  32. // 移除硬编码的字幕数组
  33. // secondVideoSubtitles: [...],
  34. // thirdVideoSubtitles: [...],
  35. // 等等...
  36. showAnswerButton: false,
  37. // 控制答题按钮显示
  38. currentVideoIndex: 0,
  39. // 当前播放的视频索引
  40. videoList: [],
  41. // 修改为空数组,将通过API获取
  42. // 其他属性保持不变...
  43. questions: [],
  44. // 添加新属性存储API返回的问题数据
  45. introVideoUrl: "https://data.qicai321.com/minlong/ee4d9cce-c3d5-4350-8c6e-684283827897.mp4",
  46. // 保留介绍视频
  47. isRecording: false,
  48. recordingTimer: null,
  49. showStopRecordingButton: false,
  50. mediaRecorder: null,
  51. recordedChunks: [],
  52. recorder: null,
  53. lastUploadedVideoUrl: "",
  54. showStartRecordingButton: false,
  55. showRetryButton: false,
  56. // 控制重试按钮显示
  57. lastVideoToRetry: null,
  58. // 存储上次失败的视频URL,用于重试
  59. recordingStartTime: null,
  60. // 录制开始时间
  61. recordingTimerCount: 0,
  62. // 录制计时器计数
  63. recordingTimeDisplay: "00:00",
  64. // 格式化的录制时间显示
  65. // 添加上传队列相关数据
  66. uploadQueue: [],
  67. // 存储待上传的视频
  68. isUploading: false,
  69. // 标记是否正在上传
  70. uploadProgress: {},
  71. // 存储每个视频的上传进度
  72. uploadStatus: {},
  73. // 存储每个视频的上传状态
  74. showUploadStatus: false,
  75. // 是否显示上传状态指示器
  76. uploadStatusText: "",
  77. // 上传状态文本
  78. mediaRecorderTimeout: null,
  79. // 用于存储MediaRecorder的超时机制
  80. maxRecordingTime: 300,
  81. // 最大录制时间(秒)- 从60秒改为300秒(5分钟)
  82. remainingTime: 300,
  83. // 剩余录制时间(秒)- 从60秒改为300秒
  84. countdownValue: 10,
  85. // 倒计时数值
  86. showCountdown: false,
  87. // 是否显示倒计时蒙层
  88. countdownTimer: null,
  89. showGif: false,
  90. // 控制是否显示GIF
  91. gifUrl: "",
  92. // GIF图片的URL
  93. globalSocketTask: null,
  94. // 添加全局 WebSocket 连接对象
  95. lowScoreVideoUrl: "https://data.qicai321.com/minlong/latentsync/0530e7f5-1957-422d-8f34-ba4a92608081_result.mp4",
  96. // 低分提示视频URL
  97. showRerecordButton: false,
  98. // 控制重新录制按钮显示
  99. isPlayingLowScoreVideo: false,
  100. // 标记是否正在播放低分提示视频
  101. lowScoreVideoSubtitles: [
  102. {
  103. startTime: 0,
  104. endTime: 10,
  105. // 假设视频长度为10秒,可根据实际情况调整
  106. text: "我未听清楚您在说什么,请您再说一遍!"
  107. }
  108. ],
  109. // 用于存储低分提示视频的字幕
  110. retryCount: 0,
  111. // 添加重试次数计数器
  112. maxRetryAttempts: 2,
  113. // 最大重试次数限制
  114. needPlayLowScoreVideo: false,
  115. // 是否需要播放低分视频
  116. finalRecordingDuration: 0,
  117. // 最终录制时长
  118. historyTime: 0,
  119. // 添加历史时间记录
  120. followUpQuestions: [],
  121. // 存储追问问题数据
  122. currentParentQuestionId: null,
  123. // 当前父问题ID
  124. hasPlayedFollowUp: {},
  125. // 记录已播放的追问,格式: {questionId: true}
  126. isFollowUpQuestion: false,
  127. // 标记当前是否正在播放追问问题
  128. currentFollowUpQuestion: null,
  129. // 添加当前追问问题的完整信息
  130. lastQuestionWasFollowUp: false,
  131. lastFollowUpQuestionId: null,
  132. lastUpdateTime: Date.now(),
  133. // 添加最后更新时间戳
  134. subtitleMap: {},
  135. // 用于存储字幕和翻译的映射
  136. progressPercent: 0,
  137. // 录制进度百分比
  138. progressColor: "#05dc8b",
  139. // 进度条颜色
  140. progressBgColor: "rgba(0, 0, 0,0.3)",
  141. // 进度条背景色
  142. parentQuestion: "",
  143. // 添加父问题存储
  144. screenCaptureCount: 0,
  145. // 添加截屏次数记录
  146. personDetectionSocket: null,
  147. // WebSocket对象
  148. personDetectionInterval: null,
  149. // 定时器对象
  150. showCameraWarning: false,
  151. // 添加新的数据属性
  152. showPageWarning: false
  153. // 添加新的数据属性
  154. };
  155. },
  156. mounted() {
  157. this.fetchQuestions();
  158. this.fetchFollowUpQuestions();
  159. this.checkAudioPermission();
  160. this.initCamera();
  161. this.checkIOSCameraRecordPermission();
  162. this.checkAndFixRenderingIssues();
  163. setTimeout(() => {
  164. if (this.cameraStream && !this.useMiniProgramCameraComponent) {
  165. this.testAudioInput();
  166. }
  167. }, 3e3);
  168. this.historyTime = 0;
  169. common_vendor.index.setKeepScreenOn({
  170. keepScreenOn: true
  171. });
  172. common_vendor.index.onUserCaptureScreen(() => {
  173. console.log("User captured screen");
  174. this.screenCaptureCount++;
  175. if (this.screenCaptureCount === 1) {
  176. common_vendor.index.showModal({
  177. title: "Warning",
  178. content: "Screen capture detected. If you capture the screen again, your interview will be invalid.",
  179. showCancel: false,
  180. confirmText: "OK"
  181. });
  182. } else if (this.screenCaptureCount >= 2) {
  183. common_vendor.index.showModal({
  184. title: "Interview Invalid",
  185. content: "Your interview has been invalidated due to multiple screen captures. Please contact the recruiter for assistance.",
  186. showCancel: false,
  187. confirmText: "OK",
  188. success: () => {
  189. this.invalidateInterview();
  190. }
  191. });
  192. }
  193. });
  194. const systemInfo = common_vendor.index.getSystemInfoSync();
  195. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith("mp-");
  196. if (isMiniProgram) {
  197. this.initPersonDetectionWebSocket();
  198. }
  199. },
  200. beforeDestroy() {
  201. common_vendor.index.offUserCaptureScreen();
  202. this.cleanupPersonDetectionWebSocket();
  203. },
  204. methods: {
  205. // 初始化相机
  206. async initCamera() {
  207. const systemInfo = common_vendor.index.getSystemInfoSync();
  208. const isMiniProgram = systemInfo.uniPlatform === "mp-weixin" || systemInfo.uniPlatform === "mp-alipay" || systemInfo.uniPlatform === "mp-baidu";
  209. if (isMiniProgram) {
  210. this.useMiniProgramCameraComponent = true;
  211. this.cameraContext = common_vendor.index.createCameraContext();
  212. common_vendor.index.getSetting({
  213. success: (res) => {
  214. if (!res.authSetting["scope.record"]) {
  215. common_vendor.index.authorize({
  216. scope: "scope.record",
  217. success: () => {
  218. console.log("录音权限已获取");
  219. },
  220. fail: (err) => {
  221. console.error("录音权限获取失败:", err);
  222. this.showPermissionDialog("录音");
  223. }
  224. });
  225. }
  226. if (!res.authSetting["scope.camera"]) {
  227. common_vendor.index.authorize({
  228. scope: "scope.camera",
  229. success: () => {
  230. console.log("相机权限已获取");
  231. },
  232. fail: (err) => {
  233. console.error("相机权限获取失败:", err);
  234. this.showPermissionDialog("相机");
  235. }
  236. });
  237. }
  238. const systemInfo2 = common_vendor.index.getSystemInfoSync();
  239. if (systemInfo2.platform === "ios") {
  240. if (!res.authSetting["scope.camera"] || !res.authSetting["scope.record"]) {
  241. console.log("iOS需要同时获取相机和录音权限");
  242. }
  243. }
  244. }
  245. });
  246. } else {
  247. try {
  248. const constraints = {
  249. audio: {
  250. echoCancellation: true,
  251. noiseSuppression: true,
  252. autoGainControl: true
  253. },
  254. video: {
  255. width: { ideal: 640, max: 1280 },
  256. // 控制视频宽度
  257. height: { ideal: 480, max: 720 },
  258. // 控制视频高度
  259. frameRate: { ideal: 15, max: 24 },
  260. // 控制帧率
  261. facingMode: "user"
  262. }
  263. };
  264. const stream = await navigator.mediaDevices.getUserMedia(constraints);
  265. this.cameraStream = stream;
  266. const audioTracks = stream.getAudioTracks();
  267. console.log("音频轨道数量:", audioTracks.length);
  268. if (audioTracks.length > 0) {
  269. console.log("音频轨道已获取:", audioTracks[0].label);
  270. audioTracks[0].enabled = true;
  271. } else {
  272. console.warn("未检测到音频轨道,尝试单独获取音频");
  273. this.tryGetAudioOnly();
  274. }
  275. const videoElement = this.$refs.userCameraVideo;
  276. if (videoElement) {
  277. videoElement.srcObject = stream;
  278. videoElement.muted = true;
  279. }
  280. } catch (error) {
  281. console.error("获取摄像头失败:", error);
  282. this.cameraError = error.message || "无法访问摄像头";
  283. common_vendor.index.showToast({
  284. title: "无法访问摄像头,请检查权限设置",
  285. icon: "none"
  286. });
  287. }
  288. }
  289. },
  290. // 停止用户摄像头
  291. stopUserCamera() {
  292. if (this.cameraStream) {
  293. this.cameraStream.getTracks().forEach((track) => {
  294. track.stop();
  295. });
  296. this.cameraStream = null;
  297. }
  298. },
  299. async fetchData() {
  300. this.loading = true;
  301. this.assistantResponse = "";
  302. this.audioTranscript = "";
  303. this.processedResponses = [];
  304. try {
  305. const requestTask = common_vendor.index.request({
  306. url: "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",
  307. method: "POST",
  308. header: {
  309. "Content-Type": "application/json",
  310. "Authorization": "Bearer sk-9e1ec73a7d97493b8613c63f06b6110c"
  311. },
  312. data: {
  313. "model": "qwen-omni-turbo",
  314. "messages": [
  315. {
  316. "role": "user",
  317. "content": [
  318. {
  319. "type": "input_audio",
  320. "input_audio": {
  321. "data": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250211/tixcef/cherry.wav",
  322. "format": "wav"
  323. }
  324. },
  325. {
  326. "type": "text",
  327. "text": "这段音频在说什么"
  328. }
  329. ]
  330. }
  331. ],
  332. "stream": true,
  333. "stream_options": {
  334. "include_usage": true
  335. },
  336. "modalities": ["text", "audio"],
  337. "audio": { "voice": "Cherry", "format": "wav" }
  338. },
  339. success: (res) => {
  340. console.log("请求成功,响应数据:", res.data);
  341. if (typeof res.data === "string" && res.data.includes("data: {")) {
  342. const chunks = res.data.split("data: ").filter((chunk) => chunk.trim() !== "");
  343. chunks.forEach((chunk) => {
  344. this.handleStreamResponse(chunk);
  345. });
  346. } else {
  347. this.handleStreamResponse(res.data);
  348. }
  349. this.playDigitalHumanVideo();
  350. },
  351. fail: (err) => {
  352. console.error("请求失败:", err);
  353. },
  354. complete: () => {
  355. this.loading = false;
  356. }
  357. });
  358. } catch (error) {
  359. console.error("获取数据失败:", error);
  360. this.loading = false;
  361. }
  362. },
  363. handleStreamResponse(data) {
  364. if (typeof data === "string") {
  365. if (data === "[DONE]")
  366. return;
  367. try {
  368. const cleanData = data.trim();
  369. if (cleanData.startsWith("{") && cleanData.endsWith("}")) {
  370. const jsonData = JSON.parse(cleanData);
  371. this.processStreamChunk(jsonData);
  372. }
  373. } catch (e) {
  374. console.error("解析JSON失败:", e, "原始数据:", data);
  375. }
  376. } else {
  377. this.processStreamChunk(data);
  378. }
  379. },
  380. processStreamChunk(chunk) {
  381. if (chunk.choices && chunk.choices.length > 0) {
  382. const choice = chunk.choices[0];
  383. if (choice.delta && choice.delta.content) {
  384. this.assistantResponse += choice.delta.content;
  385. }
  386. if (choice.delta && choice.delta.audio && choice.delta.audio.transcript) {
  387. this.audioTranscript += choice.delta.audio.transcript;
  388. }
  389. if (choice.delta) {
  390. const result = {};
  391. if (choice.delta.role) {
  392. result.role = choice.delta.role;
  393. }
  394. if (choice.delta.audio && choice.delta.audio.transcript) {
  395. result.transcript = choice.delta.audio.transcript;
  396. }
  397. if (Object.keys(result).length > 0) {
  398. this.processedResponses.push(result);
  399. }
  400. }
  401. }
  402. },
  403. processResponseData() {
  404. this.processedResponses = this.responses.map((item) => {
  405. const result = {};
  406. if (item.delta && item.delta.role) {
  407. result.role = item.delta.role;
  408. }
  409. if (item.delta && item.delta.audio && item.delta.audio.transcript) {
  410. result.transcript = item.delta.audio.transcript;
  411. }
  412. return result;
  413. }).filter((item) => Object.keys(item).length > 0);
  414. },
  415. // 播放数字人视频
  416. playDigitalHumanVideo() {
  417. if (this.videoList.length === 0) {
  418. this.fetchQuestions();
  419. return;
  420. }
  421. this.videoUrl = this.videoList[this.currentVideoIndex];
  422. this.videoPlaying = true;
  423. this.$nextTick(() => {
  424. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  425. if (videoContext) {
  426. videoContext.play();
  427. setTimeout(() => {
  428. if (this.videoPlaying && this.$refs.videoPlayer) {
  429. console.log("视频应该正在播放");
  430. } else {
  431. console.log("视频可能未成功播放,尝试替代方案");
  432. this.tryAlternativeVideoPath();
  433. }
  434. }, 1e3);
  435. } else {
  436. console.error("无法创建视频上下文");
  437. this.tryAlternativeVideoPath();
  438. }
  439. });
  440. },
  441. // 修改 tryAlternativeVideoPath 方法
  442. tryAlternativeVideoPath() {
  443. console.log("尝试使用替代路径");
  444. const alternativePaths = [
  445. "./static/demo.mp4",
  446. "../static/demo.mp4",
  447. "static/demo.mp4",
  448. "/static/demo.mp4",
  449. // 添加绝对路径
  450. `${window.location.origin}/static/demo.mp4`
  451. ];
  452. const currentPathIndex = alternativePaths.indexOf(this.videoUrl);
  453. const nextPathIndex = (currentPathIndex + 1) % alternativePaths.length;
  454. this.videoUrl = alternativePaths[nextPathIndex];
  455. console.log("尝试新路径:", this.videoUrl);
  456. this.$nextTick(() => {
  457. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  458. if (videoContext) {
  459. videoContext.stop();
  460. videoContext.play();
  461. setTimeout(() => {
  462. if (nextPathIndex === alternativePaths.length - 1 && !this.videoPlaying) {
  463. console.log("所有路径均失败,尝试使用uni.getVideoInfo检查视频");
  464. this.checkVideoWithAPI();
  465. }
  466. }, 1e3);
  467. }
  468. });
  469. },
  470. // 添加新方法:使用uni API检查视频
  471. checkVideoWithAPI() {
  472. common_vendor.index.getVideoInfo({
  473. src: "/static/demo.mp4",
  474. success: (res) => {
  475. console.log("视频信息获取成功:", res);
  476. this.videoUrl = "/static/demo.mp4";
  477. this.$nextTick(() => {
  478. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  479. if (videoContext) {
  480. videoContext.play();
  481. }
  482. });
  483. },
  484. fail: (err) => {
  485. console.error("视频信息获取失败:", err);
  486. this.fallbackToLocalVideo();
  487. }
  488. });
  489. },
  490. // 添加新方法:回退到本地视频
  491. fallbackToLocalVideo() {
  492. console.log("尝试使用本地视频资源");
  493. const platform = common_vendor.index.getSystemInfoSync().platform;
  494. if (platform === "android" || platform === "ios") {
  495. this.videoUrl = platform === "android" ? "android.resource://package_name/raw/demo" : "file:///assets/demo.mp4";
  496. this.$nextTick(() => {
  497. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  498. if (videoContext) {
  499. videoContext.play();
  500. }
  501. });
  502. } else {
  503. this.videoPlaying = false;
  504. common_vendor.index.showToast({
  505. title: "视频加载失败,显示静态图片",
  506. icon: "none"
  507. });
  508. }
  509. },
  510. // 修改 handleVideoError 方法
  511. handleVideoError(e) {
  512. console.error("视频加载错误:", e);
  513. if (e && e.detail) {
  514. console.error("详细错误信息:", e.detail);
  515. }
  516. common_vendor.index.getFileInfo({
  517. filePath: this.videoUrl.startsWith("/") ? this.videoUrl.substring(1) : this.videoUrl,
  518. success: (res) => {
  519. console.log("文件存在,大小:", res.size);
  520. this.tryDifferentFormat();
  521. },
  522. fail: (err) => {
  523. console.error("文件不存在或无法访问:", err);
  524. this.tryAlternativeVideoPath();
  525. }
  526. });
  527. common_vendor.index.showToast({
  528. title: "视频加载失败,请检查文件是否存在",
  529. icon: "none",
  530. duration: 2e3
  531. });
  532. },
  533. // 添加新方法:尝试不同格式
  534. tryDifferentFormat() {
  535. console.log("尝试不同的视频格式");
  536. const formats = [
  537. { ext: "mp4", mime: "video/mp4" },
  538. { ext: "webm", mime: "video/webm" },
  539. { ext: "ogg", mime: "video/ogg" },
  540. { ext: "mov", mime: "video/quicktime" }
  541. ];
  542. const currentPath = this.videoUrl;
  543. const basePath = currentPath.substring(0, currentPath.lastIndexOf(".")) || "/static/demo";
  544. let nextFormat = formats.find((f) => !currentPath.endsWith(f.ext));
  545. if (nextFormat) {
  546. this.videoUrl = `${basePath}.${nextFormat.ext}`;
  547. console.log("尝试新格式:", this.videoUrl);
  548. this.$nextTick(() => {
  549. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  550. if (videoContext) {
  551. videoContext.stop();
  552. videoContext.play();
  553. }
  554. });
  555. } else {
  556. this.useBuiltInResource();
  557. }
  558. },
  559. // 添加新方法:使用内置资源
  560. useBuiltInResource() {
  561. console.log("尝试使用内置资源");
  562. const platform = common_vendor.index.getSystemInfoSync().platform;
  563. if (platform === "windows") {
  564. process.env.UNI_INPUT_DIR || "";
  565. this.videoUrl = `./static/demo.mp4`;
  566. console.log("Windows平台尝试路径:", this.videoUrl);
  567. } else if (platform === "android" || platform === "ios") {
  568. this.useNativeVideo();
  569. } else {
  570. const baseUrl = window.location.origin;
  571. this.videoUrl = `${baseUrl}/static/demo.mp4`;
  572. console.log("Web平台尝试URL:", this.videoUrl);
  573. }
  574. this.$nextTick(() => {
  575. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  576. if (videoContext) {
  577. videoContext.play();
  578. }
  579. });
  580. },
  581. // 添加新方法:使用原生视频能力
  582. useNativeVideo() {
  583. console.log("尝试使用原生视频能力");
  584. common_vendor.index.chooseVideo({
  585. sourceType: ["album"],
  586. success: (res) => {
  587. this.videoUrl = res.tempFilePath;
  588. this.$nextTick(() => {
  589. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  590. if (videoContext) {
  591. videoContext.play();
  592. }
  593. });
  594. },
  595. fail: () => {
  596. this.videoPlaying = false;
  597. common_vendor.index.showToast({
  598. title: "无法加载视频,显示静态图片",
  599. icon: "none"
  600. });
  601. }
  602. });
  603. },
  604. // 处理视频结束事件
  605. handleVideoEnded() {
  606. console.log("视频播放结束事件触发");
  607. const videoElement = this.$refs.videoPlayer;
  608. if (videoElement) {
  609. const currentTime = videoElement.currentTime || 0;
  610. const duration = videoElement.duration || 0;
  611. if (duration > 0 && duration - currentTime > 0.5) {
  612. console.log("检测到可能的误触发结束事件,继续播放", currentTime, duration);
  613. setTimeout(() => {
  614. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  615. if (videoContext) {
  616. if (duration - currentTime > 2) {
  617. videoContext.seek(this.historyTime || 0);
  618. } else {
  619. videoContext.play();
  620. }
  621. }
  622. }, 100);
  623. return;
  624. }
  625. console.log("视频确认结束,当前时间:", currentTime, "总时长:", duration);
  626. }
  627. this.videoPlaying = false;
  628. if (this.isPlayingLowScoreVideo) {
  629. console.log("低分提示视频播放完成");
  630. if (this.retryCount < this.maxRetryAttempts) {
  631. console.log(`显示重新录制按钮 (重试次数: ${this.retryCount + 1}/${this.maxRetryAttempts})`);
  632. this.showRerecordButton = true;
  633. if (this.isFollowUpQuestion && this.currentFollowUpQuestion) {
  634. this.currentSubtitle = this.currentFollowUpQuestion.digital_human_video_subtitle || this.currentFollowUpQuestion.question;
  635. }
  636. } else {
  637. console.log("已达到最大重试次数,继续下一题");
  638. this.retryCount = 0;
  639. this.proceedToNextQuestion();
  640. }
  641. this.isPlayingLowScoreVideo = false;
  642. return;
  643. }
  644. if (this.isFollowUpQuestion) {
  645. console.log("追问问题视频播放完成");
  646. this.showStartRecordingButton = true;
  647. this.startCountdown();
  648. return;
  649. }
  650. if (this.currentVideoIndex >= 1) {
  651. this.showStartRecordingButton = true;
  652. this.startCountdown();
  653. } else {
  654. this.showAnswerButton = true;
  655. }
  656. if (this.isFollowUpQuestion) {
  657. this.isFollowUpQuestion = false;
  658. this.currentFollowUpQuestion = null;
  659. }
  660. },
  661. // 添加新方法:开始倒计时
  662. startCountdown() {
  663. this.showCountdown = true;
  664. this.countdownValue = 10;
  665. this.countdownTimer = setInterval(() => {
  666. this.countdownValue--;
  667. if (this.countdownValue <= 0) {
  668. this.clearCountdown();
  669. this.showStartRecordingButton = false;
  670. this.startRecordingAnswer();
  671. }
  672. }, 1e3);
  673. },
  674. // 添加新方法:清除倒计时
  675. clearCountdown() {
  676. if (this.countdownTimer) {
  677. clearInterval(this.countdownTimer);
  678. this.countdownTimer = null;
  679. }
  680. this.showCountdown = false;
  681. },
  682. // 修改 handleStartRecordingClick 方法,使其可以终止倒计时
  683. handleStartRecordingClick() {
  684. this.showStartRecordingButton = false;
  685. this.clearCountdown();
  686. this.startRecordingAnswer();
  687. },
  688. // 修改 stopRecordingAnswer 方法,添加录制时长检查
  689. stopRecordingAnswer() {
  690. this.clearCountdown();
  691. const recordingDuration = this.getRecordingDuration();
  692. const minimumDuration = 3;
  693. const lowScoreDuration = 7;
  694. if (recordingDuration < minimumDuration) {
  695. common_vendor.index.showToast({
  696. title: "录制时间过短,请至少录制3秒",
  697. icon: "none",
  698. duration: 2e3
  699. });
  700. return;
  701. }
  702. this.completeRecordingStop();
  703. if (recordingDuration < lowScoreDuration) {
  704. console.log(`录制时间 ${recordingDuration} 秒,少于 ${lowScoreDuration} 秒,将播放低分提示视频`);
  705. this.needPlayLowScoreVideo = true;
  706. } else {
  707. this.needPlayLowScoreVideo = false;
  708. }
  709. },
  710. // 添加新方法:开始录制用户回答
  711. startRecordingAnswer() {
  712. console.log("开始录制用户回答");
  713. this.isRecording = true;
  714. this.recordingStartTime = Date.now();
  715. this.recordingTimerCount = 0;
  716. this.remainingTime = this.maxRecordingTime;
  717. this.recordingTimer = setInterval(() => {
  718. this.recordingTimerCount++;
  719. this.remainingTime = Math.max(0, this.maxRecordingTime - this.recordingTimerCount);
  720. this.recordingTimeDisplay = this.formatTime(this.recordingTimerCount);
  721. this.progressPercent = this.recordingTimerCount / this.maxRecordingTime * 100;
  722. if (this.recordingTimerCount >= this.maxRecordingTime) {
  723. console.log("已达到最大录制时间(5分钟),自动停止录制");
  724. this.stopRecordingAnswer();
  725. }
  726. }, 1e3);
  727. const systemInfo = common_vendor.index.getSystemInfoSync();
  728. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith("mp-");
  729. if (isMiniProgram) {
  730. this.startMiniProgramRecording();
  731. } else {
  732. this.startBrowserRecording();
  733. }
  734. this.showStopRecordingButton = true;
  735. },
  736. // 添加一个新方法:重置相机组件
  737. resetCamera() {
  738. console.log("重置相机组件");
  739. this.useMiniProgramCameraComponent = false;
  740. if (this.cameraContext) {
  741. this.cameraContext = null;
  742. }
  743. setTimeout(() => {
  744. this.useMiniProgramCameraComponent = true;
  745. setTimeout(() => {
  746. this.cameraContext = common_vendor.index.createCameraContext();
  747. console.log("相机组件已重置");
  748. }, 500);
  749. }, 500);
  750. },
  751. // 修改 startMiniProgramRecording 方法
  752. startMiniProgramRecording() {
  753. console.log("开始小程序录制方法");
  754. const systemInfo = common_vendor.index.getSystemInfoSync();
  755. const isIOS = systemInfo.platform === "ios";
  756. if (isIOS) {
  757. this.resetCamera();
  758. setTimeout(() => {
  759. this.actualStartRecording(isIOS);
  760. }, 1e3);
  761. } else {
  762. this.actualStartRecording(isIOS);
  763. }
  764. },
  765. // 添加新方法:实际开始录制
  766. actualStartRecording(isIOS) {
  767. if (!this.cameraContext) {
  768. this.cameraContext = common_vendor.index.createCameraContext();
  769. console.log("创建新的相机上下文");
  770. }
  771. common_vendor.index.getSetting({
  772. success: (res) => {
  773. const hasRecordAuth = res.authSetting["scope.record"];
  774. const hasCameraAuth = res.authSetting["scope.camera"];
  775. if (!hasRecordAuth || !hasCameraAuth) {
  776. console.warn("缺少必要权限,请求权限");
  777. this.requestMiniProgramPermissions();
  778. return;
  779. }
  780. if (isIOS) {
  781. console.log("iOS: 检查相机状态");
  782. const options = {
  783. timeout: 3e5,
  784. // 300秒超时 (5分钟)
  785. quality: "low",
  786. // 降低质量
  787. compressed: true,
  788. success: () => {
  789. console.log("iOS录制开始成功");
  790. },
  791. fail: (err) => {
  792. console.error("iOS录制失败:", err);
  793. this.useAlternativeRecordingMethod();
  794. }
  795. };
  796. try {
  797. console.log("尝试开始录制");
  798. this.recorder = this.cameraContext.startRecord(options);
  799. } catch (e) {
  800. console.error("开始录制异常:", e);
  801. this.useAlternativeRecordingMethod();
  802. }
  803. } else {
  804. const options = {
  805. timeout: 3e5,
  806. // 300秒超时 (5分钟)
  807. quality: "medium",
  808. compressed: true,
  809. success: () => {
  810. console.log("Android录制开始成功");
  811. },
  812. fail: (err) => {
  813. console.error("Android录制失败:", err);
  814. common_vendor.index.showToast({
  815. title: "录制失败,请检查相机权限",
  816. icon: "none"
  817. });
  818. this.proceedToNextQuestion();
  819. }
  820. };
  821. this.recorder = this.cameraContext.startRecord(options);
  822. }
  823. }
  824. });
  825. },
  826. // 添加新方法:使用替代录制方法
  827. useAlternativeRecordingMethod() {
  828. console.log("使用替代录制方法");
  829. common_vendor.index.showActionSheet({
  830. itemList: ["使用相册中的视频", "跳过此问题"],
  831. success: (res) => {
  832. if (res.tapIndex === 0) {
  833. common_vendor.index.chooseVideo({
  834. sourceType: ["album"],
  835. maxDuration: 300,
  836. // 从60秒改为300秒
  837. camera: "front",
  838. success: (res2) => {
  839. console.log("选择视频成功:", res2.tempFilePath);
  840. this.isRecording = false;
  841. this.showStopRecordingButton = false;
  842. this.uploadRecordedVideo(res2.tempFilePath);
  843. },
  844. fail: () => {
  845. console.log("用户取消选择视频");
  846. this.proceedToNextQuestion();
  847. }
  848. });
  849. } else {
  850. console.log("用户选择跳过问题");
  851. this.proceedToNextQuestion();
  852. }
  853. },
  854. fail: () => {
  855. console.log("操作取消");
  856. this.proceedToNextQuestion();
  857. }
  858. });
  859. },
  860. // 添加新方法:请求小程序权限
  861. requestMiniProgramPermissions() {
  862. common_vendor.index.authorize({
  863. scope: "scope.record",
  864. success: () => {
  865. console.log("录音权限已获取");
  866. common_vendor.index.authorize({
  867. scope: "scope.camera",
  868. success: () => {
  869. console.log("相机权限已获取");
  870. this.startMiniProgramRecording();
  871. },
  872. fail: (err) => {
  873. console.error("相机权限获取失败:", err);
  874. this.showPermissionDialog("相机");
  875. }
  876. });
  877. },
  878. fail: (err) => {
  879. console.error("录音权限获取失败:", err);
  880. this.showPermissionDialog("录音");
  881. }
  882. });
  883. },
  884. // 修改浏览器环境下的录制方法
  885. startBrowserRecording() {
  886. if (!this.cameraStream) {
  887. console.error("没有可用的摄像头流");
  888. common_vendor.index.showToast({
  889. title: "录制失败,摄像头未就绪",
  890. icon: "none"
  891. });
  892. this.proceedToNextQuestion();
  893. return;
  894. }
  895. try {
  896. const hasAudio = this.cameraStream.getAudioTracks().length > 0;
  897. if (!hasAudio) {
  898. console.warn("警告:媒体流中没有音频轨道,尝试重新获取带音频的媒体流");
  899. navigator.mediaDevices.getUserMedia({
  900. audio: {
  901. echoCancellation: true,
  902. noiseSuppression: true,
  903. autoGainControl: true
  904. },
  905. video: true
  906. }).then((newStream) => {
  907. const audioTracks = newStream.getAudioTracks();
  908. if (audioTracks.length > 0) {
  909. console.log("成功获取音频轨道:", audioTracks[0].label);
  910. const videoTrack = this.cameraStream.getVideoTracks()[0];
  911. const audioTrack = newStream.getAudioTracks()[0];
  912. const combinedStream = new MediaStream();
  913. if (videoTrack)
  914. combinedStream.addTrack(videoTrack);
  915. if (audioTrack)
  916. combinedStream.addTrack(audioTrack);
  917. this.cameraStream = combinedStream;
  918. const videoElement = this.$refs.userCameraVideo;
  919. if (videoElement) {
  920. videoElement.srcObject = combinedStream;
  921. videoElement.muted = true;
  922. }
  923. this.setupMediaRecorder(combinedStream);
  924. } else {
  925. console.warn("仍然无法获取音频轨道");
  926. this.setupMediaRecorder(this.cameraStream);
  927. }
  928. }).catch((err) => {
  929. console.error("获取音频失败:", err);
  930. this.setupMediaRecorder(this.cameraStream);
  931. });
  932. } else {
  933. console.log("检测到音频轨道,直接使用");
  934. this.setupMediaRecorder(this.cameraStream);
  935. }
  936. } catch (error) {
  937. console.error("浏览器录制失败:", error);
  938. common_vendor.index.showToast({
  939. title: "录制失败,浏览器可能不支持此功能",
  940. icon: "none"
  941. });
  942. this.proceedToNextQuestion();
  943. }
  944. },
  945. // 修改 setupMediaRecorder 方法
  946. setupMediaRecorder(stream) {
  947. const videoTracks = stream.getVideoTracks();
  948. const audioTracks = stream.getAudioTracks();
  949. console.log("设置MediaRecorder - 视频轨道:", videoTracks.length, "音频轨道:", audioTracks.length);
  950. let mimeType = "";
  951. const supportedTypes = [
  952. "video/webm;codecs=vp9,opus",
  953. "video/webm;codecs=vp8,opus",
  954. "video/webm;codecs=h264,opus",
  955. "video/mp4;codecs=h264,aac",
  956. "video/webm",
  957. "video/mp4"
  958. ];
  959. for (const type of supportedTypes) {
  960. if (MediaRecorder.isTypeSupported(type)) {
  961. mimeType = type;
  962. console.log("使用支持的MIME类型:", mimeType);
  963. break;
  964. }
  965. }
  966. const options = {
  967. mimeType: mimeType || "",
  968. audioBitsPerSecond: 64e3,
  969. // 降低音频比特率
  970. videoBitsPerSecond: 1e6
  971. // 降低视频比特率到1Mbps
  972. };
  973. try {
  974. this.mediaRecorder = new MediaRecorder(stream, options);
  975. console.log("MediaRecorder创建成功,使用选项:", options);
  976. } catch (e) {
  977. console.warn("使用指定选项创建MediaRecorder失败,尝试使用默认选项");
  978. this.mediaRecorder = new MediaRecorder(stream);
  979. }
  980. this.recordedChunks = [];
  981. this.mediaRecorder.ondataavailable = (event) => {
  982. if (event.data && event.data.size > 0) {
  983. this.recordedChunks.push(event.data);
  984. console.log(`收到数据块: ${event.data.size} 字节`);
  985. }
  986. };
  987. this.mediaRecorder.onstop = async () => {
  988. console.log("MediaRecorder停止,数据块数量:", this.recordedChunks.length);
  989. if (this.recordedChunks.length === 0) {
  990. console.error("没有录制到数据");
  991. common_vendor.index.showToast({
  992. title: "录制失败,未捕获到数据",
  993. icon: "none"
  994. });
  995. this.proceedToNextQuestion();
  996. return;
  997. }
  998. const mimeType2 = this.mediaRecorder.mimeType || "video/webm";
  999. const blob = new Blob(this.recordedChunks, { type: mimeType2 });
  1000. console.log("创建Blob,原始大小:", blob.size, "类型:", mimeType2);
  1001. common_vendor.index.showLoading({
  1002. title: "正在处理视频...",
  1003. mask: true
  1004. });
  1005. try {
  1006. const compressedBlob = await this.compressVideo(blob);
  1007. const fileName = `answer_${this.currentVideoIndex}_${Date.now()}.webm`;
  1008. const file = new File([compressedBlob], fileName, { type: mimeType2 });
  1009. common_vendor.index.hideLoading();
  1010. this.uploadRecordedVideo(file);
  1011. } catch (error) {
  1012. console.error("视频处理失败:", error);
  1013. common_vendor.index.hideLoading();
  1014. const fileName = `answer_${this.currentVideoIndex}_${Date.now()}.webm`;
  1015. const file = new File([blob], fileName, { type: mimeType2 });
  1016. this.uploadRecordedVideo(file);
  1017. }
  1018. };
  1019. this.mediaRecorder.onerror = (event) => {
  1020. console.error("MediaRecorder错误:", event.error);
  1021. };
  1022. try {
  1023. this.mediaRecorder.start(1e3);
  1024. console.log("MediaRecorder开始录制");
  1025. this.mediaRecorderTimeout = setTimeout(() => {
  1026. if (this.mediaRecorder && this.mediaRecorder.state === "recording") {
  1027. console.log("MediaRecorder备份超时机制触发,停止录制");
  1028. this.mediaRecorder.stop();
  1029. }
  1030. }, 3e5);
  1031. } catch (e) {
  1032. console.error("开始录制失败:", e);
  1033. }
  1034. },
  1035. // 添加新方法:停止录制用户回答
  1036. stopRecordingAnswer() {
  1037. console.log("停止录制用户回答");
  1038. if (this.countdownTimer) {
  1039. clearInterval(this.countdownTimer);
  1040. this.countdownTimer = null;
  1041. this.showCountdown = false;
  1042. }
  1043. const recordingDuration = this.getRecordingDuration();
  1044. const minimumDuration = 3;
  1045. const lowScoreDuration = 7;
  1046. if (recordingDuration < minimumDuration) {
  1047. common_vendor.index.showToast({
  1048. title: "录制时间过短,请至少录制3秒",
  1049. icon: "none",
  1050. duration: 2e3
  1051. });
  1052. return;
  1053. }
  1054. this.completeRecordingStop();
  1055. if (recordingDuration < lowScoreDuration) {
  1056. console.log(`录制时间 ${recordingDuration} 秒,少于 ${lowScoreDuration} 秒,将播放低分提示视频`);
  1057. this.needPlayLowScoreVideo = true;
  1058. } else {
  1059. this.needPlayLowScoreVideo = false;
  1060. }
  1061. },
  1062. // 添加新方法:获取录制时长
  1063. getRecordingDuration() {
  1064. if (this.recordingStartTime) {
  1065. return (Date.now() - this.recordingStartTime) / 1e3;
  1066. }
  1067. if (this.mediaRecorder && this.$refs.userCameraVideo) {
  1068. return this.$refs.userCameraVideo.currentTime || 0;
  1069. }
  1070. if (this.recordingTimerCount) {
  1071. return this.recordingTimerCount;
  1072. }
  1073. return 0;
  1074. },
  1075. // 添加新方法:重置录制
  1076. resetRecording() {
  1077. if (this.recordingTimer) {
  1078. clearTimeout(this.recordingTimer);
  1079. }
  1080. this.recordingStartTime = Date.now();
  1081. this.recordingTimerCount = 0;
  1082. if (this.mediaRecorder && this.mediaRecorder.state !== "inactive") {
  1083. this.mediaRecorder.stop();
  1084. this.recordedChunks = [];
  1085. setTimeout(() => {
  1086. this.startBrowserRecording();
  1087. }, 500);
  1088. } else if (this.cameraContext) {
  1089. this.cameraContext.stopRecord({
  1090. success: () => {
  1091. console.log("相机录制已停止");
  1092. },
  1093. fail: (err) => {
  1094. console.error("停止相机录制失败:", err);
  1095. }
  1096. });
  1097. }
  1098. common_vendor.index.showToast({
  1099. title: "请重新开始回答",
  1100. icon: "none",
  1101. duration: 2e3
  1102. });
  1103. },
  1104. // 修改 completeRecordingStop 方法,确保正确处理追问问题ID
  1105. completeRecordingStop() {
  1106. console.log("完成录制停止");
  1107. if (this.recordingTimer) {
  1108. clearInterval(this.recordingTimer);
  1109. this.recordingTimer = null;
  1110. }
  1111. this.finalRecordingDuration = this.recordingTimerCount;
  1112. this.showStopRecordingButton = false;
  1113. this.isRecording = false;
  1114. const systemInfo = common_vendor.index.getSystemInfoSync();
  1115. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith("mp-");
  1116. if (isMiniProgram) {
  1117. this.stopMiniProgramRecording();
  1118. } else {
  1119. this.stopBrowserRecording();
  1120. }
  1121. if (this.isFollowUpQuestion && this.currentFollowUpQuestion) {
  1122. console.log("当前是追问问题,记录追问问题ID:", this.currentFollowUpQuestion.id);
  1123. this.lastQuestionWasFollowUp = true;
  1124. this.lastFollowUpQuestionId = this.currentFollowUpQuestion.id;
  1125. } else {
  1126. this.lastQuestionWasFollowUp = false;
  1127. this.lastFollowUpQuestionId = null;
  1128. }
  1129. },
  1130. // 修改 stopMiniProgramRecording 方法,确保正确传递追问问题ID
  1131. stopMiniProgramRecording() {
  1132. console.log("停止小程序录制");
  1133. if (!this.cameraContext) {
  1134. console.error("相机上下文不存在");
  1135. this.proceedToNextQuestion();
  1136. return;
  1137. }
  1138. this.cameraContext.stopRecord({
  1139. success: (res) => {
  1140. console.log("小程序录制停止成功:", res);
  1141. const videoPath = res.tempVideoPath;
  1142. if (videoPath) {
  1143. this.uploadRecordedVideo(videoPath);
  1144. } else {
  1145. console.error("未获取到录制视频路径");
  1146. this.proceedToNextQuestion();
  1147. }
  1148. },
  1149. fail: (err) => {
  1150. console.error("小程序录制停止失败:", err);
  1151. this.proceedToNextQuestion();
  1152. }
  1153. });
  1154. },
  1155. // 添加新方法:停止浏览器录制
  1156. stopBrowserRecording() {
  1157. if (this.mediaRecorder && this.mediaRecorder.state !== "inactive") {
  1158. this.mediaRecorder.stop();
  1159. console.log("浏览器录制停止成功");
  1160. } else {
  1161. console.error("MediaRecorder不存在或已经停止");
  1162. this.proceedToNextQuestion();
  1163. }
  1164. },
  1165. // 修改 uploadRecordedVideo 方法,添加记录父问题ID的逻辑
  1166. uploadRecordedVideo(fileOrPath) {
  1167. console.log("准备上传视频:", typeof fileOrPath === "string" ? fileOrPath : fileOrPath.name);
  1168. console.log("当前问题ID:", this.currentParentQuestionId);
  1169. console.log("当前问题类型:", this.isFollowUpQuestion);
  1170. console.log("当前追问问题:", this.currentFollowUpQuestion);
  1171. let questionId;
  1172. let isFollowUpQuestionUpload = false;
  1173. let questionText = "";
  1174. let questionForm = 0;
  1175. if (this.currentFollowUpQuestion && (this.currentFollowUpQuestion.question_form === 5 || this.isFollowUpQuestion)) {
  1176. questionId = this.currentFollowUpQuestion.id;
  1177. isFollowUpQuestionUpload = true;
  1178. questionText = this.currentFollowUpQuestion.question || "";
  1179. questionForm = 5;
  1180. console.log("正在上传追问问题的回答:", {
  1181. questionId,
  1182. questionText,
  1183. questionForm,
  1184. isFollowUp: true
  1185. });
  1186. } else {
  1187. const currentQuestion = this.getCurrentQuestionByIndex(this.currentVideoIndex);
  1188. if (currentQuestion && currentQuestion.id) {
  1189. questionId = currentQuestion.id;
  1190. questionText = currentQuestion.question || "";
  1191. console.log("正在上传常规问题的回答:", {
  1192. questionId,
  1193. questionText,
  1194. questionForm: 0
  1195. });
  1196. } else {
  1197. questionId = this.getDefaultQuestionId(this.currentVideoIndex);
  1198. console.log("使用默认问题ID:", questionId);
  1199. }
  1200. }
  1201. const uploadTask = {
  1202. id: Date.now().toString(),
  1203. file: fileOrPath,
  1204. questionId,
  1205. isFollowUp: isFollowUpQuestionUpload,
  1206. questionText,
  1207. questionForm,
  1208. attempts: 0,
  1209. maxAttempts: 3,
  1210. parentQuestionId: this.currentParentQuestionId
  1211. // 添加父问题ID
  1212. };
  1213. if (!isFollowUpQuestionUpload) {
  1214. this.currentParentQuestionId = questionId;
  1215. }
  1216. this.uploadQueue.push(uploadTask);
  1217. this.uploadProgress[uploadTask.id] = 0;
  1218. this.uploadStatus[uploadTask.id] = "pending";
  1219. common_vendor.index.showToast({
  1220. title: "已完成回答",
  1221. icon: "none",
  1222. duration: 1500
  1223. });
  1224. this.updateUploadStatusText();
  1225. if (!this.isUploading) {
  1226. this.processUploadQueue();
  1227. }
  1228. this.handlePostUploadActions(uploadTask);
  1229. },
  1230. // 添加新方法:处理上传后的逻辑
  1231. handlePostUploadActions(task) {
  1232. if (this.needPlayLowScoreVideo && this.retryCount < 1) {
  1233. this.playLowScoreVideo();
  1234. this.needPlayLowScoreVideo = false;
  1235. } else {
  1236. if (task.isFollowUp) {
  1237. console.log("追问问题回答完成,进入下一个问题");
  1238. this.retryCount = 0;
  1239. this.isFollowUpQuestion = false;
  1240. this.currentFollowUpQuestion = null;
  1241. this.proceedToNextQuestion();
  1242. } else {
  1243. this.currentParentQuestionId = task.questionId;
  1244. console.log("检查常规问题的追问,父问题ID:", this.currentParentQuestionId);
  1245. this.checkAndPlayFollowUpQuestion(this.currentParentQuestionId);
  1246. }
  1247. }
  1248. },
  1249. // 修改 processUploadQueue 方法
  1250. processUploadQueue() {
  1251. if (this.uploadQueue.length === 0) {
  1252. this.isUploading = false;
  1253. this.showUploadStatus = false;
  1254. return;
  1255. }
  1256. this.isUploading = true;
  1257. this.showUploadStatus = true;
  1258. const task = this.uploadQueue[0];
  1259. this.uploadStatus[task.id] = "uploading";
  1260. this.updateUploadStatusText();
  1261. task.attempts++;
  1262. if (typeof task.file === "string") {
  1263. this.uploadFileWithUni(task);
  1264. } else {
  1265. this.uploadFileWithXHR(task);
  1266. }
  1267. },
  1268. // 添加新方法:使用XMLHttpRequest上传文件
  1269. uploadFileWithXHR(task) {
  1270. const userInfo = common_vendor.index.getStorageSync("userInfo");
  1271. const openid = userInfo ? JSON.parse(userInfo).openid || "" : "";
  1272. const tenant_id = JSON.parse(common_vendor.index.getStorageSync("userInfo")).tenant_id || "1";
  1273. const formData = new FormData();
  1274. formData.append("file", task.file);
  1275. formData.append("openid", openid);
  1276. formData.append("tenant_id", tenant_id);
  1277. formData.append("application_id", common_vendor.index.getStorageSync("appId"));
  1278. formData.append("question_id", task.questionId);
  1279. formData.append("video_duration", 0);
  1280. formData.append("has_audio", "true");
  1281. const xhr = new XMLHttpRequest();
  1282. xhr.open("POST", `${common_config.apiBaseUrl}/api/upload/`, true);
  1283. xhr.timeout = 12e4;
  1284. xhr.upload.onprogress = (event) => {
  1285. if (event.lengthComputable) {
  1286. const percentComplete = Math.round(event.loaded / event.total * 100);
  1287. this.uploadProgress[task.id] = percentComplete;
  1288. this.updateUploadStatusText();
  1289. }
  1290. };
  1291. xhr.onload = () => {
  1292. if (xhr.status === 200) {
  1293. try {
  1294. const res = JSON.parse(xhr.responseText);
  1295. console.log("上传响应:", res);
  1296. if (res.code === 2e3) {
  1297. const videoUrl = res.data.url || res.data.photoUrl || "";
  1298. if (videoUrl) {
  1299. this.uploadStatus[task.id] = "success";
  1300. this.updateUploadStatusText();
  1301. this.submitVideoToInterview(videoUrl, task);
  1302. } else {
  1303. this.handleUploadFailure(task, "视频URL获取失败");
  1304. }
  1305. } else {
  1306. this.handleUploadFailure(task, res.msg || "上传失败");
  1307. }
  1308. } catch (e) {
  1309. this.handleUploadFailure(task, "解析响应失败");
  1310. }
  1311. } else {
  1312. this.handleUploadFailure(task, "HTTP状态: " + xhr.status);
  1313. }
  1314. };
  1315. xhr.onerror = () => {
  1316. this.handleUploadFailure(task, "网络错误");
  1317. };
  1318. xhr.ontimeout = () => {
  1319. this.handleUploadFailure(task, "上传超时");
  1320. };
  1321. xhr.send(formData);
  1322. },
  1323. // 添加新方法:使用uni.uploadFile上传文件
  1324. uploadFileWithUni(task) {
  1325. const userInfo = common_vendor.index.getStorageSync("userInfo");
  1326. const openid = userInfo ? JSON.parse(userInfo).openid || "" : "";
  1327. const tenant_id = JSON.parse(common_vendor.index.getStorageSync("userInfo")).tenant_id || "1";
  1328. const uploadTask = common_vendor.index.uploadFile({
  1329. url: `${common_config.apiBaseUrl}/api/upload/`,
  1330. filePath: task.file,
  1331. name: "file",
  1332. formData: {
  1333. openid,
  1334. tenant_id,
  1335. application_id: common_vendor.index.getStorageSync("appId"),
  1336. question_id: task.questionId,
  1337. video_duration: 0,
  1338. has_audio: "true"
  1339. },
  1340. success: (uploadRes) => {
  1341. try {
  1342. const res = JSON.parse(uploadRes.data);
  1343. console.log("上传响应:", res);
  1344. if (res.code === 2e3) {
  1345. const videoUrl = res.data.permanent_link || res.data.url || "";
  1346. if (videoUrl) {
  1347. this.uploadStatus[task.id] = "success";
  1348. this.updateUploadStatusText();
  1349. this.submitVideoToInterview(videoUrl, task);
  1350. } else {
  1351. this.handleUploadFailure(task, "视频URL获取失败");
  1352. }
  1353. } else {
  1354. this.handleUploadFailure(task, res.msg || "上传失败");
  1355. }
  1356. } catch (e) {
  1357. this.handleUploadFailure(task, "解析响应失败");
  1358. }
  1359. },
  1360. fail: (err) => {
  1361. this.handleUploadFailure(task, err.errMsg || "上传失败");
  1362. }
  1363. });
  1364. uploadTask.onProgressUpdate((res) => {
  1365. this.uploadProgress[task.id] = res.progress;
  1366. this.updateUploadStatusText();
  1367. });
  1368. },
  1369. // 添加新方法:处理上传失败
  1370. handleUploadFailure(task, errorMsg) {
  1371. console.error("上传失败:", errorMsg);
  1372. this.uploadStatus[task.id] = "failed";
  1373. this.updateUploadStatusText();
  1374. if (task.attempts < task.maxAttempts) {
  1375. console.log(`将在5秒后重试上传,当前尝试次数: ${task.attempts}/${task.maxAttempts}`);
  1376. setTimeout(() => {
  1377. this.uploadProgress[task.id] = 0;
  1378. if (typeof task.file !== "string") {
  1379. this.uploadFileWithXHR(task);
  1380. } else {
  1381. this.uploadFileWithUni(task);
  1382. }
  1383. }, 5e3);
  1384. } else {
  1385. console.log("超过最大重试次数,放弃上传");
  1386. common_vendor.index.showToast({
  1387. title: "视频上传失败,请稍后重试",
  1388. icon: "none",
  1389. duration: 2e3
  1390. });
  1391. this.uploadQueue.shift();
  1392. this.processUploadQueue();
  1393. }
  1394. },
  1395. // 修改 submitVideoToInterview 方法
  1396. submitVideoToInterview(videoUrl, task) {
  1397. const requestData = {
  1398. application_id: common_vendor.index.getStorageSync("appId"),
  1399. question_id: task.questionId,
  1400. video_url: videoUrl,
  1401. tenant_id: JSON.parse(common_vendor.index.getStorageSync("userInfo")).tenant_id || "1",
  1402. is_follow_up: task.isFollowUp ? 1 : 0,
  1403. question_form: task.questionForm,
  1404. question_text: task.questionText
  1405. };
  1406. common_vendor.index.request({
  1407. url: `${common_config.apiBaseUrl}/api/job/upload_video`,
  1408. method: "POST",
  1409. data: requestData,
  1410. header: {
  1411. "content-type": "application/x-www-form-urlencoded"
  1412. },
  1413. success: (res) => {
  1414. if (res.data.code === 200 || res.data.code === 2e3) {
  1415. this.uploadQueue.shift();
  1416. this.processUploadQueue();
  1417. } else {
  1418. this.handleUploadError(task, "提交失败: " + (res.data.msg || "未知错误"));
  1419. }
  1420. },
  1421. fail: (err) => {
  1422. this.handleUploadError(task, "网络错误: " + err.errMsg);
  1423. }
  1424. });
  1425. },
  1426. // 添加新方法:处理提交失败
  1427. handleSubmitFailure(task, errorMsg) {
  1428. console.error("提交失败:", errorMsg);
  1429. this.uploadStatus[task.id] = "failed";
  1430. this.updateUploadStatusText();
  1431. if (task.attempts < task.maxAttempts) {
  1432. console.log(`将在5秒后重试提交,当前尝试次数: ${task.attempts}/${task.maxAttempts}`);
  1433. setTimeout(() => {
  1434. this.submitVideoToInterview(task.videoUrl, task);
  1435. }, 5e3);
  1436. } else {
  1437. console.log("超过最大重试次数,放弃提交");
  1438. common_vendor.index.showToast({
  1439. title: "视频提交失败,请稍后重试",
  1440. icon: "none",
  1441. duration: 2e3
  1442. });
  1443. this.uploadQueue.shift();
  1444. this.processUploadQueue();
  1445. }
  1446. },
  1447. // 添加新方法:更新上传状态文本
  1448. updateUploadStatusText() {
  1449. if (this.uploadQueue.length === 0) {
  1450. this.uploadStatusText = "";
  1451. return;
  1452. }
  1453. const currentTask = this.uploadQueue[0];
  1454. const progress = this.uploadProgress[currentTask.id] || 0;
  1455. const status = this.uploadStatus[currentTask.id] || "pending";
  1456. let statusText = "";
  1457. switch (status) {
  1458. case "pending":
  1459. statusText = "等待上传";
  1460. break;
  1461. case "uploading":
  1462. statusText = `上传中 ${progress}%`;
  1463. break;
  1464. case "success":
  1465. statusText = "上传成功,提交中...";
  1466. break;
  1467. case "failed":
  1468. statusText = `上传失败,${currentTask.attempts < currentTask.maxAttempts ? "即将重试" : "已放弃"}`;
  1469. break;
  1470. }
  1471. const questionTypeText = currentTask.isFollowUp ? "追问" : "问题";
  1472. const questionShortText = currentTask.questionText ? currentTask.questionText.length > 10 ? currentTask.questionText.substring(0, 10) + "..." : currentTask.questionText : `${questionTypeText}${currentTask.questionId}`;
  1473. this.uploadStatusText = `${questionTypeText}「${questionShortText}」:${statusText}`;
  1474. if (this.uploadQueue.length > 1) {
  1475. this.uploadStatusText += ` (${this.uploadQueue.length}个视频待处理)`;
  1476. }
  1477. },
  1478. // 修改 proceedToNextQuestion 方法,确保在切换视频时重置历史时间
  1479. proceedToNextQuestion() {
  1480. console.log("继续下一个问题");
  1481. this.currentVideoIndex++;
  1482. this.historyTime = 0;
  1483. if (this.currentVideoIndex < this.videoList.length) {
  1484. this.videoUrl = this.videoList[this.currentVideoIndex];
  1485. this.videoPlaying = true;
  1486. this.$nextTick(() => {
  1487. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  1488. if (videoContext) {
  1489. videoContext.play();
  1490. }
  1491. });
  1492. } else {
  1493. console.log("所有视频已播放完毕");
  1494. this.stopUserCamera();
  1495. this.clearCountdown();
  1496. const currentJobDetail = JSON.parse(common_vendor.index.getStorageSync("selectedJob"));
  1497. console.log("当前职位ID:", currentJobDetail);
  1498. const jobId = currentJobDetail ? currentJobDetail.id : null;
  1499. console.log("当前职位ID:", jobId);
  1500. setTimeout(() => {
  1501. if (jobId === 9) {
  1502. common_vendor.index.navigateTo({
  1503. url: "/pages/interview-question/interview-question",
  1504. success: () => {
  1505. console.log("成功跳转到interview-question页面");
  1506. },
  1507. fail: (err) => {
  1508. console.error("跳转到interview-question页面失败:", err);
  1509. common_vendor.index.redirectTo({
  1510. url: "/pages/interview-question/interview-question",
  1511. fail: (redirectErr) => {
  1512. console.error("重定向到interview-question页面也失败:", redirectErr);
  1513. common_vendor.index.navigateBack({
  1514. delta: 1
  1515. });
  1516. }
  1517. });
  1518. }
  1519. });
  1520. } else {
  1521. common_vendor.index.navigateTo({
  1522. url: "/pages/camera/camera",
  1523. success: () => {
  1524. console.log("成功跳转到camera页面");
  1525. },
  1526. fail: (err) => {
  1527. console.error("跳转到camera页面失败:", err);
  1528. common_vendor.index.redirectTo({
  1529. url: "/pages/camera/camera",
  1530. fail: (redirectErr) => {
  1531. console.error("重定向到camera页面也失败:", redirectErr);
  1532. common_vendor.index.switchTab({
  1533. url: "/pages/camera/camera",
  1534. fail: (switchErr) => {
  1535. console.error("所有跳转方式都失败:", switchErr);
  1536. common_vendor.index.navigateBack({
  1537. delta: 1
  1538. });
  1539. }
  1540. });
  1541. }
  1542. });
  1543. }
  1544. });
  1545. }
  1546. }, 2e3);
  1547. }
  1548. },
  1549. // 修改 handleAnswerButtonClick 方法,确保在切换视频时重置历史时间
  1550. handleAnswerButtonClick() {
  1551. console.log("点击开始回答按钮");
  1552. this.showAnswerButton = false;
  1553. this.currentVideoIndex++;
  1554. this.historyTime = 0;
  1555. if (this.currentVideoIndex < this.videoList.length) {
  1556. this.videoUrl = this.videoList[this.currentVideoIndex];
  1557. this.videoPlaying = true;
  1558. this.$nextTick(() => {
  1559. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  1560. if (videoContext) {
  1561. videoContext.play();
  1562. }
  1563. });
  1564. }
  1565. },
  1566. // 处理相机错误
  1567. handleCameraError(e) {
  1568. console.error("相机错误:", e);
  1569. const systemInfo = common_vendor.index.getSystemInfoSync();
  1570. const isIOS = systemInfo.platform === "ios";
  1571. if (isIOS) {
  1572. console.log("iOS相机错误,尝试重新初始化");
  1573. common_vendor.index.showToast({
  1574. title: "相机初始化中...",
  1575. icon: "loading",
  1576. duration: 2e3
  1577. });
  1578. this.resetCamera();
  1579. if (this.isRecording) {
  1580. this.isRecording = false;
  1581. this.showStopRecordingButton = false;
  1582. setTimeout(() => {
  1583. this.useAlternativeRecordingMethod();
  1584. }, 1e3);
  1585. }
  1586. } else {
  1587. common_vendor.index.showToast({
  1588. title: "相机初始化失败,请检查权限设置",
  1589. icon: "none"
  1590. });
  1591. this.tryFallbackOptions();
  1592. }
  1593. },
  1594. // 添加新方法:尝试备用选项
  1595. tryFallbackOptions() {
  1596. const systemInfo = common_vendor.index.getSystemInfoSync();
  1597. if (systemInfo.uniPlatform === "mp-weixin" || systemInfo.uniPlatform === "mp-alipay") {
  1598. this.useMiniProgramCamera();
  1599. } else {
  1600. this.showStaticCameraPlaceholder();
  1601. }
  1602. },
  1603. // 添加新方法:使用小程序相机API
  1604. useMiniProgramCamera() {
  1605. console.log("尝试使用小程序相机组件");
  1606. this.useMiniProgramCameraComponent = true;
  1607. },
  1608. // 添加新方法:显示静态图像
  1609. showStaticCameraPlaceholder() {
  1610. console.log("显示静态摄像头占位图");
  1611. const img = document.createElement("img");
  1612. img.src = "/static/images/camera-placeholder.png";
  1613. img.className = "static-camera-image";
  1614. img.style.width = "100%";
  1615. img.style.height = "100%";
  1616. img.style.objectFit = "cover";
  1617. const container = this.$refs.userCameraVideo.parentNode;
  1618. container.appendChild(img);
  1619. },
  1620. // 修改 handleTimeUpdate 方法
  1621. handleTimeUpdate(e) {
  1622. const currentTime = e.detail.currentTime || e.target.currentTime;
  1623. if (this.isRecording && this.recordingTimerCount) {
  1624. this.recordingTimeDisplay = this.formatTime(this.recordingTimerCount);
  1625. }
  1626. if (this.isPlayingLowScoreVideo) {
  1627. if (this.lowScoreVideoSubtitles && this.lowScoreVideoSubtitles.length > 0) {
  1628. const subtitle = this.lowScoreVideoSubtitles[0];
  1629. this.currentSubtitle = subtitle.text;
  1630. }
  1631. return;
  1632. }
  1633. let currentSubtitles = null;
  1634. if (this.isFollowUpQuestion && this.currentFollowUpQuestion) {
  1635. const subtitleKey = `followUpSubtitles_${this.currentFollowUpQuestion.id}`;
  1636. currentSubtitles = this[subtitleKey] || [{
  1637. startTime: 0,
  1638. endTime: 30,
  1639. text: this.currentFollowUpQuestion.digital_human_video_subtitle || this.currentFollowUpQuestion.question
  1640. }];
  1641. } else {
  1642. if (this.currentVideoIndex === 0) {
  1643. currentSubtitles = this.subtitles;
  1644. } else {
  1645. const subtitleArrayName = `question${this.currentVideoIndex}Subtitles`;
  1646. currentSubtitles = this[subtitleArrayName];
  1647. }
  1648. }
  1649. if (currentSubtitles && currentSubtitles.length > 0) {
  1650. const subtitle = currentSubtitles.find(
  1651. (sub) => currentTime >= sub.startTime && currentTime <= sub.endTime
  1652. ) || currentSubtitles[0];
  1653. if (subtitle) {
  1654. this.currentSubtitle = subtitle.text;
  1655. }
  1656. }
  1657. this.historyTime = currentTime;
  1658. this.lastUpdateTime = Date.now();
  1659. },
  1660. // Add a new method to handle the "Start Recording" button click
  1661. handleStartRecordingClick() {
  1662. this.showStartRecordingButton = false;
  1663. this.clearCountdown();
  1664. this.startRecordingAnswer();
  1665. },
  1666. // 修改 checkAudioPermission 方法,确保在录制前获取音频权限
  1667. checkAudioPermission() {
  1668. const systemInfo = common_vendor.index.getSystemInfoSync();
  1669. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith("mp-");
  1670. if (isMiniProgram) {
  1671. common_vendor.index.getSetting({
  1672. success: (res) => {
  1673. if (!res.authSetting["scope.record"]) {
  1674. common_vendor.index.authorize({
  1675. scope: "scope.record",
  1676. success: () => {
  1677. console.log("录音权限已获取");
  1678. },
  1679. fail: (err) => {
  1680. console.error("录音权限获取失败:", err);
  1681. this.showPermissionDialog("录音");
  1682. }
  1683. });
  1684. }
  1685. if (!res.authSetting["scope.camera"]) {
  1686. common_vendor.index.authorize({
  1687. scope: "scope.camera",
  1688. success: () => {
  1689. console.log("相机权限已获取");
  1690. },
  1691. fail: (err) => {
  1692. console.error("相机权限获取失败:", err);
  1693. this.showPermissionDialog("相机");
  1694. }
  1695. });
  1696. }
  1697. }
  1698. });
  1699. }
  1700. },
  1701. // 添加新方法:测试音频输入
  1702. testAudioInput() {
  1703. if (!this.cameraStream) {
  1704. console.warn("没有可用的媒体流,无法测试音频");
  1705. return;
  1706. }
  1707. const audioTracks = this.cameraStream.getAudioTracks();
  1708. if (audioTracks.length === 0) {
  1709. console.warn("没有检测到音频轨道,尝试重新获取");
  1710. this.tryGetAudioOnly();
  1711. return;
  1712. }
  1713. console.log("音频轨道信息:", audioTracks[0].getSettings());
  1714. try {
  1715. const AudioContext = window.AudioContext || window.webkitAudioContext;
  1716. if (!AudioContext) {
  1717. console.warn("浏览器不支持AudioContext");
  1718. return;
  1719. }
  1720. const audioContext = new AudioContext();
  1721. const analyser = audioContext.createAnalyser();
  1722. const microphone = audioContext.createMediaStreamSource(this.cameraStream);
  1723. microphone.connect(analyser);
  1724. analyser.fftSize = 256;
  1725. const bufferLength = analyser.frequencyBinCount;
  1726. const dataArray = new Uint8Array(bufferLength);
  1727. let silenceCounter = 0;
  1728. const checkAudio = () => {
  1729. if (this.isRecording)
  1730. return;
  1731. analyser.getByteFrequencyData(dataArray);
  1732. let sum = 0;
  1733. for (let i = 0; i < bufferLength; i++) {
  1734. sum += dataArray[i];
  1735. }
  1736. const average = sum / bufferLength;
  1737. if (average > 10) {
  1738. console.log("检测到音频输入,音量:", average);
  1739. silenceCounter = 0;
  1740. } else {
  1741. silenceCounter++;
  1742. if (silenceCounter > 10) {
  1743. console.warn("持续检测不到音频输入,可能麦克风未正常工作");
  1744. silenceCounter = 0;
  1745. }
  1746. }
  1747. requestAnimationFrame(checkAudio);
  1748. };
  1749. checkAudio();
  1750. } catch (e) {
  1751. console.error("音频测试失败:", e);
  1752. }
  1753. },
  1754. // 添加新方法:尝试单独获取音频
  1755. tryGetAudioOnly() {
  1756. navigator.mediaDevices.getUserMedia({ audio: true }).then((audioStream) => {
  1757. if (this.cameraStream) {
  1758. const videoTrack = this.cameraStream.getVideoTracks()[0];
  1759. const audioTrack = audioStream.getAudioTracks()[0];
  1760. const combinedStream = new MediaStream();
  1761. if (videoTrack)
  1762. combinedStream.addTrack(videoTrack);
  1763. if (audioTrack)
  1764. combinedStream.addTrack(audioTrack);
  1765. this.cameraStream = combinedStream;
  1766. const videoElement = this.$refs.userCameraVideo;
  1767. if (videoElement) {
  1768. videoElement.srcObject = combinedStream;
  1769. videoElement.muted = true;
  1770. }
  1771. console.log("成功合并音频和视频轨道");
  1772. } else {
  1773. console.warn("没有视频流可合并");
  1774. }
  1775. }).catch((err) => {
  1776. console.error("单独获取音频失败:", err);
  1777. });
  1778. },
  1779. // 添加新方法:显示权限对话框
  1780. showPermissionDialog(permissionType) {
  1781. common_vendor.index.showModal({
  1782. title: "需要权限",
  1783. content: `请允许使用${permissionType}权限,否则可能影响面试功能`,
  1784. confirmText: "去设置",
  1785. success: (res) => {
  1786. if (res.confirm) {
  1787. common_vendor.index.openSetting({
  1788. success: (settingRes) => {
  1789. console.log("设置页面打开成功", settingRes);
  1790. }
  1791. });
  1792. }
  1793. }
  1794. });
  1795. },
  1796. // 添加重试上传方法
  1797. retryVideoUpload() {
  1798. if (this.lastVideoToRetry) {
  1799. this.showRetryButton = false;
  1800. common_vendor.index.showLoading({
  1801. title: "正在重新提交...",
  1802. mask: true
  1803. });
  1804. this.submitVideoToInterview(this.lastVideoToRetry);
  1805. } else {
  1806. common_vendor.index.showToast({
  1807. title: "没有可重试的视频",
  1808. icon: "none"
  1809. });
  1810. }
  1811. },
  1812. // 添加一个新方法用于压缩视频
  1813. async compressVideo(videoBlob) {
  1814. if (videoBlob.size < 5 * 1024 * 1024) {
  1815. return videoBlob;
  1816. }
  1817. console.log("开始压缩视频,原始大小:", videoBlob.size);
  1818. const videoElement = document.createElement("video");
  1819. videoElement.muted = true;
  1820. videoElement.autoplay = false;
  1821. const canvas = document.createElement("canvas");
  1822. const ctx = canvas.getContext("2d");
  1823. videoElement.src = URL.createObjectURL(videoBlob);
  1824. return new Promise((resolve) => {
  1825. videoElement.onloadedmetadata = () => {
  1826. const width = Math.floor(videoElement.videoWidth / 2);
  1827. const height = Math.floor(videoElement.videoHeight / 2);
  1828. canvas.width = width;
  1829. canvas.height = height;
  1830. const stream = canvas.captureStream(15);
  1831. if (videoElement.captureStream) {
  1832. const originalStream = videoElement.captureStream();
  1833. const audioTracks = originalStream.getAudioTracks();
  1834. if (audioTracks.length > 0) {
  1835. stream.addTrack(audioTracks[0]);
  1836. }
  1837. }
  1838. const options = {
  1839. mimeType: "video/webm;codecs=vp8,opus",
  1840. audioBitsPerSecond: 64e3,
  1841. videoBitsPerSecond: 8e5
  1842. // 800kbps
  1843. };
  1844. const mediaRecorder = new MediaRecorder(stream, options);
  1845. const chunks = [];
  1846. mediaRecorder.ondataavailable = (e) => {
  1847. if (e.data.size > 0) {
  1848. chunks.push(e.data);
  1849. }
  1850. };
  1851. mediaRecorder.onstop = () => {
  1852. const compressedBlob = new Blob(chunks, { type: "video/webm" });
  1853. console.log("视频压缩完成,压缩后大小:", compressedBlob.size);
  1854. resolve(compressedBlob);
  1855. };
  1856. videoElement.onplay = () => {
  1857. mediaRecorder.start(10);
  1858. const drawFrame = () => {
  1859. if (videoElement.paused || videoElement.ended) {
  1860. mediaRecorder.stop();
  1861. return;
  1862. }
  1863. ctx.drawImage(videoElement, 0, 0, width, height);
  1864. requestAnimationFrame(drawFrame);
  1865. };
  1866. drawFrame();
  1867. };
  1868. videoElement.play();
  1869. };
  1870. });
  1871. },
  1872. // 修改 checkIOSCameraRecordPermission 方法
  1873. checkIOSCameraRecordPermission() {
  1874. const systemInfo = common_vendor.index.getSystemInfoSync();
  1875. if (systemInfo.platform !== "ios")
  1876. return;
  1877. common_vendor.index.getSetting({
  1878. success: (res) => {
  1879. if (!res.authSetting["scope.camera"]) {
  1880. common_vendor.index.authorize({
  1881. scope: "scope.camera",
  1882. success: () => {
  1883. console.log("iOS相机权限已获取");
  1884. },
  1885. fail: (err) => {
  1886. console.error("iOS相机权限获取失败:", err);
  1887. this.showPermissionDialog("相机");
  1888. }
  1889. });
  1890. }
  1891. if (!res.authSetting["scope.record"]) {
  1892. common_vendor.index.authorize({
  1893. scope: "scope.record",
  1894. success: () => {
  1895. console.log("iOS录音权限已获取");
  1896. },
  1897. fail: (err) => {
  1898. console.error("iOS录音权限获取失败:", err);
  1899. this.showPermissionDialog("录音");
  1900. }
  1901. });
  1902. }
  1903. }
  1904. });
  1905. },
  1906. // 添加新方法:检查并修复渲染问题
  1907. checkAndFixRenderingIssues() {
  1908. try {
  1909. if (typeof u !== "undefined" && u) {
  1910. if (!u.currentQuestion) {
  1911. console.log("修复: 创建缺失的currentQuestion对象");
  1912. u.currentQuestion = {};
  1913. }
  1914. if (u.currentQuestion && typeof u.currentQuestion.isImportant === "undefined") {
  1915. console.log("修复: 设置缺失的isImportant属性");
  1916. u.currentQuestion.isImportant = false;
  1917. }
  1918. }
  1919. } catch (e) {
  1920. console.log("防御性检查异常:", e);
  1921. }
  1922. },
  1923. // 添加格式化时间的辅助方法
  1924. formatTime(seconds) {
  1925. if (!seconds && seconds !== 0)
  1926. return "03:30";
  1927. const minutes = Math.floor(seconds / 60);
  1928. const remainingSeconds = seconds % 60;
  1929. return `${minutes.toString().padStart(2, "0")}:${remainingSeconds.toString().padStart(2, "0")}`;
  1930. },
  1931. // 添加获取问题数据的方法
  1932. fetchQuestions() {
  1933. this.loading = true;
  1934. const tenant_id = JSON.parse(common_vendor.index.getStorageSync("userInfo")).tenant_id || "1";
  1935. let position_id = 1;
  1936. try {
  1937. const selectedJob = JSON.parse(common_vendor.index.getStorageSync("selectedJob") || "{}");
  1938. if (selectedJob && selectedJob.id) {
  1939. position_id = selectedJob.id;
  1940. console.log("使用选择的职位ID获取问题:", position_id);
  1941. } else {
  1942. console.warn("未找到选择的职位信息,使用默认职位ID:", position_id);
  1943. }
  1944. } catch (e) {
  1945. console.error("解析职位信息失败:", e);
  1946. }
  1947. const timestamp = Date.now();
  1948. const requestUrl = `${common_config.apiBaseUrl}/api/wechat/open_questions/?position_id=${position_id}&tenant_id=${tenant_id}&question_form=0&_t=${timestamp}`;
  1949. console.log("完整的请求URL:", requestUrl);
  1950. common_vendor.index.request({
  1951. url: requestUrl,
  1952. method: "GET",
  1953. success: (res) => {
  1954. if (res.data && res.data.code === 2e3 && res.data.data && res.data.data.items) {
  1955. console.log("获取问题数据成功:", res.data.data.items);
  1956. this.questions = res.data.data.items;
  1957. this.processQuestionData();
  1958. this.playIntroVideo();
  1959. } else {
  1960. console.error("获取问题数据失败:", res.data);
  1961. common_vendor.index.showToast({
  1962. title: "获取问题数据失败",
  1963. icon: "none"
  1964. });
  1965. }
  1966. },
  1967. fail: (err) => {
  1968. console.error("请求问题数据失败:", err);
  1969. common_vendor.index.showToast({
  1970. title: "网络错误,请检查网络连接",
  1971. icon: "none"
  1972. });
  1973. },
  1974. complete: () => {
  1975. this.loading = false;
  1976. }
  1977. });
  1978. },
  1979. // 处理问题数据,提取视频URL和字幕
  1980. processQuestionData() {
  1981. this.videoList = [];
  1982. this.videoList.push(this.introVideoUrl);
  1983. this.subtitles = [
  1984. {
  1985. startTime: 0,
  1986. endTime: 5,
  1987. text: "你好,我是本次面试的面试官,欢迎参加本公司的线上面试!"
  1988. },
  1989. {
  1990. startTime: 5,
  1991. endTime: 13,
  1992. text: "面试预计需要15分钟,请你提前安排在网络良好、光线亮度合适、且相对安静的环境参加这次面试"
  1993. },
  1994. {
  1995. startTime: 13,
  1996. endTime: 20,
  1997. text: "以免影响本次面试的结果。如果你在面试过程中遇到问题,请与我们的招聘人员联系。"
  1998. }
  1999. ];
  2000. const sortedQuestions = [...this.questions].sort((a, b) => a.sequence_number - b.sequence_number);
  2001. const questionsToUse = sortedQuestions.slice(0, 5);
  2002. questionsToUse.forEach((question, index) => {
  2003. if (question.digital_human_video_url) {
  2004. this.videoList.push(question.digital_human_video_url);
  2005. const subtitleArray = [{
  2006. startTime: 0,
  2007. endTime: 30,
  2008. // 延长字幕显示时间到30秒
  2009. text: question.digital_human_video_subtitle || question.question
  2010. }];
  2011. const videoIndex = this.videoList.length - 1;
  2012. this[`question${videoIndex}Subtitles`] = subtitleArray;
  2013. this.subtitleMap[question.digital_human_video_url] = subtitleArray;
  2014. }
  2015. });
  2016. if (this.videoList.length <= 1)
  2017. ;
  2018. else {
  2019. console.log("处理后的视频列表:", this.videoList);
  2020. console.log("处理后的字幕:", this.subtitles);
  2021. }
  2022. },
  2023. // 使用默认视频和字幕(作为备用)
  2024. useDefaultVideosAndSubtitles() {
  2025. console.log("使用默认视频和字幕");
  2026. this.subtitles = [
  2027. {
  2028. startTime: 0,
  2029. endTime: 5,
  2030. text: "你好,我是本次面试的面试官,欢迎参加本公司的线上面试!"
  2031. },
  2032. {
  2033. startTime: 5,
  2034. endTime: 13,
  2035. text: "面试预计需要15分钟,请你提前安排在网络良好、光线亮度合适、且相对安静的环境参加这次面试"
  2036. },
  2037. {
  2038. startTime: 13,
  2039. endTime: 20,
  2040. text: "以免影响本次面试的结果。如果你在面试过程中遇到问题,请与我们的招聘人员联系。"
  2041. }
  2042. ];
  2043. this.question1Subtitles = [{
  2044. startTime: 0,
  2045. endTime: 10,
  2046. text: "请结合您的基本信息与过往履历进行简单的自我介绍,并讲一讲您有哪些优势胜任本岗位:"
  2047. }];
  2048. this.question2Subtitles = [{
  2049. startTime: 0,
  2050. endTime: 4,
  2051. text: "在工作中,你如何确保个人防护装备的正确使用?"
  2052. }];
  2053. this.question3Subtitles = [{
  2054. startTime: 0,
  2055. endTime: 4,
  2056. text: "描述一次你与团队合作改善生产流程的经历。"
  2057. }];
  2058. this.question4Subtitles = [{
  2059. startTime: 0,
  2060. endTime: 6,
  2061. text: "你在团队合作中曾遇到过哪些挑战?如何解决团队内部的分歧?"
  2062. }];
  2063. this.question5Subtitles = [{
  2064. startTime: 0,
  2065. endTime: 5,
  2066. text: "您已完成本次面试全部题目,请问您对于这个岗位还有什么想要了解的吗?"
  2067. }];
  2068. },
  2069. // 播放介绍视频
  2070. playIntroVideo() {
  2071. this.videoUrl = this.videoList[0];
  2072. this.videoPlaying = true;
  2073. this.$nextTick(() => {
  2074. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  2075. if (videoContext) {
  2076. videoContext.play();
  2077. }
  2078. });
  2079. },
  2080. // 添加新方法:获取默认问题ID
  2081. getDefaultQuestionId(videoIndex) {
  2082. switch (videoIndex) {
  2083. case 1:
  2084. return 10;
  2085. case 2:
  2086. return 11;
  2087. case 3:
  2088. return 12;
  2089. case 4:
  2090. return 13;
  2091. default:
  2092. return 10;
  2093. }
  2094. },
  2095. // 添加新方法:根据索引获取当前问题
  2096. getCurrentQuestionByIndex(videoIndex) {
  2097. const questionIndex = videoIndex - 1;
  2098. const sortedQuestions = [...this.questions].sort((a, b) => a.sequence_number - b.sequence_number);
  2099. if (questionIndex >= 0 && questionIndex < sortedQuestions.length) {
  2100. return sortedQuestions[questionIndex];
  2101. }
  2102. return null;
  2103. },
  2104. onShow() {
  2105. console.log("identity-verify页面onShow");
  2106. console.log("当前本地存储中的职位信息:", common_vendor.index.getStorageSync("selectedJob"));
  2107. this.fetchQuestions();
  2108. this.fetchFollowUpQuestions();
  2109. },
  2110. // 添加新方法:重置录制状态,准备重新回答
  2111. resetForRerecording() {
  2112. console.log("重置录制状态,准备重新回答");
  2113. this.isRecording = false;
  2114. this.showStopRecordingButton = false;
  2115. this.showStartRecordingButton = true;
  2116. this.clearCountdown();
  2117. if (this.recordingTimer) {
  2118. clearInterval(this.recordingTimer);
  2119. this.recordingTimer = null;
  2120. }
  2121. this.recordingTimerCount = 0;
  2122. this.recordingTimeDisplay = "00:00 ";
  2123. this.remainingTime = this.maxRecordingTime;
  2124. if (this.mediaRecorder && this.mediaRecorder.state !== "inactive") {
  2125. this.mediaRecorder.stop();
  2126. this.recordedChunks = [];
  2127. }
  2128. if (this.cameraContext) {
  2129. this.cameraContext.stopRecord({
  2130. success: () => {
  2131. console.log("相机录制已停止");
  2132. },
  2133. fail: (err) => {
  2134. console.error("停止相机录制失败:", err);
  2135. }
  2136. });
  2137. }
  2138. },
  2139. // 修改 playLowScoreVideo 方法,优化字幕显示
  2140. playLowScoreVideo() {
  2141. console.log("播放低分提示视频");
  2142. this.isPlayingLowScoreVideo = true;
  2143. this.showStartRecordingButton = false;
  2144. this.showStopRecordingButton = false;
  2145. this.showRerecordButton = false;
  2146. this.videoUrl = this.lowScoreVideoUrl;
  2147. this.videoPlaying = true;
  2148. const originalSubtitle = this.currentSubtitle;
  2149. this.currentSubtitle = "";
  2150. this.$nextTick(() => {
  2151. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  2152. if (videoContext) {
  2153. videoContext.play();
  2154. setTimeout(() => {
  2155. this.currentSubtitle = "我未听清楚您在说什么,请您再说一遍!";
  2156. this.lowScoreVideoSubtitles = [
  2157. {
  2158. startTime: 0,
  2159. endTime: 30,
  2160. text: "我未听清楚您在说什么,请您再说一遍!",
  2161. translation: "I didn't quite catch what you said, could you please repeat it?"
  2162. }
  2163. ];
  2164. setTimeout(() => {
  2165. if (this.isFollowUpQuestion && this.currentFollowUpQuestion) {
  2166. this.currentSubtitle = this.currentFollowUpQuestion.digital_human_video_subtitle || this.currentFollowUpQuestion.question;
  2167. } else {
  2168. this.currentSubtitle = originalSubtitle;
  2169. }
  2170. }, 3e3);
  2171. }, 500);
  2172. }
  2173. });
  2174. },
  2175. // 添加新方法:处理重新录制按钮点击
  2176. handleRerecordButtonClick() {
  2177. console.log("点击重新录制按钮");
  2178. this.retryCount++;
  2179. console.log(`当前重试次数: ${this.retryCount}/${this.maxRetryAttempts}`);
  2180. this.showRerecordButton = false;
  2181. this.handleStartRecordingClick();
  2182. },
  2183. // 添加 onUnload 生命周期钩子,移除 WebSocket 关闭
  2184. onUnload() {
  2185. console.log("页面卸载");
  2186. },
  2187. // 修改 onHide 生命周期钩子,移除 WebSocket 关闭
  2188. onHide() {
  2189. console.log("页面隐藏");
  2190. },
  2191. // 添加新方法:阻止视频控制
  2192. preventVideoControl(e) {
  2193. e.preventDefault();
  2194. e.stopPropagation();
  2195. console.log("阻止视频控制操作");
  2196. return false;
  2197. },
  2198. // 添加获取追问问题的方法
  2199. fetchFollowUpQuestions() {
  2200. const tenant_id = JSON.parse(common_vendor.index.getStorageSync("userInfo")).tenant_id || "1";
  2201. let position_id = 1;
  2202. try {
  2203. const selectedJob = JSON.parse(common_vendor.index.getStorageSync("selectedJob") || "{}");
  2204. if (selectedJob && selectedJob.id) {
  2205. position_id = selectedJob.id;
  2206. console.log("使用选择的职位ID获取追问问题:", position_id);
  2207. } else {
  2208. console.warn("未找到选择的职位信息,使用默认职位ID:", position_id);
  2209. }
  2210. } catch (e) {
  2211. console.error("解析职位信息失败:", e);
  2212. }
  2213. const timestamp = Date.now();
  2214. const requestUrl = `${common_config.apiBaseUrl}/api/wechat/open_questions/?position_id=${position_id}&tenant_id=${tenant_id}&question_form=5&_t=${timestamp}`;
  2215. console.log("获取追问问题的请求URL:", requestUrl);
  2216. common_vendor.index.request({
  2217. url: requestUrl,
  2218. method: "GET",
  2219. success: (res) => {
  2220. if (res.data && res.data.code === 2e3 && res.data.data && res.data.data.items) {
  2221. console.log("获取追问问题数据成功:", res.data.data.items);
  2222. this.followUpQuestions = res.data.data.items.map((item) => ({
  2223. ...item,
  2224. question_form: 5
  2225. // 确保每个追问问题都有正确的question_form值
  2226. }));
  2227. this.processFollowUpQuestions();
  2228. } else {
  2229. console.error("获取追问问题数据失败:", res.data);
  2230. this.followUpQuestions = [];
  2231. }
  2232. },
  2233. fail: (err) => {
  2234. console.error("请求追问问题数据失败:", err);
  2235. this.followUpQuestions = [];
  2236. }
  2237. });
  2238. },
  2239. // 改进处理追问问题数据的方法
  2240. processFollowUpQuestions() {
  2241. if (!this.followUpQuestions || this.followUpQuestions.length === 0) {
  2242. console.log("没有追问问题数据");
  2243. this.followUpQuestions = [];
  2244. return;
  2245. }
  2246. console.log("处理追问问题数据,总数:", this.followUpQuestions.length);
  2247. this.followUpQuestions = this.followUpQuestions.filter((q) => q.parent_question_id);
  2248. const parentQuestionIds = /* @__PURE__ */ new Set();
  2249. this.followUpQuestions.forEach((question) => {
  2250. if (question.parent_question_id) {
  2251. parentQuestionIds.add(question.parent_question_id);
  2252. }
  2253. });
  2254. console.log("有追问的父问题ID:", Array.from(parentQuestionIds));
  2255. this.hasPlayedFollowUp = {};
  2256. },
  2257. // 修改检查并播放追问问题的方法
  2258. checkAndPlayFollowUpQuestion(parentQuestionId) {
  2259. console.log("检查是否有追问问题,父问题ID:", parentQuestionId);
  2260. if (!parentQuestionId) {
  2261. console.warn("没有父问题ID,无法检查追问问题");
  2262. this.proceedToNextQuestion();
  2263. return;
  2264. }
  2265. if (this.hasPlayedFollowUp[parentQuestionId]) {
  2266. console.log("已经播放过此问题的追问,直接进入下一个问题");
  2267. this.retryCount = 0;
  2268. this.proceedToNextQuestion();
  2269. return;
  2270. }
  2271. const followUpQuestion = this.followUpQuestions.find(
  2272. (q) => q.parent_question_id === parentQuestionId && q.digital_human_video_url && q.question_form === 5
  2273. );
  2274. if (followUpQuestion) {
  2275. console.log("找到追问问题:", followUpQuestion);
  2276. const recordingDuration = this.getRecordingDuration();
  2277. const lowScoreDuration = 7;
  2278. if (recordingDuration < lowScoreDuration) {
  2279. console.log(`录制时间 ${recordingDuration} 秒,少于 ${lowScoreDuration} 秒,将播放低分提示视频`);
  2280. this.retryCount++;
  2281. this.needPlayLowScoreVideo = true;
  2282. this.playLowScoreVideo();
  2283. return;
  2284. }
  2285. this.retryCount = 0;
  2286. this.hasPlayedFollowUp[parentQuestionId] = true;
  2287. this.isFollowUpQuestion = true;
  2288. this.currentParentQuestionId = parentQuestionId;
  2289. this.currentFollowUpQuestion = followUpQuestion;
  2290. this.playFollowUpQuestionVideo(followUpQuestion);
  2291. } else {
  2292. console.log("没有找到对应的追问问题,继续下一个问题");
  2293. this.retryCount = 0;
  2294. this.proceedToNextQuestion();
  2295. }
  2296. },
  2297. // 修改播放追问问题视频的方法
  2298. playFollowUpQuestionVideo(followUpQuestion) {
  2299. console.log("播放追问问题视频:", followUpQuestion.digital_human_video_url);
  2300. this.parentQuestion = this.currentSubtitle;
  2301. this.videoUrl = followUpQuestion.digital_human_video_url;
  2302. this.videoPlaying = true;
  2303. this.isFollowUpQuestion = true;
  2304. this.currentFollowUpQuestion = followUpQuestion;
  2305. const followUpSubtitles = [{
  2306. startTime: 0,
  2307. endTime: 60,
  2308. // 延长显示时间到60秒
  2309. text: followUpQuestion.digital_human_video_subtitle || followUpQuestion.question
  2310. }];
  2311. const subtitleKey = `followUpSubtitles_${followUpQuestion.id}`;
  2312. this[subtitleKey] = followUpSubtitles;
  2313. this.$nextTick(() => {
  2314. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  2315. if (videoContext) {
  2316. videoContext.play();
  2317. this.currentSubtitle = followUpSubtitles[0].text;
  2318. }
  2319. });
  2320. },
  2321. // 添加作废面试的方法
  2322. invalidateInterview() {
  2323. if (this.isRecording) {
  2324. this.stopRecordingAnswer();
  2325. }
  2326. if (this.recordingTimer) {
  2327. clearInterval(this.recordingTimer);
  2328. }
  2329. this.isRecording = false;
  2330. this.showStopRecordingButton = false;
  2331. this.showStartRecordingButton = false;
  2332. setTimeout(() => {
  2333. common_vendor.index.switchTab({
  2334. url: "/pages/index/index"
  2335. });
  2336. }, 500);
  2337. },
  2338. initPersonDetectionWebSocket() {
  2339. if (this.personDetectionSocket) {
  2340. this.cleanupPersonDetectionWebSocket();
  2341. }
  2342. try {
  2343. this.personDetectionSocket = common_vendor.index.connectSocket({
  2344. url: `${common_config.personDetectionWsUrl}/ws/interview-room/room_${common_vendor.index.getStorageSync("appId")}/${common_vendor.index.getStorageSync("appId")}/`,
  2345. success: () => {
  2346. console.log("WebSocket connection initiated");
  2347. },
  2348. fail: (error) => {
  2349. console.error("WebSocket connection failed:", error);
  2350. }
  2351. });
  2352. this.personDetectionSocket.onOpen(() => {
  2353. console.log("WebSocket connection opened");
  2354. this.startPersonDetectionInterval();
  2355. });
  2356. this.personDetectionSocket.onError((error) => {
  2357. console.error("WebSocket error:", error);
  2358. this.cleanupPersonDetectionWebSocket();
  2359. });
  2360. this.personDetectionSocket.onClose(() => {
  2361. console.log("WebSocket connection closed");
  2362. this.cleanupPersonDetectionWebSocket();
  2363. });
  2364. this.personDetectionSocket.onMessage((res) => {
  2365. try {
  2366. const data = JSON.parse(res.data);
  2367. console.log(data);
  2368. if (data.type === "person_detection_result") {
  2369. this.handlePersonDetectionResult(data);
  2370. }
  2371. } catch (error) {
  2372. console.error("Error parsing WebSocket message:", error);
  2373. }
  2374. });
  2375. } catch (error) {
  2376. console.error("Error initializing WebSocket:", error);
  2377. this.cleanupPersonDetectionWebSocket();
  2378. }
  2379. },
  2380. startPersonDetectionInterval() {
  2381. if (this.personDetectionInterval) {
  2382. clearInterval(this.personDetectionInterval);
  2383. }
  2384. this.personDetectionInterval = setInterval(() => {
  2385. if (this.personDetectionSocket && this.cameraContext) {
  2386. this.cameraContext.takePhoto({
  2387. quality: "low",
  2388. success: (res) => {
  2389. const tempFilePath = res.tempImagePath;
  2390. common_vendor.index.getFileSystemManager().readFile({
  2391. filePath: tempFilePath,
  2392. encoding: "base64",
  2393. success: (res2) => {
  2394. const base64Image = res2.data;
  2395. this.personDetectionSocket.send({
  2396. data: JSON.stringify({
  2397. type: "person_detection",
  2398. image_data: base64Image
  2399. })
  2400. });
  2401. },
  2402. fail: (error) => {
  2403. console.error("Error reading image file:", error);
  2404. }
  2405. });
  2406. },
  2407. fail: (error) => {
  2408. console.error("Error taking photo:", error);
  2409. }
  2410. });
  2411. }
  2412. }, 3e3);
  2413. },
  2414. cleanupPersonDetectionWebSocket() {
  2415. if (this.personDetectionInterval) {
  2416. clearInterval(this.personDetectionInterval);
  2417. this.personDetectionInterval = null;
  2418. }
  2419. if (this.personDetectionSocket) {
  2420. try {
  2421. this.personDetectionSocket.close();
  2422. } catch (error) {
  2423. console.error("Error closing WebSocket:", error);
  2424. }
  2425. this.personDetectionSocket = null;
  2426. }
  2427. },
  2428. handlePersonDetectionResult(data) {
  2429. console.log(data.data.detection.has_person);
  2430. console.log(data.data.identity.status);
  2431. if (data.data.identity.status !== "identity_verified") {
  2432. this.showPageWarning = true;
  2433. common_vendor.index.showToast({
  2434. title: data.data.identity.message,
  2435. icon: "none",
  2436. duration: 3e3
  2437. });
  2438. common_vendor.index.vibrateLong({
  2439. success: function() {
  2440. console.log("Vibration successful");
  2441. },
  2442. fail: function(err) {
  2443. console.error("Vibration failed:", err);
  2444. }
  2445. });
  2446. setTimeout(() => {
  2447. this.showPageWarning = false;
  2448. }, 3e3);
  2449. }
  2450. }
  2451. },
  2452. computed: {
  2453. // 计算进度比例
  2454. progressRatio() {
  2455. return this.recordingTimerCount / this.maxRecordingTime;
  2456. },
  2457. // 右半圆旋转角度
  2458. half1Turn() {
  2459. if (this.progressRatio <= 0.5) {
  2460. return this.progressRatio * 2 * 180;
  2461. } else {
  2462. return 180;
  2463. }
  2464. },
  2465. // 左半圆旋转角度
  2466. half2Turn() {
  2467. if (this.progressRatio <= 0.5) {
  2468. return 0;
  2469. } else {
  2470. return (this.progressRatio - 0.5) * 2 * 180;
  2471. }
  2472. },
  2473. // 修改进度百分比的计算方式
  2474. progressPercent() {
  2475. return Math.min(Math.round(this.recordingTimerCount / this.maxRecordingTime * 100), 100);
  2476. },
  2477. // 添加总题数计算属性
  2478. totalQuestions() {
  2479. return this.questions.length || 5;
  2480. }
  2481. }
  2482. };
  2483. function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
  2484. return common_vendor.e({
  2485. a: $data.videoUrl,
  2486. b: common_vendor.o((...args) => $options.handleVideoError && $options.handleVideoError(...args)),
  2487. c: common_vendor.o((...args) => $options.handleVideoEnded && $options.handleVideoEnded(...args)),
  2488. d: common_vendor.o((...args) => $options.handleTimeUpdate && $options.handleTimeUpdate(...args)),
  2489. e: common_vendor.o((...args) => $options.preventVideoControl && $options.preventVideoControl(...args)),
  2490. f: common_vendor.o((...args) => $options.preventVideoControl && $options.preventVideoControl(...args)),
  2491. g: $data.showAnswerButton
  2492. }, $data.showAnswerButton ? {
  2493. h: common_vendor.o((...args) => $options.handleAnswerButtonClick && $options.handleAnswerButtonClick(...args))
  2494. } : {}, {
  2495. i: $data.currentSubtitle
  2496. }, $data.currentSubtitle ? common_vendor.e({
  2497. j: $data.currentVideoIndex > 0
  2498. }, $data.currentVideoIndex > 0 ? {
  2499. k: common_vendor.t($data.currentVideoIndex),
  2500. l: common_vendor.t($options.totalQuestions)
  2501. } : {}, {
  2502. m: !$data.isFollowUpQuestion
  2503. }, !$data.isFollowUpQuestion ? {
  2504. n: common_vendor.t($data.currentSubtitle)
  2505. } : {
  2506. o: common_vendor.t($data.parentQuestion),
  2507. p: common_vendor.t($data.currentSubtitle)
  2508. }) : {}, {
  2509. q: $data.useMiniProgramCameraComponent
  2510. }, $data.useMiniProgramCameraComponent ? {
  2511. r: common_vendor.o((...args) => $options.handleCameraError && $options.handleCameraError(...args))
  2512. } : {}, {
  2513. s: $data.showPageWarning ? 1 : "",
  2514. t: $data.loading
  2515. }, $data.loading ? {} : {}, {
  2516. v: $data.showDebugInfo
  2517. }, $data.showDebugInfo ? common_vendor.e({
  2518. w: $data.assistantResponse
  2519. }, $data.assistantResponse ? {
  2520. x: common_vendor.t($data.assistantResponse)
  2521. } : {}, {
  2522. y: $data.audioTranscript
  2523. }, $data.audioTranscript ? {
  2524. z: common_vendor.t($data.audioTranscript)
  2525. } : {}, {
  2526. A: common_vendor.f($data.processedResponses, (item, index, i0) => {
  2527. return common_vendor.e({
  2528. a: item.role
  2529. }, item.role ? {
  2530. b: common_vendor.t(item.role)
  2531. } : {}, {
  2532. c: item.transcript
  2533. }, item.transcript ? {
  2534. d: common_vendor.t(item.transcript)
  2535. } : {}, {
  2536. e: index
  2537. });
  2538. })
  2539. }) : {}, {
  2540. B: $data.showStopRecordingButton
  2541. }, $data.showStopRecordingButton ? {
  2542. C: common_vendor.o((...args) => $options.stopRecordingAnswer && $options.stopRecordingAnswer(...args))
  2543. } : {}, {
  2544. D: $data.isRecording
  2545. }, $data.isRecording ? {
  2546. E: common_vendor.t($data.recordingTimeDisplay),
  2547. F: `conic-gradient(${$data.progressColor} ${$options.progressPercent}%, ${$data.progressBgColor} 0%)`
  2548. } : {}, {
  2549. G: $data.showStartRecordingButton
  2550. }, $data.showStartRecordingButton ? {
  2551. H: common_vendor.o((...args) => $options.handleStartRecordingClick && $options.handleStartRecordingClick(...args))
  2552. } : {}, {
  2553. I: $data.showRetryButton
  2554. }, $data.showRetryButton ? {
  2555. J: common_vendor.o((...args) => $options.retryVideoUpload && $options.retryVideoUpload(...args))
  2556. } : {}, {
  2557. K: $data.showCountdown
  2558. }, $data.showCountdown ? {
  2559. L: common_vendor.t($data.countdownValue)
  2560. } : {}, {
  2561. M: $data.showRerecordButton
  2562. }, $data.showRerecordButton ? {
  2563. N: common_vendor.o((...args) => $options.handleRerecordButtonClick && $options.handleRerecordButtonClick(...args))
  2564. } : {}, {
  2565. O: $data.showPageWarning ? 1 : ""
  2566. });
  2567. }
  2568. const MiniProgramPage = /* @__PURE__ */ common_vendor._export_sfc(_sfc_main, [["render", _sfc_render], ["__scopeId", "data-v-464e78c6"]]);
  2569. wx.createPage(MiniProgramPage);