identity-verify.js 118 KB

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