identity-verify.js 63 KB

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