identity-verify.js 125 KB

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