followUp.js 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071
  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. subtitles: [],
  29. // 修改为空数组,将通过API获取
  30. // 移除硬编码的字幕数组
  31. // secondVideoSubtitles: [...],
  32. // thirdVideoSubtitles: [...],
  33. // 等等...
  34. showAnswerButton: false,
  35. // 控制答题按钮显示
  36. currentVideoIndex: 0,
  37. // 当前播放的视频索引
  38. videoList: [],
  39. // 修改为空数组,将通过API获取
  40. // 其他属性保持不变...
  41. questions: [],
  42. // 添加新属性存储API返回的问题数据
  43. introVideoUrl: "https://data.qicai321.com/minlong/ee4d9cce-c3d5-4350-8c6e-684283827897.mp4",
  44. // 保留介绍视频
  45. isRecording: false,
  46. recordingTimer: null,
  47. showStopRecordingButton: false,
  48. mediaRecorder: null,
  49. recordedChunks: [],
  50. recorder: null,
  51. lastUploadedVideoUrl: "",
  52. showStartRecordingButton: false,
  53. showRetryButton: false,
  54. // 控制重试按钮显示
  55. lastVideoToRetry: null,
  56. // 存储上次失败的视频URL,用于重试
  57. recordingStartTime: null,
  58. // 录制开始时间
  59. recordingTimerCount: 0,
  60. // 录制计时器计数
  61. recordingTimeDisplay: "00:00",
  62. // 格式化的录制时间显示
  63. // 添加上传队列相关数据
  64. uploadQueue: [],
  65. // 存储待上传的视频
  66. isUploading: false,
  67. // 标记是否正在上传
  68. uploadProgress: {},
  69. // 存储每个视频的上传进度
  70. uploadStatus: {},
  71. // 存储每个视频的上传状态
  72. showUploadStatus: false,
  73. // 是否显示上传状态指示器
  74. uploadStatusText: "",
  75. // 上传状态文本
  76. mediaRecorderTimeout: null,
  77. // 用于存储MediaRecorder的超时机制
  78. maxRecordingTime: 300,
  79. // 最大录制时间(秒)- 从60秒改为300秒(5分钟)
  80. remainingTime: 300,
  81. // 剩余录制时间(秒)- 从60秒改为300秒
  82. countdownValue: 10,
  83. // 倒计时数值
  84. showCountdown: false,
  85. // 是否显示倒计时蒙层
  86. countdownTimer: null,
  87. showGif: false,
  88. // 控制是否显示GIF
  89. gifUrl: "",
  90. // GIF图片的URL
  91. additionalQuestions: [],
  92. // 存储追加问题
  93. currentQuestionIndex: 0
  94. // 当前问题索引
  95. };
  96. },
  97. mounted() {
  98. this.checkAudioPermission();
  99. this.initCamera();
  100. this.checkIOSCameraRecordPermission();
  101. this.checkAndFixRenderingIssues();
  102. setTimeout(() => {
  103. if (this.cameraStream && !this.useMiniProgramCameraComponent) {
  104. this.testAudioInput();
  105. }
  106. }, 3e3);
  107. common_vendor.index.setKeepScreenOn({
  108. keepScreenOn: true
  109. });
  110. this.fetchAdditionalQuestions();
  111. },
  112. beforeDestroy() {
  113. this.stopUserCamera();
  114. this.clearCountdown();
  115. },
  116. methods: {
  117. // 初始化相机
  118. async initCamera() {
  119. const systemInfo = common_vendor.index.getSystemInfoSync();
  120. const isMiniProgram = systemInfo.uniPlatform === "mp-weixin" || systemInfo.uniPlatform === "mp-alipay" || systemInfo.uniPlatform === "mp-baidu";
  121. if (isMiniProgram) {
  122. this.useMiniProgramCameraComponent = true;
  123. this.cameraContext = common_vendor.index.createCameraContext();
  124. common_vendor.index.getSetting({
  125. success: (res) => {
  126. if (!res.authSetting["scope.record"]) {
  127. common_vendor.index.authorize({
  128. scope: "scope.record",
  129. success: () => {
  130. console.log("录音权限已获取");
  131. },
  132. fail: (err) => {
  133. console.error("录音权限获取失败:", err);
  134. this.showPermissionDialog("录音");
  135. }
  136. });
  137. }
  138. if (!res.authSetting["scope.camera"]) {
  139. common_vendor.index.authorize({
  140. scope: "scope.camera",
  141. success: () => {
  142. console.log("相机权限已获取");
  143. },
  144. fail: (err) => {
  145. console.error("相机权限获取失败:", err);
  146. this.showPermissionDialog("相机");
  147. }
  148. });
  149. }
  150. const systemInfo2 = common_vendor.index.getSystemInfoSync();
  151. if (systemInfo2.platform === "ios") {
  152. if (!res.authSetting["scope.camera"] || !res.authSetting["scope.record"]) {
  153. console.log("iOS需要同时获取相机和录音权限");
  154. }
  155. }
  156. }
  157. });
  158. } else {
  159. try {
  160. const constraints = {
  161. audio: {
  162. echoCancellation: true,
  163. noiseSuppression: true,
  164. autoGainControl: true
  165. },
  166. video: {
  167. width: { ideal: 640, max: 1280 },
  168. // 控制视频宽度
  169. height: { ideal: 480, max: 720 },
  170. // 控制视频高度
  171. frameRate: { ideal: 15, max: 24 },
  172. // 控制帧率
  173. facingMode: "user"
  174. }
  175. };
  176. const stream = await navigator.mediaDevices.getUserMedia(constraints);
  177. this.cameraStream = stream;
  178. const audioTracks = stream.getAudioTracks();
  179. console.log("音频轨道数量:", audioTracks.length);
  180. if (audioTracks.length > 0) {
  181. console.log("音频轨道已获取:", audioTracks[0].label);
  182. audioTracks[0].enabled = true;
  183. } else {
  184. console.warn("未检测到音频轨道,尝试单独获取音频");
  185. this.tryGetAudioOnly();
  186. }
  187. const videoElement = this.$refs.userCameraVideo;
  188. if (videoElement) {
  189. videoElement.srcObject = stream;
  190. videoElement.muted = true;
  191. }
  192. } catch (error) {
  193. console.error("获取摄像头失败:", error);
  194. this.cameraError = error.message || "无法访问摄像头";
  195. common_vendor.index.showToast({
  196. title: "无法访问摄像头,请检查权限设置",
  197. icon: "none"
  198. });
  199. }
  200. }
  201. },
  202. // 停止用户摄像头
  203. stopUserCamera() {
  204. if (this.cameraStream) {
  205. this.cameraStream.getTracks().forEach((track) => {
  206. track.stop();
  207. });
  208. this.cameraStream = null;
  209. }
  210. },
  211. async fetchData() {
  212. this.loading = true;
  213. this.assistantResponse = "";
  214. this.audioTranscript = "";
  215. this.processedResponses = [];
  216. try {
  217. const requestTask = common_vendor.index.request({
  218. url: "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",
  219. method: "POST",
  220. header: {
  221. "Content-Type": "application/json",
  222. "Authorization": "Bearer sk-9e1ec73a7d97493b8613c63f06b6110c"
  223. },
  224. data: {
  225. "model": "qwen-omni-turbo",
  226. "messages": [
  227. {
  228. "role": "user",
  229. "content": [
  230. {
  231. "type": "input_audio",
  232. "input_audio": {
  233. "data": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250211/tixcef/cherry.wav",
  234. "format": "wav"
  235. }
  236. },
  237. {
  238. "type": "text",
  239. "text": "这段音频在说什么"
  240. }
  241. ]
  242. }
  243. ],
  244. "stream": true,
  245. "stream_options": {
  246. "include_usage": true
  247. },
  248. "modalities": ["text", "audio"],
  249. "audio": { "voice": "Cherry", "format": "wav" }
  250. },
  251. success: (res) => {
  252. console.log("请求成功,响应数据:", res.data);
  253. if (typeof res.data === "string" && res.data.includes("data: {")) {
  254. const chunks = res.data.split("data: ").filter((chunk) => chunk.trim() !== "");
  255. chunks.forEach((chunk) => {
  256. this.handleStreamResponse(chunk);
  257. });
  258. } else {
  259. this.handleStreamResponse(res.data);
  260. }
  261. this.playDigitalHumanVideo();
  262. },
  263. fail: (err) => {
  264. console.error("请求失败:", err);
  265. },
  266. complete: () => {
  267. this.loading = false;
  268. }
  269. });
  270. } catch (error) {
  271. console.error("获取数据失败:", error);
  272. this.loading = false;
  273. }
  274. },
  275. handleStreamResponse(data) {
  276. if (typeof data === "string") {
  277. if (data === "[DONE]")
  278. return;
  279. try {
  280. const cleanData = data.trim();
  281. if (cleanData.startsWith("{") && cleanData.endsWith("}")) {
  282. const jsonData = JSON.parse(cleanData);
  283. this.processStreamChunk(jsonData);
  284. }
  285. } catch (e) {
  286. console.error("解析JSON失败:", e, "原始数据:", data);
  287. }
  288. } else {
  289. this.processStreamChunk(data);
  290. }
  291. },
  292. processStreamChunk(chunk) {
  293. if (chunk.choices && chunk.choices.length > 0) {
  294. const choice = chunk.choices[0];
  295. if (choice.delta && choice.delta.content) {
  296. this.assistantResponse += choice.delta.content;
  297. }
  298. if (choice.delta && choice.delta.audio && choice.delta.audio.transcript) {
  299. this.audioTranscript += choice.delta.audio.transcript;
  300. }
  301. if (choice.delta) {
  302. const result = {};
  303. if (choice.delta.role) {
  304. result.role = choice.delta.role;
  305. }
  306. if (choice.delta.audio && choice.delta.audio.transcript) {
  307. result.transcript = choice.delta.audio.transcript;
  308. }
  309. if (Object.keys(result).length > 0) {
  310. this.processedResponses.push(result);
  311. }
  312. }
  313. }
  314. },
  315. processResponseData() {
  316. this.processedResponses = this.responses.map((item) => {
  317. const result = {};
  318. if (item.delta && item.delta.role) {
  319. result.role = item.delta.role;
  320. }
  321. if (item.delta && item.delta.audio && item.delta.audio.transcript) {
  322. result.transcript = item.delta.audio.transcript;
  323. }
  324. return result;
  325. }).filter((item) => Object.keys(item).length > 0);
  326. },
  327. // 播放数字人视频
  328. playDigitalHumanVideo() {
  329. if (this.videoList.length === 0) {
  330. this.fetchQuestions();
  331. return;
  332. }
  333. this.videoUrl = this.videoList[this.currentVideoIndex];
  334. this.videoPlaying = true;
  335. this.$nextTick(() => {
  336. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  337. if (videoContext) {
  338. videoContext.play();
  339. setTimeout(() => {
  340. if (this.videoPlaying && this.$refs.videoPlayer) {
  341. console.log("视频应该正在播放");
  342. } else {
  343. console.log("视频可能未成功播放,尝试替代方案");
  344. this.tryAlternativeVideoPath();
  345. }
  346. }, 1e3);
  347. } else {
  348. console.error("无法创建视频上下文");
  349. this.tryAlternativeVideoPath();
  350. }
  351. });
  352. },
  353. // 修改 tryAlternativeVideoPath 方法
  354. tryAlternativeVideoPath() {
  355. console.log("尝试使用替代路径");
  356. const alternativePaths = [
  357. "./static/demo.mp4",
  358. "../static/demo.mp4",
  359. "static/demo.mp4",
  360. "/static/demo.mp4",
  361. // 添加绝对路径
  362. `${window.location.origin}/static/demo.mp4`
  363. ];
  364. const currentPathIndex = alternativePaths.indexOf(this.videoUrl);
  365. const nextPathIndex = (currentPathIndex + 1) % alternativePaths.length;
  366. this.videoUrl = alternativePaths[nextPathIndex];
  367. console.log("尝试新路径:", this.videoUrl);
  368. this.$nextTick(() => {
  369. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  370. if (videoContext) {
  371. videoContext.stop();
  372. videoContext.play();
  373. setTimeout(() => {
  374. if (nextPathIndex === alternativePaths.length - 1 && !this.videoPlaying) {
  375. console.log("所有路径均失败,尝试使用uni.getVideoInfo检查视频");
  376. this.checkVideoWithAPI();
  377. }
  378. }, 1e3);
  379. }
  380. });
  381. },
  382. // 添加新方法:使用uni API检查视频
  383. checkVideoWithAPI() {
  384. common_vendor.index.getVideoInfo({
  385. src: "/static/demo.mp4",
  386. success: (res) => {
  387. console.log("视频信息获取成功:", res);
  388. this.videoUrl = "/static/demo.mp4";
  389. this.$nextTick(() => {
  390. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  391. if (videoContext) {
  392. videoContext.play();
  393. }
  394. });
  395. },
  396. fail: (err) => {
  397. console.error("视频信息获取失败:", err);
  398. this.fallbackToLocalVideo();
  399. }
  400. });
  401. },
  402. // 添加新方法:回退到本地视频
  403. fallbackToLocalVideo() {
  404. console.log("尝试使用本地视频资源");
  405. const platform = common_vendor.index.getSystemInfoSync().platform;
  406. if (platform === "android" || platform === "ios") {
  407. this.videoUrl = platform === "android" ? "android.resource://package_name/raw/demo" : "file:///assets/demo.mp4";
  408. this.$nextTick(() => {
  409. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  410. if (videoContext) {
  411. videoContext.play();
  412. }
  413. });
  414. } else {
  415. this.videoPlaying = false;
  416. common_vendor.index.showToast({
  417. title: "视频加载失败,显示静态图片",
  418. icon: "none"
  419. });
  420. }
  421. },
  422. // 修改 handleVideoError 方法
  423. handleVideoError(e) {
  424. console.error("视频加载错误:", e);
  425. if (e && e.detail) {
  426. console.error("详细错误信息:", e.detail);
  427. }
  428. common_vendor.index.getFileInfo({
  429. filePath: this.videoUrl.startsWith("/") ? this.videoUrl.substring(1) : this.videoUrl,
  430. success: (res) => {
  431. console.log("文件存在,大小:", res.size);
  432. this.tryDifferentFormat();
  433. },
  434. fail: (err) => {
  435. console.error("文件不存在或无法访问:", err);
  436. this.tryAlternativeVideoPath();
  437. }
  438. });
  439. common_vendor.index.showToast({
  440. title: "视频加载失败,请检查文件是否存在",
  441. icon: "none",
  442. duration: 2e3
  443. });
  444. },
  445. // 添加新方法:尝试不同格式
  446. tryDifferentFormat() {
  447. console.log("尝试不同的视频格式");
  448. const formats = [
  449. { ext: "mp4", mime: "video/mp4" },
  450. { ext: "webm", mime: "video/webm" },
  451. { ext: "ogg", mime: "video/ogg" },
  452. { ext: "mov", mime: "video/quicktime" }
  453. ];
  454. const currentPath = this.videoUrl;
  455. const basePath = currentPath.substring(0, currentPath.lastIndexOf(".")) || "/static/demo";
  456. let nextFormat = formats.find((f) => !currentPath.endsWith(f.ext));
  457. if (nextFormat) {
  458. this.videoUrl = `${basePath}.${nextFormat.ext}`;
  459. console.log("尝试新格式:", this.videoUrl);
  460. this.$nextTick(() => {
  461. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  462. if (videoContext) {
  463. videoContext.stop();
  464. videoContext.play();
  465. }
  466. });
  467. } else {
  468. this.useBuiltInResource();
  469. }
  470. },
  471. // 添加新方法:使用内置资源
  472. useBuiltInResource() {
  473. console.log("尝试使用内置资源");
  474. const platform = common_vendor.index.getSystemInfoSync().platform;
  475. if (platform === "windows") {
  476. process.env.UNI_INPUT_DIR || "";
  477. this.videoUrl = `./static/demo.mp4`;
  478. console.log("Windows平台尝试路径:", this.videoUrl);
  479. } else if (platform === "android" || platform === "ios") {
  480. this.useNativeVideo();
  481. } else {
  482. const baseUrl = window.location.origin;
  483. this.videoUrl = `${baseUrl}/static/demo.mp4`;
  484. console.log("Web平台尝试URL:", this.videoUrl);
  485. }
  486. this.$nextTick(() => {
  487. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  488. if (videoContext) {
  489. videoContext.play();
  490. }
  491. });
  492. },
  493. // 添加新方法:使用原生视频能力
  494. useNativeVideo() {
  495. console.log("尝试使用原生视频能力");
  496. common_vendor.index.chooseVideo({
  497. sourceType: ["album"],
  498. success: (res) => {
  499. this.videoUrl = res.tempFilePath;
  500. this.$nextTick(() => {
  501. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  502. if (videoContext) {
  503. videoContext.play();
  504. }
  505. });
  506. },
  507. fail: () => {
  508. this.videoPlaying = false;
  509. common_vendor.index.showToast({
  510. title: "无法加载视频,显示静态图片",
  511. icon: "none"
  512. });
  513. }
  514. });
  515. },
  516. // 处理视频结束事件
  517. handleVideoEnded() {
  518. console.log("视频播放结束");
  519. this.videoPlaying = false;
  520. this.showStartRecordingButton = true;
  521. this.startCountdown();
  522. },
  523. // 添加新方法:开始倒计时
  524. startCountdown() {
  525. this.showCountdown = true;
  526. this.countdownValue = 10;
  527. this.countdownTimer = setInterval(() => {
  528. this.countdownValue--;
  529. if (this.countdownValue <= 0) {
  530. this.clearCountdown();
  531. this.showStartRecordingButton = false;
  532. this.startRecordingAnswer();
  533. }
  534. }, 1e3);
  535. },
  536. // 添加新方法:清除倒计时
  537. clearCountdown() {
  538. if (this.countdownTimer) {
  539. clearInterval(this.countdownTimer);
  540. this.countdownTimer = null;
  541. }
  542. this.showCountdown = false;
  543. },
  544. // 修改 handleStartRecordingClick 方法,使其可以终止倒计时
  545. handleStartRecordingClick() {
  546. this.showStartRecordingButton = false;
  547. this.clearCountdown();
  548. this.startRecordingAnswer();
  549. },
  550. // 修改 stopRecordingAnswer 方法,确保清除倒计时
  551. stopRecordingAnswer() {
  552. this.clearCountdown();
  553. const recordingDuration = this.getRecordingDuration();
  554. const minimumDuration = 5;
  555. if (recordingDuration < minimumDuration) {
  556. common_vendor.index.showToast({
  557. title: "录制时间过短,请至少录制5秒",
  558. icon: "none",
  559. duration: 2e3
  560. });
  561. return;
  562. }
  563. this.completeRecordingStop();
  564. },
  565. // 添加新方法:开始录制用户回答
  566. startRecordingAnswer() {
  567. console.log("开始录制用户回答");
  568. this.isRecording = true;
  569. this.recordingStartTime = Date.now();
  570. this.recordingTimerCount = 0;
  571. this.remainingTime = this.maxRecordingTime;
  572. this.recordingTimer = setInterval(() => {
  573. this.recordingTimerCount++;
  574. this.remainingTime = Math.max(0, this.maxRecordingTime - this.recordingTimerCount);
  575. this.recordingTimeDisplay = this.formatTime(this.recordingTimerCount) + " / " + this.formatTime(this.maxRecordingTime);
  576. if (this.recordingTimerCount >= this.maxRecordingTime) {
  577. console.log("已达到最大录制时间(60秒),自动停止录制");
  578. this.stopRecordingAnswer();
  579. }
  580. }, 1e3);
  581. const systemInfo = common_vendor.index.getSystemInfoSync();
  582. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith("mp-");
  583. if (isMiniProgram) {
  584. this.startMiniProgramRecording();
  585. } else {
  586. this.startBrowserRecording();
  587. }
  588. this.showStopRecordingButton = true;
  589. },
  590. // 添加一个新方法:重置相机组件
  591. resetCamera() {
  592. console.log("重置相机组件");
  593. this.useMiniProgramCameraComponent = false;
  594. if (this.cameraContext) {
  595. this.cameraContext = null;
  596. }
  597. setTimeout(() => {
  598. this.useMiniProgramCameraComponent = true;
  599. setTimeout(() => {
  600. this.cameraContext = common_vendor.index.createCameraContext();
  601. console.log("相机组件已重置");
  602. }, 500);
  603. }, 500);
  604. },
  605. // 修改 startMiniProgramRecording 方法
  606. startMiniProgramRecording() {
  607. console.log("开始小程序录制方法");
  608. const systemInfo = common_vendor.index.getSystemInfoSync();
  609. const isIOS = systemInfo.platform === "ios";
  610. if (isIOS) {
  611. this.resetCamera();
  612. setTimeout(() => {
  613. this.actualStartRecording(isIOS);
  614. }, 1e3);
  615. } else {
  616. this.actualStartRecording(isIOS);
  617. }
  618. },
  619. // 添加新方法:实际开始录制
  620. actualStartRecording(isIOS) {
  621. if (!this.cameraContext) {
  622. this.cameraContext = common_vendor.index.createCameraContext();
  623. console.log("创建新的相机上下文");
  624. }
  625. common_vendor.index.getSetting({
  626. success: (res) => {
  627. const hasRecordAuth = res.authSetting["scope.record"];
  628. const hasCameraAuth = res.authSetting["scope.camera"];
  629. if (!hasRecordAuth || !hasCameraAuth) {
  630. console.warn("缺少必要权限,请求权限");
  631. this.requestMiniProgramPermissions();
  632. return;
  633. }
  634. if (isIOS) {
  635. console.log("iOS: 检查相机状态");
  636. const options = {
  637. timeout: 3e5,
  638. // 300秒超时 (5分钟)
  639. quality: "low",
  640. // 降低质量
  641. compressed: true,
  642. success: () => {
  643. console.log("iOS录制开始成功");
  644. },
  645. fail: (err) => {
  646. console.error("iOS录制失败:", err);
  647. this.useAlternativeRecordingMethod();
  648. }
  649. };
  650. try {
  651. console.log("尝试开始录制");
  652. this.recorder = this.cameraContext.startRecord(options);
  653. } catch (e) {
  654. console.error("开始录制异常:", e);
  655. this.useAlternativeRecordingMethod();
  656. }
  657. } else {
  658. const options = {
  659. timeout: 3e5,
  660. // 300秒超时 (5分钟)
  661. quality: "medium",
  662. compressed: true,
  663. success: () => {
  664. console.log("Android录制开始成功");
  665. },
  666. fail: (err) => {
  667. console.error("Android录制失败:", err);
  668. common_vendor.index.showToast({
  669. title: "录制失败,请检查相机权限",
  670. icon: "none"
  671. });
  672. this.proceedToNextQuestion();
  673. }
  674. };
  675. this.recorder = this.cameraContext.startRecord(options);
  676. }
  677. }
  678. });
  679. },
  680. // 添加新方法:使用替代录制方法
  681. useAlternativeRecordingMethod() {
  682. console.log("使用替代录制方法");
  683. common_vendor.index.showActionSheet({
  684. itemList: ["使用相册中的视频", "跳过此问题"],
  685. success: (res) => {
  686. if (res.tapIndex === 0) {
  687. common_vendor.index.chooseVideo({
  688. sourceType: ["album"],
  689. maxDuration: 300,
  690. // 从60秒改为300秒
  691. camera: "front",
  692. success: (res2) => {
  693. console.log("选择视频成功:", res2.tempFilePath);
  694. this.isRecording = false;
  695. this.showStopRecordingButton = false;
  696. this.uploadRecordedVideo(res2.tempFilePath);
  697. },
  698. fail: () => {
  699. console.log("用户取消选择视频");
  700. this.proceedToNextQuestion();
  701. }
  702. });
  703. } else {
  704. console.log("用户选择跳过问题");
  705. this.proceedToNextQuestion();
  706. }
  707. },
  708. fail: () => {
  709. console.log("操作取消");
  710. this.proceedToNextQuestion();
  711. }
  712. });
  713. },
  714. // 添加新方法:请求小程序权限
  715. requestMiniProgramPermissions() {
  716. common_vendor.index.authorize({
  717. scope: "scope.record",
  718. success: () => {
  719. console.log("录音权限已获取");
  720. common_vendor.index.authorize({
  721. scope: "scope.camera",
  722. success: () => {
  723. console.log("相机权限已获取");
  724. this.startMiniProgramRecording();
  725. },
  726. fail: (err) => {
  727. console.error("相机权限获取失败:", err);
  728. this.showPermissionDialog("相机");
  729. }
  730. });
  731. },
  732. fail: (err) => {
  733. console.error("录音权限获取失败:", err);
  734. this.showPermissionDialog("录音");
  735. }
  736. });
  737. },
  738. // 修改浏览器环境下的录制方法
  739. startBrowserRecording() {
  740. if (!this.cameraStream) {
  741. console.error("没有可用的摄像头流");
  742. common_vendor.index.showToast({
  743. title: "录制失败,摄像头未就绪",
  744. icon: "none"
  745. });
  746. this.proceedToNextQuestion();
  747. return;
  748. }
  749. try {
  750. const hasAudio = this.cameraStream.getAudioTracks().length > 0;
  751. if (!hasAudio) {
  752. console.warn("警告:媒体流中没有音频轨道,尝试重新获取带音频的媒体流");
  753. navigator.mediaDevices.getUserMedia({
  754. audio: {
  755. echoCancellation: true,
  756. noiseSuppression: true,
  757. autoGainControl: true
  758. },
  759. video: true
  760. }).then((newStream) => {
  761. const audioTracks = newStream.getAudioTracks();
  762. if (audioTracks.length > 0) {
  763. console.log("成功获取音频轨道:", audioTracks[0].label);
  764. const videoTrack = this.cameraStream.getVideoTracks()[0];
  765. const audioTrack = newStream.getAudioTracks()[0];
  766. const combinedStream = new MediaStream();
  767. if (videoTrack)
  768. combinedStream.addTrack(videoTrack);
  769. if (audioTrack)
  770. combinedStream.addTrack(audioTrack);
  771. this.cameraStream = combinedStream;
  772. const videoElement = this.$refs.userCameraVideo;
  773. if (videoElement) {
  774. videoElement.srcObject = combinedStream;
  775. videoElement.muted = true;
  776. }
  777. this.setupMediaRecorder(combinedStream);
  778. } else {
  779. console.warn("仍然无法获取音频轨道");
  780. this.setupMediaRecorder(this.cameraStream);
  781. }
  782. }).catch((err) => {
  783. console.error("获取音频失败:", err);
  784. this.setupMediaRecorder(this.cameraStream);
  785. });
  786. } else {
  787. console.log("检测到音频轨道,直接使用");
  788. this.setupMediaRecorder(this.cameraStream);
  789. }
  790. } catch (error) {
  791. console.error("浏览器录制失败:", error);
  792. common_vendor.index.showToast({
  793. title: "录制失败,浏览器可能不支持此功能",
  794. icon: "none"
  795. });
  796. this.proceedToNextQuestion();
  797. }
  798. },
  799. // 修改 setupMediaRecorder 方法
  800. setupMediaRecorder(stream) {
  801. const videoTracks = stream.getVideoTracks();
  802. const audioTracks = stream.getAudioTracks();
  803. console.log("设置MediaRecorder - 视频轨道:", videoTracks.length, "音频轨道:", audioTracks.length);
  804. let mimeType = "";
  805. const supportedTypes = [
  806. "video/webm;codecs=vp9,opus",
  807. "video/webm;codecs=vp8,opus",
  808. "video/webm;codecs=h264,opus",
  809. "video/mp4;codecs=h264,aac",
  810. "video/webm",
  811. "video/mp4"
  812. ];
  813. for (const type of supportedTypes) {
  814. if (MediaRecorder.isTypeSupported(type)) {
  815. mimeType = type;
  816. console.log("使用支持的MIME类型:", mimeType);
  817. break;
  818. }
  819. }
  820. const options = {
  821. mimeType: mimeType || "",
  822. audioBitsPerSecond: 64e3,
  823. // 降低音频比特率
  824. videoBitsPerSecond: 1e6
  825. // 降低视频比特率到1Mbps
  826. };
  827. try {
  828. this.mediaRecorder = new MediaRecorder(stream, options);
  829. console.log("MediaRecorder创建成功,使用选项:", options);
  830. } catch (e) {
  831. console.warn("使用指定选项创建MediaRecorder失败,尝试使用默认选项");
  832. this.mediaRecorder = new MediaRecorder(stream);
  833. }
  834. this.recordedChunks = [];
  835. this.mediaRecorder.ondataavailable = (event) => {
  836. if (event.data && event.data.size > 0) {
  837. this.recordedChunks.push(event.data);
  838. console.log(`收到数据块: ${event.data.size} 字节`);
  839. }
  840. };
  841. this.mediaRecorder.onstop = async () => {
  842. console.log("MediaRecorder停止,数据块数量:", this.recordedChunks.length);
  843. if (this.recordedChunks.length === 0) {
  844. console.error("没有录制到数据");
  845. common_vendor.index.showToast({
  846. title: "录制失败,未捕获到数据",
  847. icon: "none"
  848. });
  849. this.proceedToNextQuestion();
  850. return;
  851. }
  852. const mimeType2 = this.mediaRecorder.mimeType || "video/webm";
  853. const blob = new Blob(this.recordedChunks, { type: mimeType2 });
  854. console.log("创建Blob,原始大小:", blob.size, "类型:", mimeType2);
  855. common_vendor.index.showLoading({
  856. title: "正在处理视频...",
  857. mask: true
  858. });
  859. try {
  860. const compressedBlob = await this.compressVideo(blob);
  861. const fileName = `answer_${this.currentVideoIndex}_${Date.now()}.webm`;
  862. const file = new File([compressedBlob], fileName, { type: mimeType2 });
  863. common_vendor.index.hideLoading();
  864. this.uploadRecordedVideo(file);
  865. } catch (error) {
  866. console.error("视频处理失败:", error);
  867. common_vendor.index.hideLoading();
  868. const fileName = `answer_${this.currentVideoIndex}_${Date.now()}.webm`;
  869. const file = new File([blob], fileName, { type: mimeType2 });
  870. this.uploadRecordedVideo(file);
  871. }
  872. };
  873. this.mediaRecorder.onerror = (event) => {
  874. console.error("MediaRecorder错误:", event.error);
  875. };
  876. try {
  877. this.mediaRecorder.start(1e3);
  878. console.log("MediaRecorder开始录制");
  879. this.mediaRecorderTimeout = setTimeout(() => {
  880. if (this.mediaRecorder && this.mediaRecorder.state === "recording") {
  881. console.log("MediaRecorder备份超时机制触发,停止录制");
  882. this.mediaRecorder.stop();
  883. }
  884. }, 3e5);
  885. } catch (e) {
  886. console.error("开始录制失败:", e);
  887. }
  888. },
  889. // 添加新方法:停止录制用户回答
  890. stopRecordingAnswer() {
  891. console.log("停止录制用户回答");
  892. if (this.countdownTimer) {
  893. clearInterval(this.countdownTimer);
  894. this.countdownTimer = null;
  895. this.showCountdown = false;
  896. }
  897. const recordingDuration = this.getRecordingDuration();
  898. const minimumDuration = 5;
  899. if (recordingDuration < minimumDuration) {
  900. common_vendor.index.showToast({
  901. title: "录制时间过短,请至少录制5秒",
  902. icon: "none",
  903. duration: 2e3
  904. });
  905. return;
  906. }
  907. this.completeRecordingStop();
  908. },
  909. // 添加新方法:获取录制时长
  910. getRecordingDuration() {
  911. if (this.recordingStartTime) {
  912. return (Date.now() - this.recordingStartTime) / 1e3;
  913. }
  914. if (this.mediaRecorder && this.$refs.userCameraVideo) {
  915. return this.$refs.userCameraVideo.currentTime || 0;
  916. }
  917. if (this.recordingTimerCount) {
  918. return this.recordingTimerCount;
  919. }
  920. return 0;
  921. },
  922. // 添加新方法:重置录制
  923. resetRecording() {
  924. if (this.recordingTimer) {
  925. clearTimeout(this.recordingTimer);
  926. }
  927. this.recordingStartTime = Date.now();
  928. this.recordingTimerCount = 0;
  929. if (this.mediaRecorder && this.mediaRecorder.state !== "inactive") {
  930. this.mediaRecorder.stop();
  931. this.recordedChunks = [];
  932. setTimeout(() => {
  933. this.startBrowserRecording();
  934. }, 500);
  935. } else if (this.cameraContext) {
  936. this.cameraContext.stopRecord({
  937. success: () => {
  938. console.log("重置录制:停止当前录制成功");
  939. setTimeout(() => {
  940. this.startMiniProgramRecording();
  941. }, 500);
  942. },
  943. fail: (err) => {
  944. console.error("重置录制:停止当前录制失败", err);
  945. this.startMiniProgramRecording();
  946. }
  947. });
  948. }
  949. common_vendor.index.showToast({
  950. title: "请重新开始回答",
  951. icon: "none",
  952. duration: 2e3
  953. });
  954. },
  955. // 添加新方法:完成录制停止流程
  956. completeRecordingStop() {
  957. this.isRecording = false;
  958. if (this.recordingTimer) {
  959. clearInterval(this.recordingTimer);
  960. this.recordingTimer = null;
  961. }
  962. if (this.mediaRecorderTimeout) {
  963. clearTimeout(this.mediaRecorderTimeout);
  964. this.mediaRecorderTimeout = null;
  965. }
  966. common_vendor.index.hideLoading();
  967. this.showStopRecordingButton = false;
  968. const systemInfo = common_vendor.index.getSystemInfoSync();
  969. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith("mp-");
  970. if (isMiniProgram) {
  971. this.stopMiniProgramRecording();
  972. } else {
  973. this.stopBrowserRecording();
  974. }
  975. },
  976. // 修改 stopMiniProgramRecording 方法
  977. stopMiniProgramRecording() {
  978. if (!this.cameraContext) {
  979. console.error("相机上下文不存在");
  980. this.proceedToNextQuestion();
  981. return;
  982. }
  983. const systemInfo = common_vendor.index.getSystemInfoSync();
  984. const isIOS = systemInfo.platform === "ios";
  985. const stopOptions = {
  986. success: (res) => {
  987. console.log("小程序录像停止成功:", res);
  988. const tempFilePath = res.tempVideoPath;
  989. if (!tempFilePath) {
  990. console.error("未获取到视频文件路径");
  991. common_vendor.index.showToast({
  992. title: "录制失败,未获取到视频文件",
  993. icon: "none"
  994. });
  995. this.proceedToNextQuestion();
  996. return;
  997. }
  998. if (isIOS) {
  999. common_vendor.index.getFileInfo({
  1000. filePath: tempFilePath,
  1001. success: () => {
  1002. this.uploadRecordedVideo(tempFilePath);
  1003. },
  1004. fail: (err) => {
  1005. console.error("视频文件不存在:", err);
  1006. common_vendor.index.showToast({
  1007. title: "录制失败,视频文件不存在",
  1008. icon: "none"
  1009. });
  1010. this.proceedToNextQuestion();
  1011. }
  1012. });
  1013. } else {
  1014. this.uploadRecordedVideo(tempFilePath);
  1015. }
  1016. },
  1017. fail: (err) => {
  1018. console.error("小程序录像停止失败:", err);
  1019. common_vendor.index.showToast({
  1020. title: "录制失败",
  1021. icon: "none"
  1022. });
  1023. this.proceedToNextQuestion();
  1024. }
  1025. };
  1026. this.cameraContext.stopRecord(stopOptions);
  1027. },
  1028. // 添加新方法:停止浏览器录制
  1029. stopBrowserRecording() {
  1030. if (this.mediaRecorder && this.mediaRecorder.state !== "inactive") {
  1031. this.mediaRecorder.stop();
  1032. console.log("浏览器录制停止成功");
  1033. } else {
  1034. console.error("MediaRecorder不存在或已经停止");
  1035. this.proceedToNextQuestion();
  1036. }
  1037. },
  1038. // 修改上传录制的视频方法
  1039. uploadRecordedVideo(fileOrPath) {
  1040. console.log("准备上传视频:", typeof fileOrPath === "string" ? fileOrPath : fileOrPath.name);
  1041. let questionId;
  1042. const currentQuestion = this.additionalQuestions[this.currentVideoIndex];
  1043. if (currentQuestion && currentQuestion.id) {
  1044. questionId = currentQuestion.id;
  1045. console.log(`使用API返回的问题ID: ${questionId}, 问题: ${currentQuestion.question}`);
  1046. } else {
  1047. questionId = this.getDefaultQuestionId(this.currentVideoIndex);
  1048. console.log(`未找到当前问题,使用默认ID: ${questionId}`);
  1049. }
  1050. console.log("上传视频对应的问题ID:", questionId);
  1051. const uploadTask = {
  1052. id: Date.now().toString(),
  1053. // 生成唯一ID
  1054. file: fileOrPath,
  1055. questionId,
  1056. attempts: 0,
  1057. // 上传尝试次数
  1058. maxAttempts: 3
  1059. // 最大尝试次数
  1060. };
  1061. this.uploadQueue.push(uploadTask);
  1062. this.uploadProgress[uploadTask.id] = 0;
  1063. this.uploadStatus[uploadTask.id] = "pending";
  1064. common_vendor.index.showToast({
  1065. title: "已完成回答",
  1066. icon: "none",
  1067. duration: 1500
  1068. });
  1069. this.updateUploadStatusText();
  1070. if (!this.isUploading) {
  1071. this.processUploadQueue();
  1072. }
  1073. this.proceedToNextQuestion();
  1074. },
  1075. // 添加新方法:处理上传队列
  1076. processUploadQueue() {
  1077. if (this.uploadQueue.length === 0) {
  1078. this.isUploading = false;
  1079. this.showUploadStatus = false;
  1080. return;
  1081. }
  1082. this.isUploading = true;
  1083. this.showUploadStatus = true;
  1084. const task = this.uploadQueue[0];
  1085. this.uploadStatus[task.id] = "uploading";
  1086. this.updateUploadStatusText();
  1087. task.attempts++;
  1088. if (typeof task.file !== "string") {
  1089. this.uploadFileWithXHR(task);
  1090. } else {
  1091. this.uploadFileWithUni(task);
  1092. }
  1093. },
  1094. // 添加新方法:使用XMLHttpRequest上传文件
  1095. uploadFileWithXHR(task) {
  1096. const userInfo = common_vendor.index.getStorageSync("userInfo");
  1097. const openid = userInfo ? JSON.parse(userInfo).openid || "" : "";
  1098. const tenant_id = JSON.parse(common_vendor.index.getStorageSync("userInfo")).tenant_id || "1";
  1099. const formData = new FormData();
  1100. formData.append("file", task.file);
  1101. formData.append("openid", openid);
  1102. formData.append("tenant_id", tenant_id);
  1103. formData.append("application_id", common_vendor.index.getStorageSync("appId"));
  1104. formData.append("question_id", task.questionId);
  1105. formData.append("video_duration", 0);
  1106. formData.append("has_audio", "true");
  1107. const xhr = new XMLHttpRequest();
  1108. xhr.open("POST", `${common_config.apiBaseUrl}/api/upload/`, true);
  1109. xhr.timeout = 12e4;
  1110. xhr.upload.onprogress = (event) => {
  1111. if (event.lengthComputable) {
  1112. const percentComplete = Math.round(event.loaded / event.total * 100);
  1113. this.uploadProgress[task.id] = percentComplete;
  1114. this.updateUploadStatusText();
  1115. }
  1116. };
  1117. xhr.onload = () => {
  1118. if (xhr.status === 200) {
  1119. try {
  1120. const res = JSON.parse(xhr.responseText);
  1121. console.log("上传响应:", res);
  1122. if (res.code === 2e3) {
  1123. const videoUrl = res.data.url || res.data.photoUrl || "";
  1124. if (videoUrl) {
  1125. this.uploadStatus[task.id] = "success";
  1126. this.updateUploadStatusText();
  1127. this.submitVideoToInterview(videoUrl, task);
  1128. } else {
  1129. this.handleUploadFailure(task, "视频URL获取失败");
  1130. }
  1131. } else {
  1132. this.handleUploadFailure(task, res.msg || "上传失败");
  1133. }
  1134. } catch (e) {
  1135. this.handleUploadFailure(task, "解析响应失败");
  1136. }
  1137. } else {
  1138. this.handleUploadFailure(task, "HTTP状态: " + xhr.status);
  1139. }
  1140. };
  1141. xhr.onerror = () => {
  1142. this.handleUploadFailure(task, "网络错误");
  1143. };
  1144. xhr.ontimeout = () => {
  1145. this.handleUploadFailure(task, "上传超时");
  1146. };
  1147. xhr.send(formData);
  1148. },
  1149. // 添加新方法:使用uni.uploadFile上传文件
  1150. uploadFileWithUni(task) {
  1151. const userInfo = common_vendor.index.getStorageSync("userInfo");
  1152. const openid = userInfo ? JSON.parse(userInfo).openid || "" : "";
  1153. const tenant_id = JSON.parse(common_vendor.index.getStorageSync("userInfo")).tenant_id || "1";
  1154. const uploadTask = common_vendor.index.uploadFile({
  1155. url: `${common_config.apiBaseUrl}/api/upload/`,
  1156. filePath: task.file,
  1157. name: "file",
  1158. formData: {
  1159. openid,
  1160. tenant_id,
  1161. application_id: common_vendor.index.getStorageSync("appId"),
  1162. question_id: task.questionId,
  1163. video_duration: 0,
  1164. has_audio: "true"
  1165. },
  1166. success: (uploadRes) => {
  1167. try {
  1168. const res = JSON.parse(uploadRes.data);
  1169. console.log("上传响应:", res);
  1170. if (res.code === 2e3) {
  1171. const videoUrl = res.data.permanent_link || res.data.url || "";
  1172. if (videoUrl) {
  1173. this.uploadStatus[task.id] = "success";
  1174. this.updateUploadStatusText();
  1175. this.submitVideoToInterview(videoUrl, task);
  1176. } else {
  1177. this.handleUploadFailure(task, "视频URL获取失败");
  1178. }
  1179. } else {
  1180. this.handleUploadFailure(task, res.msg || "上传失败");
  1181. }
  1182. } catch (e) {
  1183. this.handleUploadFailure(task, "解析响应失败");
  1184. }
  1185. },
  1186. fail: (err) => {
  1187. this.handleUploadFailure(task, err.errMsg || "上传失败");
  1188. }
  1189. });
  1190. uploadTask.onProgressUpdate((res) => {
  1191. this.uploadProgress[task.id] = res.progress;
  1192. this.updateUploadStatusText();
  1193. });
  1194. },
  1195. // 添加新方法:处理上传失败
  1196. handleUploadFailure(task, errorMsg) {
  1197. console.error("上传失败:", errorMsg);
  1198. this.uploadStatus[task.id] = "failed";
  1199. this.updateUploadStatusText();
  1200. if (task.attempts < task.maxAttempts) {
  1201. console.log(`将在5秒后重试上传,当前尝试次数: ${task.attempts}/${task.maxAttempts}`);
  1202. setTimeout(() => {
  1203. this.uploadProgress[task.id] = 0;
  1204. if (typeof task.file !== "string") {
  1205. this.uploadFileWithXHR(task);
  1206. } else {
  1207. this.uploadFileWithUni(task);
  1208. }
  1209. }, 5e3);
  1210. } else {
  1211. console.log("超过最大重试次数,放弃上传");
  1212. common_vendor.index.showToast({
  1213. title: "视频上传失败,请稍后重试",
  1214. icon: "none",
  1215. duration: 2e3
  1216. });
  1217. this.uploadQueue.shift();
  1218. this.processUploadQueue();
  1219. }
  1220. },
  1221. // 修改 submitVideoToInterview 方法
  1222. submitVideoToInterview(videoUrl, task = null) {
  1223. console.log("提交视频URL到面试接口:", videoUrl);
  1224. let questionId;
  1225. if (task) {
  1226. questionId = task.questionId;
  1227. } else {
  1228. if (this.currentVideoIndex >= 1 && this.questions.length > 0) {
  1229. const currentQuestion = this.getCurrentQuestionByIndex(this.currentVideoIndex);
  1230. if (currentQuestion && currentQuestion.id) {
  1231. questionId = currentQuestion.id;
  1232. console.log(`使用API返回的问题ID: ${questionId}, 问题: ${currentQuestion.question}`);
  1233. } else {
  1234. questionId = this.getDefaultQuestionId(this.currentVideoIndex);
  1235. console.log(`未找到当前问题,使用默认ID: ${questionId}`);
  1236. }
  1237. } else {
  1238. questionId = this.getDefaultQuestionId(this.currentVideoIndex);
  1239. console.log(`使用备用问题ID: ${questionId} (问题索引: ${this.currentVideoIndex})`);
  1240. }
  1241. }
  1242. const requestData = {
  1243. application_id: common_vendor.index.getStorageSync("appId"),
  1244. question_id: questionId,
  1245. video_url: videoUrl,
  1246. tenant_id: JSON.parse(common_vendor.index.getStorageSync("userInfo")).tenant_id || "1"
  1247. };
  1248. console.log("提交面试请求参数:", requestData);
  1249. common_vendor.index.request({
  1250. url: `${common_config.apiBaseUrl}/api/job/upload_video`,
  1251. method: "POST",
  1252. data: requestData,
  1253. header: {
  1254. "content-type": "application/x-www-form-urlencoded"
  1255. },
  1256. success: (res) => {
  1257. console.log("面试接口提交成功:", res);
  1258. if (res.data.code === 0 || res.data.code === 2e3) {
  1259. if (task) {
  1260. this.uploadQueue.shift();
  1261. this.processUploadQueue();
  1262. } else {
  1263. common_vendor.index.showToast({
  1264. title: "回答已提交",
  1265. icon: "success"
  1266. });
  1267. this.lastUploadedVideoUrl = videoUrl;
  1268. this.showRetryButton = false;
  1269. this.lastVideoToRetry = null;
  1270. }
  1271. } else {
  1272. if (task) {
  1273. this.handleSubmitFailure(task, res.data.msg || "提交失败");
  1274. } else {
  1275. common_vendor.index.showToast({
  1276. title: res.data.msg || "提交失败,请重试",
  1277. icon: "none"
  1278. });
  1279. this.lastVideoToRetry = videoUrl;
  1280. this.showRetryButton = true;
  1281. }
  1282. }
  1283. },
  1284. fail: (err) => {
  1285. console.error("面试接口提交失败:", err);
  1286. if (task) {
  1287. this.handleSubmitFailure(task, err.errMsg || "网络错误");
  1288. } else {
  1289. common_vendor.index.hideLoading();
  1290. common_vendor.index.showToast({
  1291. title: "网络错误,请重试",
  1292. icon: "none"
  1293. });
  1294. this.lastVideoToRetry = videoUrl;
  1295. this.showRetryButton = true;
  1296. }
  1297. }
  1298. });
  1299. },
  1300. // 添加新方法:处理提交失败
  1301. handleSubmitFailure(task, errorMsg) {
  1302. console.error("提交失败:", errorMsg);
  1303. this.uploadStatus[task.id] = "failed";
  1304. this.updateUploadStatusText();
  1305. if (task.attempts < task.maxAttempts) {
  1306. console.log(`将在5秒后重试提交,当前尝试次数: ${task.attempts}/${task.maxAttempts}`);
  1307. setTimeout(() => {
  1308. this.submitVideoToInterview(task.videoUrl, task);
  1309. }, 5e3);
  1310. } else {
  1311. console.log("超过最大重试次数,放弃提交");
  1312. common_vendor.index.showToast({
  1313. title: "视频提交失败,请稍后重试",
  1314. icon: "none",
  1315. duration: 2e3
  1316. });
  1317. this.uploadQueue.shift();
  1318. this.processUploadQueue();
  1319. }
  1320. },
  1321. // 添加新方法:更新上传状态文本
  1322. updateUploadStatusText() {
  1323. if (this.uploadQueue.length === 0) {
  1324. this.uploadStatusText = "";
  1325. return;
  1326. }
  1327. const currentTask = this.uploadQueue[0];
  1328. const progress = this.uploadProgress[currentTask.id] || 0;
  1329. const status = this.uploadStatus[currentTask.id] || "pending";
  1330. let statusText = "";
  1331. switch (status) {
  1332. case "pending":
  1333. statusText = "等待上传";
  1334. break;
  1335. case "uploading":
  1336. statusText = `上传中 ${progress}%`;
  1337. break;
  1338. case "success":
  1339. statusText = "上传成功,提交中...";
  1340. break;
  1341. case "failed":
  1342. statusText = `上传失败,${currentTask.attempts < currentTask.maxAttempts ? "即将重试" : "已放弃"}`;
  1343. break;
  1344. }
  1345. this.uploadStatusText = `问题${currentTask.questionId - 9}:${statusText}`;
  1346. if (this.uploadQueue.length > 1) {
  1347. this.uploadStatusText += ` (${this.uploadQueue.length}个视频待处理)`;
  1348. }
  1349. },
  1350. // 修改 proceedToNextQuestion 方法
  1351. proceedToNextQuestion() {
  1352. if (this.currentVideoIndex >= this.additionalQuestions.length - 1) {
  1353. common_vendor.index.navigateTo({
  1354. url: "/pages/camera/camera"
  1355. });
  1356. return;
  1357. }
  1358. this.currentVideoIndex++;
  1359. if (this.currentVideoIndex < this.videoList.length) {
  1360. this.videoUrl = this.videoList[this.currentVideoIndex];
  1361. this.videoPlaying = true;
  1362. this.currentSubtitle = "";
  1363. this.$nextTick(() => {
  1364. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  1365. if (videoContext) {
  1366. videoContext.play();
  1367. }
  1368. });
  1369. } else {
  1370. common_vendor.index.showToast({
  1371. title: "追加问题已完成",
  1372. icon: "success",
  1373. duration: 2e3
  1374. });
  1375. setTimeout(() => {
  1376. common_vendor.index.navigateTo({
  1377. url: "/pages/camera/camera"
  1378. });
  1379. }, 2e3);
  1380. }
  1381. },
  1382. // 修改 handleAnswerButtonClick 方法
  1383. handleAnswerButtonClick() {
  1384. this.showAnswerButton = false;
  1385. this.proceedToNextQuestion();
  1386. },
  1387. // 处理相机错误
  1388. handleCameraError(e) {
  1389. console.error("相机错误:", e);
  1390. const systemInfo = common_vendor.index.getSystemInfoSync();
  1391. const isIOS = systemInfo.platform === "ios";
  1392. if (isIOS) {
  1393. console.log("iOS相机错误,尝试重新初始化");
  1394. common_vendor.index.showToast({
  1395. title: "相机初始化中...",
  1396. icon: "loading",
  1397. duration: 2e3
  1398. });
  1399. this.resetCamera();
  1400. if (this.isRecording) {
  1401. this.isRecording = false;
  1402. this.showStopRecordingButton = false;
  1403. setTimeout(() => {
  1404. this.useAlternativeRecordingMethod();
  1405. }, 1e3);
  1406. }
  1407. } else {
  1408. common_vendor.index.showToast({
  1409. title: "相机初始化失败,请检查权限设置",
  1410. icon: "none"
  1411. });
  1412. this.tryFallbackOptions();
  1413. }
  1414. },
  1415. // 添加新方法:尝试备用选项
  1416. tryFallbackOptions() {
  1417. const systemInfo = common_vendor.index.getSystemInfoSync();
  1418. if (systemInfo.uniPlatform === "mp-weixin" || systemInfo.uniPlatform === "mp-alipay") {
  1419. this.useMiniProgramCamera();
  1420. } else {
  1421. this.showStaticCameraPlaceholder();
  1422. }
  1423. },
  1424. // 添加新方法:使用小程序相机API
  1425. useMiniProgramCamera() {
  1426. console.log("尝试使用小程序相机组件");
  1427. this.useMiniProgramCameraComponent = true;
  1428. },
  1429. // 添加新方法:显示静态图像
  1430. showStaticCameraPlaceholder() {
  1431. console.log("显示静态摄像头占位图");
  1432. const img = document.createElement("img");
  1433. img.src = "/static/images/camera-placeholder.png";
  1434. img.className = "static-camera-image";
  1435. img.style.width = "100%";
  1436. img.style.height = "100%";
  1437. img.style.objectFit = "cover";
  1438. const container = this.$refs.userCameraVideo.parentNode;
  1439. container.appendChild(img);
  1440. },
  1441. // 修改 handleTimeUpdate 方法,确保正确显示追加问题的字幕
  1442. handleTimeUpdate(e) {
  1443. const currentTime = e.target.currentTime;
  1444. if (this.isRecording && this.recordingTimerCount) {
  1445. this.recordingTimeDisplay = this.formatTime(this.recordingTimerCount);
  1446. }
  1447. if (this.currentVideoIndex >= 0 && this.currentVideoIndex < this.additionalQuestions.length) {
  1448. const currentQuestion = this.additionalQuestions[this.currentVideoIndex];
  1449. if (currentQuestion && currentQuestion.subtitles) {
  1450. const subtitle = currentQuestion.subtitles.find(
  1451. (sub) => currentTime >= sub.startTime && currentTime < sub.endTime
  1452. );
  1453. this.currentSubtitle = subtitle ? subtitle.text : "";
  1454. } else {
  1455. this.currentSubtitle = currentQuestion.question || "";
  1456. }
  1457. } else {
  1458. this.currentSubtitle = "";
  1459. }
  1460. },
  1461. // Add a new method to handle the "Start Recording" button click
  1462. handleStartRecordingClick() {
  1463. this.showStartRecordingButton = false;
  1464. this.clearCountdown();
  1465. this.startRecordingAnswer();
  1466. },
  1467. // 修改 checkAudioPermission 方法,确保在录制前获取音频权限
  1468. checkAudioPermission() {
  1469. const systemInfo = common_vendor.index.getSystemInfoSync();
  1470. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith("mp-");
  1471. if (isMiniProgram) {
  1472. common_vendor.index.getSetting({
  1473. success: (res) => {
  1474. if (!res.authSetting["scope.record"]) {
  1475. common_vendor.index.authorize({
  1476. scope: "scope.record",
  1477. success: () => {
  1478. console.log("录音权限已获取");
  1479. },
  1480. fail: (err) => {
  1481. console.error("录音权限获取失败:", err);
  1482. this.showPermissionDialog("录音");
  1483. }
  1484. });
  1485. }
  1486. if (!res.authSetting["scope.camera"]) {
  1487. common_vendor.index.authorize({
  1488. scope: "scope.camera",
  1489. success: () => {
  1490. console.log("相机权限已获取");
  1491. },
  1492. fail: (err) => {
  1493. console.error("相机权限获取失败:", err);
  1494. this.showPermissionDialog("相机");
  1495. }
  1496. });
  1497. }
  1498. }
  1499. });
  1500. }
  1501. },
  1502. // 添加新方法:测试音频输入
  1503. testAudioInput() {
  1504. if (!this.cameraStream) {
  1505. console.warn("没有可用的媒体流,无法测试音频");
  1506. return;
  1507. }
  1508. const audioTracks = this.cameraStream.getAudioTracks();
  1509. if (audioTracks.length === 0) {
  1510. console.warn("没有检测到音频轨道,尝试重新获取");
  1511. this.tryGetAudioOnly();
  1512. return;
  1513. }
  1514. console.log("音频轨道信息:", audioTracks[0].getSettings());
  1515. try {
  1516. const AudioContext = window.AudioContext || window.webkitAudioContext;
  1517. if (!AudioContext) {
  1518. console.warn("浏览器不支持AudioContext");
  1519. return;
  1520. }
  1521. const audioContext = new AudioContext();
  1522. const analyser = audioContext.createAnalyser();
  1523. const microphone = audioContext.createMediaStreamSource(this.cameraStream);
  1524. microphone.connect(analyser);
  1525. analyser.fftSize = 256;
  1526. const bufferLength = analyser.frequencyBinCount;
  1527. const dataArray = new Uint8Array(bufferLength);
  1528. let silenceCounter = 0;
  1529. const checkAudio = () => {
  1530. if (this.isRecording)
  1531. return;
  1532. analyser.getByteFrequencyData(dataArray);
  1533. let sum = 0;
  1534. for (let i = 0; i < bufferLength; i++) {
  1535. sum += dataArray[i];
  1536. }
  1537. const average = sum / bufferLength;
  1538. if (average > 10) {
  1539. console.log("检测到音频输入,音量:", average);
  1540. silenceCounter = 0;
  1541. } else {
  1542. silenceCounter++;
  1543. if (silenceCounter > 10) {
  1544. console.warn("持续检测不到音频输入,可能麦克风未正常工作");
  1545. silenceCounter = 0;
  1546. }
  1547. }
  1548. requestAnimationFrame(checkAudio);
  1549. };
  1550. checkAudio();
  1551. } catch (e) {
  1552. console.error("音频测试失败:", e);
  1553. }
  1554. },
  1555. // 添加新方法:尝试单独获取音频
  1556. tryGetAudioOnly() {
  1557. navigator.mediaDevices.getUserMedia({ audio: true }).then((audioStream) => {
  1558. if (this.cameraStream) {
  1559. const videoTrack = this.cameraStream.getVideoTracks()[0];
  1560. const audioTrack = audioStream.getAudioTracks()[0];
  1561. const combinedStream = new MediaStream();
  1562. if (videoTrack)
  1563. combinedStream.addTrack(videoTrack);
  1564. if (audioTrack)
  1565. combinedStream.addTrack(audioTrack);
  1566. this.cameraStream = combinedStream;
  1567. const videoElement = this.$refs.userCameraVideo;
  1568. if (videoElement) {
  1569. videoElement.srcObject = combinedStream;
  1570. videoElement.muted = true;
  1571. }
  1572. console.log("成功合并音频和视频轨道");
  1573. } else {
  1574. console.warn("没有视频流可合并");
  1575. }
  1576. }).catch((err) => {
  1577. console.error("单独获取音频失败:", err);
  1578. });
  1579. },
  1580. // 添加新方法:显示权限对话框
  1581. showPermissionDialog(permissionType) {
  1582. common_vendor.index.showModal({
  1583. title: "需要权限",
  1584. content: `请允许使用${permissionType}权限,否则可能影响面试功能`,
  1585. confirmText: "去设置",
  1586. success: (res) => {
  1587. if (res.confirm) {
  1588. common_vendor.index.openSetting({
  1589. success: (settingRes) => {
  1590. console.log("设置页面打开成功", settingRes);
  1591. }
  1592. });
  1593. }
  1594. }
  1595. });
  1596. },
  1597. // 添加重试上传方法
  1598. retryVideoUpload() {
  1599. if (this.lastVideoToRetry) {
  1600. this.showRetryButton = false;
  1601. common_vendor.index.showLoading({
  1602. title: "正在重新提交...",
  1603. mask: true
  1604. });
  1605. this.submitVideoToInterview(this.lastVideoToRetry);
  1606. } else {
  1607. common_vendor.index.showToast({
  1608. title: "没有可重试的视频",
  1609. icon: "none"
  1610. });
  1611. }
  1612. },
  1613. // 添加一个新方法用于压缩视频
  1614. async compressVideo(videoBlob) {
  1615. if (videoBlob.size < 5 * 1024 * 1024) {
  1616. return videoBlob;
  1617. }
  1618. console.log("开始压缩视频,原始大小:", videoBlob.size);
  1619. const videoElement = document.createElement("video");
  1620. videoElement.muted = true;
  1621. videoElement.autoplay = false;
  1622. const canvas = document.createElement("canvas");
  1623. const ctx = canvas.getContext("2d");
  1624. videoElement.src = URL.createObjectURL(videoBlob);
  1625. return new Promise((resolve) => {
  1626. videoElement.onloadedmetadata = () => {
  1627. const width = Math.floor(videoElement.videoWidth / 2);
  1628. const height = Math.floor(videoElement.videoHeight / 2);
  1629. canvas.width = width;
  1630. canvas.height = height;
  1631. const stream = canvas.captureStream(15);
  1632. if (videoElement.captureStream) {
  1633. const originalStream = videoElement.captureStream();
  1634. const audioTracks = originalStream.getAudioTracks();
  1635. if (audioTracks.length > 0) {
  1636. stream.addTrack(audioTracks[0]);
  1637. }
  1638. }
  1639. const options = {
  1640. mimeType: "video/webm;codecs=vp8,opus",
  1641. audioBitsPerSecond: 64e3,
  1642. videoBitsPerSecond: 8e5
  1643. // 800kbps
  1644. };
  1645. const mediaRecorder = new MediaRecorder(stream, options);
  1646. const chunks = [];
  1647. mediaRecorder.ondataavailable = (e) => {
  1648. if (e.data.size > 0) {
  1649. chunks.push(e.data);
  1650. }
  1651. };
  1652. mediaRecorder.onstop = () => {
  1653. const compressedBlob = new Blob(chunks, { type: "video/webm" });
  1654. console.log("视频压缩完成,压缩后大小:", compressedBlob.size);
  1655. resolve(compressedBlob);
  1656. };
  1657. videoElement.onplay = () => {
  1658. mediaRecorder.start(100);
  1659. const drawFrame = () => {
  1660. if (videoElement.paused || videoElement.ended) {
  1661. mediaRecorder.stop();
  1662. return;
  1663. }
  1664. ctx.drawImage(videoElement, 0, 0, width, height);
  1665. requestAnimationFrame(drawFrame);
  1666. };
  1667. drawFrame();
  1668. };
  1669. videoElement.play();
  1670. };
  1671. });
  1672. },
  1673. // 修改 checkIOSCameraRecordPermission 方法
  1674. checkIOSCameraRecordPermission() {
  1675. const systemInfo = common_vendor.index.getSystemInfoSync();
  1676. if (systemInfo.platform !== "ios")
  1677. return;
  1678. common_vendor.index.getSetting({
  1679. success: (res) => {
  1680. if (!res.authSetting["scope.camera"]) {
  1681. common_vendor.index.authorize({
  1682. scope: "scope.camera",
  1683. success: () => {
  1684. console.log("iOS相机权限已获取");
  1685. },
  1686. fail: (err) => {
  1687. console.error("iOS相机权限获取失败:", err);
  1688. this.showPermissionDialog("相机");
  1689. }
  1690. });
  1691. }
  1692. if (!res.authSetting["scope.record"]) {
  1693. common_vendor.index.authorize({
  1694. scope: "scope.record",
  1695. success: () => {
  1696. console.log("iOS录音权限已获取");
  1697. },
  1698. fail: (err) => {
  1699. console.error("iOS录音权限获取失败:", err);
  1700. this.showPermissionDialog("录音");
  1701. }
  1702. });
  1703. }
  1704. }
  1705. });
  1706. },
  1707. // 添加新方法:检查并修复渲染问题
  1708. checkAndFixRenderingIssues() {
  1709. try {
  1710. if (typeof u !== "undefined" && u) {
  1711. if (!u.currentQuestion) {
  1712. console.log("修复: 创建缺失的currentQuestion对象");
  1713. u.currentQuestion = {};
  1714. }
  1715. if (u.currentQuestion && typeof u.currentQuestion.isImportant === "undefined") {
  1716. console.log("修复: 设置缺失的isImportant属性");
  1717. u.currentQuestion.isImportant = false;
  1718. }
  1719. }
  1720. } catch (e) {
  1721. console.log("防御性检查异常:", e);
  1722. }
  1723. },
  1724. // 添加格式化时间的辅助方法
  1725. formatTime(seconds) {
  1726. if (!seconds && seconds !== 0)
  1727. return "03:30";
  1728. const minutes = Math.floor(seconds / 60);
  1729. const remainingSeconds = seconds % 60;
  1730. return `${minutes.toString().padStart(2, "0")}:${remainingSeconds.toString().padStart(2, "0")}`;
  1731. },
  1732. // 添加获取问题数据的方法
  1733. fetchQuestions() {
  1734. this.loading = true;
  1735. const tenant_id = JSON.parse(common_vendor.index.getStorageSync("userInfo")).tenant_id || "1";
  1736. let position_id = 1;
  1737. try {
  1738. const selectedJob = JSON.parse(common_vendor.index.getStorageSync("selectedJob") || "{}");
  1739. if (selectedJob && selectedJob.id) {
  1740. position_id = selectedJob.id;
  1741. console.log("使用选择的职位ID获取问题:", position_id);
  1742. } else {
  1743. console.warn("未找到选择的职位信息,使用默认职位ID:", position_id);
  1744. }
  1745. } catch (e) {
  1746. console.error("解析职位信息失败:", e);
  1747. }
  1748. const timestamp = Date.now();
  1749. const requestUrl = `${common_config.apiBaseUrl}/api/wechat/open_questions/?position_id=${position_id}&tenant_id=${tenant_id}&question_form=0&_t=${timestamp}`;
  1750. console.log("完整的请求URL:", requestUrl);
  1751. common_vendor.index.request({
  1752. url: requestUrl,
  1753. method: "GET",
  1754. success: (res) => {
  1755. if (res.data && res.data.code === 2e3 && res.data.data && res.data.data.items) {
  1756. console.log("获取问题数据成功:", res.data.data.items);
  1757. this.questions = res.data.data.items;
  1758. this.processQuestionData();
  1759. this.playIntroVideo();
  1760. } else {
  1761. console.error("获取问题数据失败:", res.data);
  1762. common_vendor.index.showToast({
  1763. title: "获取问题数据失败",
  1764. icon: "none"
  1765. });
  1766. }
  1767. },
  1768. fail: (err) => {
  1769. console.error("请求问题数据失败:", err);
  1770. common_vendor.index.showToast({
  1771. title: "网络错误,请检查网络连接",
  1772. icon: "none"
  1773. });
  1774. },
  1775. complete: () => {
  1776. this.loading = false;
  1777. }
  1778. });
  1779. },
  1780. // 处理问题数据,提取视频URL和字幕
  1781. processQuestionData() {
  1782. this.videoList = [];
  1783. this.videoList.push(this.introVideoUrl);
  1784. this.subtitles = [
  1785. {
  1786. startTime: 0,
  1787. endTime: 5,
  1788. text: "你好,我是本次面试的面试官,欢迎参加本公司的线上面试!"
  1789. },
  1790. {
  1791. startTime: 5,
  1792. endTime: 13,
  1793. text: "面试预计需要15分钟,请你提前安排在网络良好、光线亮度合适、且相对安静的环境参加这次面试"
  1794. },
  1795. {
  1796. startTime: 13,
  1797. endTime: 20,
  1798. text: "以免影响本次面试的结果。如果你在面试过程中遇到问题,请与我们的招聘人员联系。"
  1799. }
  1800. ];
  1801. const sortedQuestions = [...this.questions].sort((a, b) => a.sequence_number - b.sequence_number);
  1802. const questionsToUse = sortedQuestions.slice(0, 5);
  1803. questionsToUse.forEach((question) => {
  1804. if (question.digital_human_video_url) {
  1805. this.videoList.push(question.digital_human_video_url);
  1806. const subtitleArray = [{
  1807. startTime: 0,
  1808. endTime: 10,
  1809. // 默认10秒,可以根据实际情况调整
  1810. text: question.digital_human_video_subtitle || question.question
  1811. }];
  1812. const index = this.videoList.length - 1;
  1813. this[`question${index}Subtitles`] = subtitleArray;
  1814. }
  1815. });
  1816. if (this.videoList.length <= 1)
  1817. ;
  1818. else {
  1819. console.log("处理后的视频列表:", this.videoList);
  1820. console.log("处理后的字幕:", this.subtitles);
  1821. }
  1822. },
  1823. // 使用默认视频和字幕(作为备用)
  1824. useDefaultVideosAndSubtitles() {
  1825. console.log("使用默认视频和字幕");
  1826. this.subtitles = [
  1827. {
  1828. startTime: 0,
  1829. endTime: 5,
  1830. text: "你好,我是本次面试的面试官,欢迎参加本公司的线上面试!"
  1831. },
  1832. {
  1833. startTime: 5,
  1834. endTime: 13,
  1835. text: "面试预计需要15分钟,请你提前安排在网络良好、光线亮度合适、且相对安静的环境参加这次面试"
  1836. },
  1837. {
  1838. startTime: 13,
  1839. endTime: 20,
  1840. text: "以免影响本次面试的结果。如果你在面试过程中遇到问题,请与我们的招聘人员联系。"
  1841. }
  1842. ];
  1843. this.question1Subtitles = [{
  1844. startTime: 0,
  1845. endTime: 10,
  1846. text: "请结合您的基本信息与过往履历进行简单的自我介绍,并讲一讲您有哪些优势胜任本岗位:"
  1847. }];
  1848. this.question2Subtitles = [{
  1849. startTime: 0,
  1850. endTime: 4,
  1851. text: "在工作中,你如何确保个人防护装备的正确使用?"
  1852. }];
  1853. this.question3Subtitles = [{
  1854. startTime: 0,
  1855. endTime: 4,
  1856. text: "描述一次你与团队合作改善生产流程的经历。"
  1857. }];
  1858. this.question4Subtitles = [{
  1859. startTime: 0,
  1860. endTime: 6,
  1861. text: "你在团队合作中曾遇到过哪些挑战?如何解决团队内部的分歧?"
  1862. }];
  1863. this.question5Subtitles = [{
  1864. startTime: 0,
  1865. endTime: 5,
  1866. text: "您已完成本次面试全部题目,请问您对于这个岗位还有什么想要了解的吗?"
  1867. }];
  1868. },
  1869. // 播放介绍视频
  1870. playIntroVideo() {
  1871. this.videoUrl = this.videoList[0];
  1872. this.videoPlaying = true;
  1873. this.$nextTick(() => {
  1874. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  1875. if (videoContext) {
  1876. videoContext.play();
  1877. }
  1878. });
  1879. },
  1880. // 添加新方法:获取默认问题ID
  1881. getDefaultQuestionId(videoIndex) {
  1882. switch (videoIndex) {
  1883. case 1:
  1884. return 10;
  1885. case 2:
  1886. return 11;
  1887. case 3:
  1888. return 12;
  1889. case 4:
  1890. return 13;
  1891. default:
  1892. return 10;
  1893. }
  1894. },
  1895. // 添加新方法:根据索引获取当前问题
  1896. getCurrentQuestionByIndex(videoIndex) {
  1897. if (videoIndex >= 0 && videoIndex < this.additionalQuestions.length) {
  1898. return this.additionalQuestions[videoIndex];
  1899. }
  1900. return null;
  1901. },
  1902. onShow() {
  1903. console.log("followUp页面onShow");
  1904. console.log("当前本地存储中的职位信息:", common_vendor.index.getStorageSync("selectedJob"));
  1905. this.fetchAdditionalQuestions();
  1906. },
  1907. // 获取追加问题
  1908. fetchAdditionalQuestions() {
  1909. this.loading = true;
  1910. const tenant_id = JSON.parse(common_vendor.index.getStorageSync("userInfo")).tenant_id || "1";
  1911. let position_id = 1;
  1912. try {
  1913. const selectedJob = JSON.parse(common_vendor.index.getStorageSync("selectedJob") || "{}");
  1914. if (selectedJob && selectedJob.id) {
  1915. position_id = selectedJob.id;
  1916. console.log("使用选择的职位ID获取追加问题:", position_id);
  1917. } else {
  1918. console.warn("未找到选择的职位信息,使用默认职位ID:", position_id);
  1919. }
  1920. } catch (e) {
  1921. console.error("解析职位信息失败:", e);
  1922. }
  1923. const requestUrl = `${common_config.apiBaseUrl}/api/job/additional_questions?position_id=${position_id}&tenant_id=${tenant_id}&count=2`;
  1924. common_vendor.index.request({
  1925. url: requestUrl,
  1926. method: "GET",
  1927. success: (res) => {
  1928. if (res.data && res.data.code === 2e3 && Array.isArray(res.data.data)) {
  1929. console.log("获取追加问题成功:", res.data.data);
  1930. this.additionalQuestions = res.data.data.map((question) => ({
  1931. ...question,
  1932. videoUrl: question.digital_human_video_url,
  1933. subtitles: [{
  1934. startTime: 0,
  1935. endTime: 60,
  1936. // 增加字幕显示时间到60秒,确保覆盖整个视频
  1937. text: question.digital_human_video_subtitle || question.question || "请回答问题"
  1938. }]
  1939. }));
  1940. this.initializeVideoList();
  1941. } else {
  1942. console.error("获取追加问题失败:", res.data);
  1943. common_vendor.index.showToast({
  1944. title: "获取追加问题失败",
  1945. icon: "none"
  1946. });
  1947. }
  1948. },
  1949. fail: (err) => {
  1950. console.error("请求追加问题失败:", err);
  1951. common_vendor.index.showToast({
  1952. title: "网络错误,请检查网络连接",
  1953. icon: "none"
  1954. });
  1955. },
  1956. complete: () => {
  1957. this.loading = false;
  1958. }
  1959. });
  1960. },
  1961. // 初始化视频列表
  1962. initializeVideoList() {
  1963. this.videoList = [];
  1964. this.additionalQuestions.forEach((question) => {
  1965. if (question.videoUrl) {
  1966. this.videoList.push(question.videoUrl);
  1967. }
  1968. });
  1969. if (this.videoList.length > 0) {
  1970. this.videoUrl = this.videoList[0];
  1971. this.currentVideoIndex = 0;
  1972. this.playCurrentVideo();
  1973. }
  1974. },
  1975. // 播放当前视频
  1976. playCurrentVideo() {
  1977. if (this.currentVideoIndex < this.videoList.length) {
  1978. this.videoUrl = this.videoList[this.currentVideoIndex];
  1979. this.videoPlaying = true;
  1980. const currentQuestion = this.additionalQuestions[this.currentVideoIndex];
  1981. if (currentQuestion) {
  1982. this.currentSubtitle = currentQuestion.question || currentQuestion.digital_human_video_subtitle || "请回答问题";
  1983. }
  1984. this.$nextTick(() => {
  1985. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  1986. if (videoContext) {
  1987. videoContext.play();
  1988. }
  1989. });
  1990. }
  1991. },
  1992. // 添加 handleVideoPlay 方法
  1993. handleVideoPlay() {
  1994. console.log("视频开始播放");
  1995. if (this.currentVideoIndex >= 0 && this.currentVideoIndex < this.additionalQuestions.length) {
  1996. const currentQuestion = this.additionalQuestions[this.currentVideoIndex];
  1997. if (currentQuestion) {
  1998. this.currentSubtitle = currentQuestion.question || currentQuestion.digital_human_video_subtitle || "请回答问题";
  1999. }
  2000. }
  2001. }
  2002. }
  2003. };
  2004. function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
  2005. return common_vendor.e({
  2006. a: $data.videoUrl,
  2007. b: common_vendor.o((...args) => $options.handleVideoError && $options.handleVideoError(...args)),
  2008. c: common_vendor.o((...args) => $options.handleVideoEnded && $options.handleVideoEnded(...args)),
  2009. d: common_vendor.o((...args) => $options.handleVideoPlay && $options.handleVideoPlay(...args)),
  2010. e: common_vendor.o((...args) => $options.handleTimeUpdate && $options.handleTimeUpdate(...args)),
  2011. f: $data.showAnswerButton
  2012. }, $data.showAnswerButton ? {
  2013. g: common_vendor.o((...args) => $options.handleAnswerButtonClick && $options.handleAnswerButtonClick(...args))
  2014. } : {}, {
  2015. h: $data.currentSubtitle
  2016. }, $data.currentSubtitle ? {
  2017. i: common_vendor.t($data.currentSubtitle)
  2018. } : {}, {
  2019. j: $data.useMiniProgramCameraComponent
  2020. }, $data.useMiniProgramCameraComponent ? {
  2021. k: common_vendor.o((...args) => $options.handleCameraError && $options.handleCameraError(...args))
  2022. } : {}, {
  2023. l: $data.loading
  2024. }, $data.loading ? {} : {}, {
  2025. m: $data.showDebugInfo
  2026. }, $data.showDebugInfo ? common_vendor.e({
  2027. n: $data.assistantResponse
  2028. }, $data.assistantResponse ? {
  2029. o: common_vendor.t($data.assistantResponse)
  2030. } : {}, {
  2031. p: $data.audioTranscript
  2032. }, $data.audioTranscript ? {
  2033. q: common_vendor.t($data.audioTranscript)
  2034. } : {}, {
  2035. r: common_vendor.f($data.processedResponses, (item, index, i0) => {
  2036. return common_vendor.e({
  2037. a: item.role
  2038. }, item.role ? {
  2039. b: common_vendor.t(item.role)
  2040. } : {}, {
  2041. c: item.transcript
  2042. }, item.transcript ? {
  2043. d: common_vendor.t(item.transcript)
  2044. } : {}, {
  2045. e: index
  2046. });
  2047. })
  2048. }) : {}, {
  2049. s: $data.showStopRecordingButton
  2050. }, $data.showStopRecordingButton ? {
  2051. t: common_vendor.o((...args) => $options.stopRecordingAnswer && $options.stopRecordingAnswer(...args))
  2052. } : {}, {
  2053. v: $data.isRecording
  2054. }, $data.isRecording ? {
  2055. w: common_vendor.t($data.recordingTimeDisplay || "00:00 / 05:00")
  2056. } : {}, {
  2057. x: $data.showStartRecordingButton
  2058. }, $data.showStartRecordingButton ? {
  2059. y: common_vendor.o((...args) => $options.handleStartRecordingClick && $options.handleStartRecordingClick(...args))
  2060. } : {}, {
  2061. z: $data.showRetryButton
  2062. }, $data.showRetryButton ? {
  2063. A: common_vendor.o((...args) => $options.retryVideoUpload && $options.retryVideoUpload(...args))
  2064. } : {}, {
  2065. B: $data.showCountdown
  2066. }, $data.showCountdown ? {
  2067. C: common_vendor.t($data.countdownValue)
  2068. } : {});
  2069. }
  2070. const MiniProgramPage = /* @__PURE__ */ common_vendor._export_sfc(_sfc_main, [["render", _sfc_render], ["__scopeId", "data-v-5095da88"]]);
  2071. wx.createPage(MiniProgramPage);