interview-question.js 95 KB

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