identity-verify.js 124 KB

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