identity-verify.js 122 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315
  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. }
  1060. },
  1061. // 添加新方法:开始录制用户回答
  1062. startRecordingAnswer() {
  1063. console.log("开始录制用户回答");
  1064. this.isRecording = true;
  1065. this.recordingStartTime = Date.now();
  1066. this.recordingTimerCount = 0;
  1067. this.remainingTime = this.maxRecordingTime;
  1068. this.recordingTimer = setInterval(() => {
  1069. this.recordingTimerCount++;
  1070. this.remainingTime = Math.max(0, this.maxRecordingTime - this.recordingTimerCount);
  1071. this.recordingTimeDisplay = this.formatTime(this.recordingTimerCount);
  1072. this.progressPercent = this.recordingTimerCount / this.maxRecordingTime * 100;
  1073. if (this.recordingTimerCount >= this.maxRecordingTime) {
  1074. console.log("已达到最大录制时间(5分钟),自动停止录制");
  1075. this.stopRecordingAnswer();
  1076. }
  1077. }, 1e3);
  1078. const systemInfo = common_vendor.index.getSystemInfoSync();
  1079. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith("mp-");
  1080. if (isMiniProgram) {
  1081. this.startMiniProgramRecording();
  1082. } else {
  1083. this.startBrowserRecording();
  1084. }
  1085. this.showStopRecordingButton = true;
  1086. },
  1087. // 添加一个新方法:重置相机组件
  1088. resetCamera() {
  1089. console.log("重置相机组件");
  1090. this.useMiniProgramCameraComponent = false;
  1091. if (this.cameraContext) {
  1092. this.cameraContext = null;
  1093. }
  1094. setTimeout(() => {
  1095. this.useMiniProgramCameraComponent = true;
  1096. setTimeout(() => {
  1097. this.cameraContext = common_vendor.index.createCameraContext();
  1098. console.log("相机组件已重置");
  1099. }, 500);
  1100. }, 500);
  1101. },
  1102. // 修改 startMiniProgramRecording 方法
  1103. startMiniProgramRecording() {
  1104. console.log("开始小程序录制方法");
  1105. const systemInfo = common_vendor.index.getSystemInfoSync();
  1106. const isIOS = systemInfo.platform === "ios";
  1107. if (isIOS) {
  1108. this.resetCamera();
  1109. setTimeout(() => {
  1110. this.actualStartRecording(isIOS);
  1111. }, 1e3);
  1112. } else {
  1113. this.actualStartRecording(isIOS);
  1114. }
  1115. },
  1116. // 添加新方法:实际开始录制
  1117. actualStartRecording(isIOS) {
  1118. if (!this.cameraContext) {
  1119. this.cameraContext = common_vendor.index.createCameraContext();
  1120. console.log("创建新的相机上下文");
  1121. }
  1122. common_vendor.index.getSetting({
  1123. success: (res) => {
  1124. const hasRecordAuth = res.authSetting["scope.record"];
  1125. const hasCameraAuth = res.authSetting["scope.camera"];
  1126. if (!hasRecordAuth || !hasCameraAuth) {
  1127. console.warn("缺少必要权限,请求权限");
  1128. this.requestMiniProgramPermissions();
  1129. return;
  1130. }
  1131. if (isIOS) {
  1132. console.log("iOS: 检查相机状态");
  1133. const options = {
  1134. timeout: 3e5,
  1135. // 300秒超时 (5分钟)
  1136. quality: "low",
  1137. // 降低质量
  1138. compressed: true,
  1139. success: () => {
  1140. console.log("iOS录制开始成功");
  1141. },
  1142. fail: (err) => {
  1143. console.error("iOS录制失败:", err);
  1144. this.useAlternativeRecordingMethod();
  1145. }
  1146. };
  1147. try {
  1148. console.log("尝试开始录制");
  1149. this.recorder = this.cameraContext.startRecord(options);
  1150. } catch (e) {
  1151. console.error("开始录制异常:", e);
  1152. this.useAlternativeRecordingMethod();
  1153. }
  1154. } else {
  1155. const options = {
  1156. timeout: 3e5,
  1157. // 300秒超时 (5分钟)
  1158. quality: "medium",
  1159. compressed: true,
  1160. success: () => {
  1161. console.log("Android录制开始成功");
  1162. },
  1163. fail: (err) => {
  1164. console.error("Android录制失败:", err);
  1165. common_vendor.index.showToast({
  1166. title: "录制失败,请检查相机权限",
  1167. icon: "none"
  1168. });
  1169. this.proceedToNextQuestion();
  1170. }
  1171. };
  1172. this.recorder = this.cameraContext.startRecord(options);
  1173. }
  1174. }
  1175. });
  1176. },
  1177. // 添加新方法:使用替代录制方法
  1178. useAlternativeRecordingMethod() {
  1179. console.log("使用替代录制方法");
  1180. common_vendor.index.showActionSheet({
  1181. itemList: ["使用相册中的视频", "跳过此问题"],
  1182. success: (res) => {
  1183. if (res.tapIndex === 0) {
  1184. common_vendor.index.chooseVideo({
  1185. sourceType: ["album"],
  1186. maxDuration: 300,
  1187. // 从60秒改为300秒
  1188. camera: "front",
  1189. success: (res2) => {
  1190. console.log("选择视频成功:", res2.tempFilePath);
  1191. this.isRecording = false;
  1192. this.showStopRecordingButton = false;
  1193. this.uploadRecordedVideo(res2.tempFilePath);
  1194. },
  1195. fail: () => {
  1196. console.log("用户取消选择视频");
  1197. this.proceedToNextQuestion();
  1198. }
  1199. });
  1200. } else {
  1201. console.log("用户选择跳过问题");
  1202. this.proceedToNextQuestion();
  1203. }
  1204. },
  1205. fail: () => {
  1206. console.log("操作取消");
  1207. this.proceedToNextQuestion();
  1208. }
  1209. });
  1210. },
  1211. // 添加新方法:请求小程序权限
  1212. requestMiniProgramPermissions() {
  1213. common_vendor.index.authorize({
  1214. scope: "scope.record",
  1215. success: () => {
  1216. console.log("录音权限已获取");
  1217. common_vendor.index.authorize({
  1218. scope: "scope.camera",
  1219. success: () => {
  1220. console.log("相机权限已获取");
  1221. this.startMiniProgramRecording();
  1222. },
  1223. fail: (err) => {
  1224. console.error("相机权限获取失败:", err);
  1225. this.showPermissionDialog("相机");
  1226. }
  1227. });
  1228. },
  1229. fail: (err) => {
  1230. console.error("录音权限获取失败:", err);
  1231. this.showPermissionDialog("录音");
  1232. }
  1233. });
  1234. },
  1235. // 修改浏览器环境下的录制方法
  1236. startBrowserRecording() {
  1237. if (!this.cameraStream) {
  1238. console.error("没有可用的摄像头流");
  1239. this.proceedToNextQuestion();
  1240. return;
  1241. }
  1242. try {
  1243. const hasAudio = this.cameraStream.getAudioTracks().length > 0;
  1244. if (!hasAudio) {
  1245. console.warn("警告:媒体流中没有音频轨道,尝试重新获取带音频的媒体流");
  1246. navigator.mediaDevices.getUserMedia({
  1247. audio: {
  1248. echoCancellation: true,
  1249. noiseSuppression: true,
  1250. autoGainControl: true
  1251. },
  1252. video: true
  1253. }).then((newStream) => {
  1254. const audioTracks = newStream.getAudioTracks();
  1255. if (audioTracks.length > 0) {
  1256. console.log("成功获取音频轨道:", audioTracks[0].label);
  1257. const videoTrack = this.cameraStream.getVideoTracks()[0];
  1258. const audioTrack = newStream.getAudioTracks()[0];
  1259. const combinedStream = new MediaStream();
  1260. if (videoTrack)
  1261. combinedStream.addTrack(videoTrack);
  1262. if (audioTrack)
  1263. combinedStream.addTrack(audioTrack);
  1264. this.cameraStream = combinedStream;
  1265. const videoElement = this.$refs.userCameraVideo;
  1266. if (videoElement) {
  1267. videoElement.srcObject = combinedStream;
  1268. videoElement.muted = true;
  1269. }
  1270. this.setupMediaRecorder(combinedStream);
  1271. } else {
  1272. console.warn("仍然无法获取音频轨道");
  1273. this.setupMediaRecorder(this.cameraStream);
  1274. }
  1275. }).catch((err) => {
  1276. console.error("获取音频失败:", err);
  1277. this.setupMediaRecorder(this.cameraStream);
  1278. });
  1279. } else {
  1280. console.log("检测到音频轨道,直接使用");
  1281. this.setupMediaRecorder(this.cameraStream);
  1282. }
  1283. } catch (error) {
  1284. console.error("浏览器录制失败:", error);
  1285. common_vendor.index.showToast({
  1286. title: "录制失败,浏览器可能不支持此功能",
  1287. icon: "none"
  1288. });
  1289. this.proceedToNextQuestion();
  1290. }
  1291. },
  1292. // 修改 setupMediaRecorder 方法
  1293. setupMediaRecorder(stream) {
  1294. const videoTracks = stream.getVideoTracks();
  1295. const audioTracks = stream.getAudioTracks();
  1296. console.log("设置MediaRecorder - 视频轨道:", videoTracks.length, "音频轨道:", audioTracks.length);
  1297. let mimeType = "";
  1298. const supportedTypes = [
  1299. "video/webm;codecs=vp9,opus",
  1300. "video/webm;codecs=vp8,opus",
  1301. "video/webm;codecs=h264,opus",
  1302. "video/mp4;codecs=h264,aac",
  1303. "video/webm",
  1304. "video/mp4"
  1305. ];
  1306. for (const type of supportedTypes) {
  1307. if (MediaRecorder.isTypeSupported(type)) {
  1308. mimeType = type;
  1309. console.log("使用支持的MIME类型:", mimeType);
  1310. break;
  1311. }
  1312. }
  1313. const options = {
  1314. mimeType: mimeType || "",
  1315. audioBitsPerSecond: 64e3,
  1316. // 降低音频比特率
  1317. videoBitsPerSecond: 1e6
  1318. // 降低视频比特率到1Mbps
  1319. };
  1320. try {
  1321. this.mediaRecorder = new MediaRecorder(stream, options);
  1322. console.log("MediaRecorder创建成功,使用选项:", options);
  1323. } catch (e) {
  1324. console.warn("使用指定选项创建MediaRecorder失败,尝试使用默认选项");
  1325. this.mediaRecorder = new MediaRecorder(stream);
  1326. }
  1327. this.recordedChunks = [];
  1328. this.mediaRecorder.ondataavailable = (event) => {
  1329. if (event.data && event.data.size > 0) {
  1330. this.recordedChunks.push(event.data);
  1331. console.log(`收到数据块: ${event.data.size} 字节`);
  1332. }
  1333. };
  1334. this.mediaRecorder.onstop = async () => {
  1335. console.log("MediaRecorder停止,数据块数量:", this.recordedChunks.length);
  1336. if (this.recordedChunks.length === 0) {
  1337. console.error("没有录制到数据");
  1338. this.proceedToNextQuestion();
  1339. return;
  1340. }
  1341. const mimeType2 = this.mediaRecorder.mimeType || "video/webm";
  1342. const blob = new Blob(this.recordedChunks, { type: mimeType2 });
  1343. console.log("创建Blob,原始大小:", blob.size, "类型:", mimeType2);
  1344. common_vendor.index.showLoading({
  1345. title: "正在处理视频...",
  1346. mask: true
  1347. });
  1348. try {
  1349. const compressedBlob = await this.compressVideo(blob);
  1350. const fileName = `answer_${this.currentVideoIndex}_${Date.now()}.webm`;
  1351. const file = new File([compressedBlob], fileName, { type: mimeType2 });
  1352. common_vendor.index.hideLoading();
  1353. this.uploadRecordedVideo(file);
  1354. } catch (error) {
  1355. console.error("视频处理失败:", error);
  1356. common_vendor.index.hideLoading();
  1357. const fileName = `answer_${this.currentVideoIndex}_${Date.now()}.webm`;
  1358. const file = new File([blob], fileName, { type: mimeType2 });
  1359. this.uploadRecordedVideo(file);
  1360. }
  1361. };
  1362. this.mediaRecorder.onerror = (event) => {
  1363. console.error("MediaRecorder错误:", event.error);
  1364. };
  1365. try {
  1366. this.mediaRecorder.start(1e3);
  1367. console.log("MediaRecorder开始录制");
  1368. this.mediaRecorderTimeout = setTimeout(() => {
  1369. if (this.mediaRecorder && this.mediaRecorder.state === "recording") {
  1370. console.log("MediaRecorder备份超时机制触发,停止录制");
  1371. this.mediaRecorder.stop();
  1372. }
  1373. }, 3e5);
  1374. } catch (e) {
  1375. console.error("开始录制失败:", e);
  1376. }
  1377. },
  1378. // 添加新方法:获取录制时长
  1379. getRecordingDuration() {
  1380. if (this.recordingStartTime) {
  1381. return (Date.now() - this.recordingStartTime) / 1e3;
  1382. }
  1383. if (this.mediaRecorder && this.$refs.userCameraVideo) {
  1384. return this.$refs.userCameraVideo.currentTime || 0;
  1385. }
  1386. if (this.recordingTimerCount) {
  1387. return this.recordingTimerCount;
  1388. }
  1389. return 0;
  1390. },
  1391. // 添加新方法:重置录制
  1392. resetRecording() {
  1393. if (this.recordingTimer) {
  1394. clearTimeout(this.recordingTimer);
  1395. }
  1396. this.recordingStartTime = Date.now();
  1397. this.recordingTimerCount = 0;
  1398. if (this.mediaRecorder && this.mediaRecorder.state !== "inactive") {
  1399. this.mediaRecorder.stop();
  1400. this.recordedChunks = [];
  1401. setTimeout(() => {
  1402. this.startBrowserRecording();
  1403. }, 500);
  1404. } else if (this.cameraContext) {
  1405. this.cameraContext.stopRecord({
  1406. success: () => {
  1407. console.log("相机录制已停止");
  1408. },
  1409. fail: (err) => {
  1410. console.error("停止相机录制失败:", err);
  1411. }
  1412. });
  1413. }
  1414. },
  1415. // 修改 completeRecordingStop 方法,确保正确处理追问问题ID
  1416. completeRecordingStop(uploadVideo = true) {
  1417. console.log("完成录制停止");
  1418. if (this.recordingTimer) {
  1419. clearInterval(this.recordingTimer);
  1420. this.recordingTimer = null;
  1421. }
  1422. this.finalRecordingDuration = this.recordingTimerCount;
  1423. this.showStopRecordingButton = false;
  1424. this.isRecording = false;
  1425. const systemInfo = common_vendor.index.getSystemInfoSync();
  1426. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith("mp-");
  1427. if (isMiniProgram) {
  1428. if (uploadVideo) {
  1429. this.stopMiniProgramRecording();
  1430. } else {
  1431. if (this.cameraContext) {
  1432. this.cameraContext.stopRecord({
  1433. success: () => {
  1434. console.log("相机录制已停止,不上传视频");
  1435. },
  1436. fail: (err) => {
  1437. console.error("停止相机录制失败:", err);
  1438. }
  1439. });
  1440. }
  1441. }
  1442. } else {
  1443. if (uploadVideo) {
  1444. this.stopBrowserRecording();
  1445. } else {
  1446. if (this.mediaRecorder && this.mediaRecorder.state !== "inactive") {
  1447. this.mediaRecorder.stop();
  1448. this.recordedChunks = [];
  1449. }
  1450. }
  1451. }
  1452. if (this.isFollowUpQuestion && this.currentFollowUpQuestion) {
  1453. console.log("当前是追问问题,记录追问问题ID:", this.currentFollowUpQuestion.id);
  1454. this.lastQuestionWasFollowUp = true;
  1455. this.lastFollowUpQuestionId = this.currentFollowUpQuestion.id;
  1456. } else {
  1457. this.lastQuestionWasFollowUp = false;
  1458. this.lastFollowUpQuestionId = null;
  1459. }
  1460. },
  1461. // 修改 stopMiniProgramRecording 方法,确保正确传递追问问题ID
  1462. stopMiniProgramRecording() {
  1463. console.log("停止小程序录制");
  1464. if (!this.cameraContext) {
  1465. console.error("相机上下文不存在");
  1466. this.proceedToNextQuestion();
  1467. return;
  1468. }
  1469. this.cameraContext.stopRecord({
  1470. success: async (res) => {
  1471. console.log("小程序录制停止成功:", res);
  1472. const videoPath = res.tempVideoPath;
  1473. if (videoPath) {
  1474. await this.uploadRecordedVideo(videoPath);
  1475. } else {
  1476. console.error("未获取到录制视频路径");
  1477. this.proceedToNextQuestion();
  1478. }
  1479. },
  1480. fail: (err) => {
  1481. console.error("小程序录制停止失败:", err);
  1482. this.proceedToNextQuestion();
  1483. }
  1484. });
  1485. },
  1486. // 添加新方法:停止浏览器录制
  1487. stopBrowserRecording() {
  1488. if (this.mediaRecorder && this.mediaRecorder.state !== "inactive") {
  1489. this.mediaRecorder.stop();
  1490. console.log("浏览器录制停止成功");
  1491. } else {
  1492. console.error("MediaRecorder不存在或已经停止");
  1493. this.proceedToNextQuestion();
  1494. }
  1495. },
  1496. // 修改 uploadRecordedVideo 方法,添加记录父问题ID的逻辑
  1497. uploadRecordedVideo(fileOrPath) {
  1498. console.log("准备上传视频:", typeof fileOrPath === "string" ? fileOrPath : fileOrPath.name);
  1499. console.log("当前问题ID:", this.currentParentQuestionId);
  1500. console.log("当前问题类型:", this.isFollowUpQuestion);
  1501. console.log("当前追问问题:", this.currentFollowUpQuestion);
  1502. let questionId;
  1503. let isFollowUpQuestionUpload = false;
  1504. let questionText = "";
  1505. let questionForm = 0;
  1506. if (this.currentFollowUpQuestion && (this.currentFollowUpQuestion.question_form === 5 || this.isFollowUpQuestion)) {
  1507. questionId = this.currentFollowUpQuestion.id;
  1508. isFollowUpQuestionUpload = true;
  1509. questionText = this.currentFollowUpQuestion.question || "";
  1510. questionForm = 5;
  1511. console.log("正在上传追问问题的回答:", {
  1512. questionId,
  1513. questionText,
  1514. questionForm,
  1515. isFollowUp: true
  1516. });
  1517. } else {
  1518. this.showThinkingLoading();
  1519. const currentQuestion = this.getCurrentQuestionByIndex(this.currentVideoIndex);
  1520. if (currentQuestion && currentQuestion.id) {
  1521. questionId = currentQuestion.id;
  1522. questionText = currentQuestion.question || "";
  1523. console.log("正在上传常规问题的回答:", {
  1524. questionId,
  1525. questionText,
  1526. questionForm: 0
  1527. });
  1528. } else {
  1529. questionId = this.getDefaultQuestionId(this.currentVideoIndex);
  1530. console.log("使用默认问题ID:", questionId);
  1531. }
  1532. }
  1533. const uploadTask = {
  1534. id: Date.now().toString(),
  1535. file: fileOrPath,
  1536. questionId,
  1537. isFollowUp: isFollowUpQuestionUpload,
  1538. questionText,
  1539. questionForm,
  1540. attempts: 0,
  1541. maxAttempts: 3,
  1542. parentQuestionId: this.currentParentQuestionId,
  1543. videoDuration: this.currentRecordingDuration || 0
  1544. // 添加视频时长
  1545. };
  1546. if (!isFollowUpQuestionUpload) {
  1547. this.currentParentQuestionId = questionId;
  1548. }
  1549. this.uploadQueue.push(uploadTask);
  1550. this.uploadProgress[uploadTask.id] = 0;
  1551. this.uploadStatus[uploadTask.id] = "pending";
  1552. this.updateUploadStatusText();
  1553. return new Promise((resolve) => {
  1554. const checkUploadStatus = () => {
  1555. if (!this.isUploading && this.uploadQueue.length === 0) {
  1556. this.handlePostUploadActions(uploadTask);
  1557. resolve();
  1558. } else {
  1559. setTimeout(checkUploadStatus, 500);
  1560. }
  1561. };
  1562. if (!this.isUploading) {
  1563. this.processUploadQueue();
  1564. }
  1565. checkUploadStatus();
  1566. });
  1567. },
  1568. // 添加新方法:处理上传后的逻辑
  1569. handlePostUploadActions(task) {
  1570. this.hideThinkingLoading();
  1571. if (this.needPlayLowScoreVideo && this.retryCount < 1) {
  1572. this.playLowScoreVideo();
  1573. this.needPlayLowScoreVideo = false;
  1574. } else {
  1575. if (task.isFollowUp) {
  1576. console.log("追问问题回答完成,进入下一个问题");
  1577. this.retryCount = 0;
  1578. this.isFollowUpQuestion = false;
  1579. this.currentFollowUpQuestion = null;
  1580. this.proceedToNextQuestion();
  1581. } else {
  1582. this.currentParentQuestionId = task.questionId;
  1583. console.log("检查常规问题的追问,父问题ID:", this.currentParentQuestionId);
  1584. this.checkAndPlayFollowUpQuestion(this.currentParentQuestionId);
  1585. }
  1586. }
  1587. },
  1588. // 修改 processUploadQueue 方法
  1589. processUploadQueue() {
  1590. if (this.uploadQueue.length === 0) {
  1591. this.isUploading = false;
  1592. this.showUploadStatus = false;
  1593. this.hideThinkingLoading();
  1594. return;
  1595. }
  1596. this.isUploading = true;
  1597. this.showUploadStatus = true;
  1598. const task = this.uploadQueue[0];
  1599. this.uploadStatus[task.id] = "uploading";
  1600. this.updateUploadStatusText();
  1601. task.attempts++;
  1602. if (typeof task.file === "string") {
  1603. this.uploadFileWithUni(task);
  1604. } else {
  1605. this.uploadFileWithXHR(task);
  1606. }
  1607. },
  1608. // 添加新方法:使用XMLHttpRequest上传文件
  1609. uploadFileWithXHR(task) {
  1610. const userInfo = common_vendor.index.getStorageSync("userInfo");
  1611. const openid = userInfo ? JSON.parse(userInfo).openid || "" : "";
  1612. const tenant_id = JSON.parse(common_vendor.index.getStorageSync("userInfo")).tenant_id || "1";
  1613. const formData = new FormData();
  1614. formData.append("file", task.file);
  1615. formData.append("openid", openid);
  1616. formData.append("tenant_id", tenant_id);
  1617. formData.append("application_id", common_vendor.index.getStorageSync("appId"));
  1618. formData.append("question_id", task.questionId);
  1619. formData.append("video_duration", task.videoDuration);
  1620. formData.append("has_audio", "true");
  1621. const xhr = new XMLHttpRequest();
  1622. xhr.open("POST", `${common_config.apiBaseUrl}/api/upload/`, true);
  1623. xhr.timeout = 12e4;
  1624. xhr.upload.onprogress = (event) => {
  1625. if (event.lengthComputable) {
  1626. const percentComplete = Math.round(event.loaded / event.total * 100);
  1627. this.uploadProgress[task.id] = percentComplete;
  1628. this.updateUploadStatusText();
  1629. }
  1630. };
  1631. xhr.onload = () => {
  1632. if (xhr.status === 200) {
  1633. try {
  1634. const res = JSON.parse(xhr.responseText);
  1635. console.log("上传响应:", res);
  1636. if (res.code === 2e3) {
  1637. const videoUrl = res.data.url || res.data.photoUrl || "";
  1638. if (videoUrl) {
  1639. this.uploadStatus[task.id] = "success";
  1640. this.updateUploadStatusText();
  1641. this.submitVideoToInterview(videoUrl, task);
  1642. } else {
  1643. this.handleUploadFailure(task, "视频URL获取失败");
  1644. }
  1645. } else {
  1646. this.handleUploadFailure(task, res.msg || "上传失败");
  1647. }
  1648. } catch (e) {
  1649. this.handleUploadFailure(task, "解析响应失败");
  1650. }
  1651. } else {
  1652. this.handleUploadFailure(task, "HTTP状态: " + xhr.status);
  1653. }
  1654. };
  1655. xhr.onerror = () => {
  1656. this.handleUploadFailure(task, "网络错误");
  1657. };
  1658. xhr.ontimeout = () => {
  1659. this.handleUploadFailure(task, "上传超时");
  1660. };
  1661. xhr.send(formData);
  1662. },
  1663. // 添加新方法:使用uni.uploadFile上传文件
  1664. uploadFileWithUni(task) {
  1665. const userInfo = common_vendor.index.getStorageSync("userInfo");
  1666. const openid = userInfo ? JSON.parse(userInfo).openid || "" : "";
  1667. const tenant_id = JSON.parse(common_vendor.index.getStorageSync("userInfo")).tenant_id || "1";
  1668. const uploadTask = common_vendor.index.uploadFile({
  1669. url: `${common_config.apiBaseUrl}/api/upload/`,
  1670. filePath: task.file,
  1671. name: "file",
  1672. formData: {
  1673. openid,
  1674. tenant_id,
  1675. application_id: common_vendor.index.getStorageSync("appId"),
  1676. question_id: task.questionId,
  1677. video_duration: 0,
  1678. has_audio: "true"
  1679. },
  1680. success: (uploadRes) => {
  1681. try {
  1682. const res = JSON.parse(uploadRes.data);
  1683. console.log("上传响应:", res);
  1684. if (res.code === 2e3) {
  1685. const videoUrl = res.data.permanent_link || res.data.url || "";
  1686. if (videoUrl) {
  1687. this.uploadStatus[task.id] = "success";
  1688. this.updateUploadStatusText();
  1689. this.submitVideoToInterview(videoUrl, task);
  1690. } else {
  1691. this.handleUploadFailure(task, "视频URL获取失败");
  1692. }
  1693. } else {
  1694. this.handleUploadFailure(task, res.msg || "上传失败");
  1695. }
  1696. } catch (e) {
  1697. this.handleUploadFailure(task, "解析响应失败");
  1698. }
  1699. },
  1700. fail: (err) => {
  1701. this.handleUploadFailure(task, err.errMsg || "上传失败");
  1702. }
  1703. });
  1704. uploadTask.onProgressUpdate((res) => {
  1705. this.uploadProgress[task.id] = res.progress;
  1706. this.updateUploadStatusText();
  1707. });
  1708. },
  1709. // 添加新方法:处理上传失败
  1710. handleUploadFailure(task, errorMsg) {
  1711. console.error("上传失败:", errorMsg);
  1712. this.uploadStatus[task.id] = "failed";
  1713. this.updateUploadStatusText();
  1714. if (task.attempts < task.maxAttempts) {
  1715. console.log(`将在5秒后重试上传,当前尝试次数: ${task.attempts}/${task.maxAttempts}`);
  1716. setTimeout(() => {
  1717. this.uploadProgress[task.id] = 0;
  1718. if (typeof task.file !== "string") {
  1719. this.uploadFileWithXHR(task);
  1720. } else {
  1721. this.uploadFileWithUni(task);
  1722. }
  1723. }, 5e3);
  1724. } else {
  1725. console.log("超过最大重试次数,放弃上传");
  1726. this.uploadQueue.shift();
  1727. this.processUploadQueue();
  1728. }
  1729. },
  1730. // 修改 submitVideoToInterview 方法
  1731. submitVideoToInterview(videoUrl, task) {
  1732. const requestData = {
  1733. application_id: common_vendor.index.getStorageSync("appId"),
  1734. question_id: task.questionId,
  1735. video_url: videoUrl,
  1736. tenant_id: JSON.parse(common_vendor.index.getStorageSync("userInfo")).tenant_id || "1",
  1737. is_follow_up: task.isFollowUp ? 1 : 0,
  1738. question_form: task.questionForm,
  1739. question_text: task.questionText
  1740. };
  1741. console.log("提交视频到面试接口", requestData);
  1742. if (task.isFollowUp) {
  1743. const followUpRequestData = {
  1744. application_id: common_vendor.index.getStorageSync("appId"),
  1745. tenant_id: JSON.parse(common_vendor.index.getStorageSync("userInfo")).tenant_id || "1",
  1746. video_url: videoUrl,
  1747. original_question_id: this.parentJobPositionQuestionId,
  1748. // 使用保存的job_position_question_id
  1749. follow_up_question: task.questionText,
  1750. video_duration: task.videoDuration,
  1751. openid: JSON.parse(common_vendor.index.getStorageSync("userInfo")).openid || ""
  1752. };
  1753. console.log("准备提交追问视频:", followUpRequestData);
  1754. common_vendor.index.request({
  1755. url: `${common_config.apiBaseUrl}/voice_interview/upload_follow_up_video/`,
  1756. method: "POST",
  1757. data: followUpRequestData,
  1758. header: {
  1759. "content-type": "application/x-www-form-urlencoded"
  1760. },
  1761. success: async (res) => {
  1762. try {
  1763. if (res.data.code === 200 || res.data.code === 2e3) {
  1764. if (res.data.data && res.data.data.transcription_status === "pending") {
  1765. console.log("视频转写进行中,5秒后重试");
  1766. setTimeout(() => {
  1767. this.checkTranscriptionStatus(task, followUpRequestData);
  1768. }, 5e3);
  1769. return;
  1770. }
  1771. console.log("追问视频提交成功");
  1772. this.isFollowUpMode = false;
  1773. this.currentVideoIndex = this.mainQuestionIndex;
  1774. this.uploadQueue.shift();
  1775. this.processUploadQueue();
  1776. this.$nextTick(() => {
  1777. if (this.currentVideoIndex < this.videoList.length) {
  1778. this.videoUrl = this.videoList[this.currentVideoIndex];
  1779. this.videoPlaying = true;
  1780. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  1781. if (videoContext) {
  1782. videoContext.play();
  1783. }
  1784. }
  1785. });
  1786. } else {
  1787. this.handleSubmitFailure(task, "提交失败: " + (res.data.msg || "未知错误"));
  1788. }
  1789. } catch (e) {
  1790. this.handleSubmitFailure(task, "解析响应失败: " + e.message);
  1791. }
  1792. },
  1793. fail: (err) => {
  1794. console.error("提交视频失败:", err);
  1795. this.handleSubmitFailure(task, "提交失败: " + err.errMsg);
  1796. }
  1797. });
  1798. } else {
  1799. common_vendor.index.request({
  1800. url: `${common_config.apiBaseUrl}/api/job/upload_video`,
  1801. method: "POST",
  1802. data: requestData,
  1803. header: {
  1804. "content-type": "application/x-www-form-urlencoded"
  1805. },
  1806. success: async (res) => {
  1807. if (res.data.code === 200 || res.data.code === 2e3) {
  1808. console.log("视频提交成功,准备调用面试互动接口");
  1809. try {
  1810. this.parentJobPositionQuestionId = res.data.data.job_position_question_id;
  1811. console.log("保存父问题ID:", this.parentJobPositionQuestionId);
  1812. await this.callInterviewInteraction(res.data.data.job_position_question_id);
  1813. console.log("面试互动接口调用成功");
  1814. } catch (error) {
  1815. console.error("面试互动接口调用失败:", error);
  1816. this.proceedToNextQuestion();
  1817. }
  1818. this.uploadQueue.shift();
  1819. this.processUploadQueue();
  1820. } else {
  1821. this.handleSubmitFailure(task, "提交失败: " + (res.data.msg || "未知错误"));
  1822. }
  1823. },
  1824. fail: (err) => {
  1825. console.error("提交视频失败:", err);
  1826. this.handleSubmitFailure(task, "提交失败: " + err.errMsg);
  1827. }
  1828. });
  1829. }
  1830. },
  1831. // 添加新方法:处理提交失败
  1832. handleSubmitFailure(task, errorMsg) {
  1833. console.error("提交失败:", errorMsg);
  1834. this.uploadStatus[task.id] = "failed";
  1835. this.updateUploadStatusText();
  1836. if (task.attempts < task.maxAttempts) {
  1837. console.log(`将在5秒后重试提交,当前尝试次数: ${task.attempts}/${task.maxAttempts}`);
  1838. setTimeout(() => {
  1839. this.submitVideoToInterview(task.videoUrl, task);
  1840. }, 5e3);
  1841. } else {
  1842. console.log("超过最大重试次数,放弃提交");
  1843. this.uploadQueue.shift();
  1844. this.processUploadQueue();
  1845. }
  1846. },
  1847. // 添加检查转写状态的方法
  1848. checkTranscriptionStatus(task, requestData, retryCount = 0) {
  1849. const maxRetries = 24;
  1850. const retryInterval = 5e3;
  1851. if (retryCount >= maxRetries) {
  1852. console.log("转写超时,继续下一个问题");
  1853. this.isFollowUpMode = false;
  1854. this.currentVideoIndex = this.mainQuestionIndex;
  1855. this.uploadQueue.shift();
  1856. this.processUploadQueue();
  1857. return;
  1858. }
  1859. common_vendor.index.request({
  1860. url: `${common_config.apiBaseUrl}/voice_interview/check_transcription_status/`,
  1861. method: "POST",
  1862. data: {
  1863. application_id: requestData.application_id,
  1864. original_question_id: requestData.original_question_id,
  1865. video_url: requestData.video_url
  1866. },
  1867. header: {
  1868. "content-type": "application/x-www-form-urlencoded"
  1869. },
  1870. success: (res) => {
  1871. if (res.data.code === 200 || res.data.code === 2e3) {
  1872. if (res.data.data && res.data.data.status === "completed") {
  1873. console.log("视频转写完成");
  1874. this.isFollowUpMode = false;
  1875. this.currentVideoIndex = this.mainQuestionIndex;
  1876. this.uploadQueue.shift();
  1877. this.processUploadQueue();
  1878. this.$nextTick(() => {
  1879. if (this.currentVideoIndex < this.videoList.length) {
  1880. this.videoUrl = this.videoList[this.currentVideoIndex];
  1881. this.videoPlaying = true;
  1882. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  1883. if (videoContext) {
  1884. videoContext.play();
  1885. }
  1886. }
  1887. });
  1888. } else {
  1889. console.log(`转写进行中,${retryInterval / 1e3}秒后重试 (${retryCount + 1}/${maxRetries})`);
  1890. setTimeout(() => {
  1891. this.checkTranscriptionStatus(task, requestData, retryCount + 1);
  1892. }, retryInterval);
  1893. }
  1894. } else if (res.data.message === "面试视频尚未完成转写" || res.data.success === false) {
  1895. console.log(`转写未完成,${retryInterval / 1e3}秒后重试 (${retryCount + 1}/${maxRetries})`);
  1896. setTimeout(() => {
  1897. this.checkTranscriptionStatus(task, requestData, retryCount + 1);
  1898. }, retryInterval);
  1899. } else {
  1900. this.handleSubmitFailure(task, "检查转写状态失败: " + (res.data.msg || "未知错误"));
  1901. }
  1902. },
  1903. fail: (err) => {
  1904. console.error("检查转写状态失败:", err);
  1905. console.log(`网络请求失败,${retryInterval / 1e3}秒后重试 (${retryCount + 1}/${maxRetries})`);
  1906. setTimeout(() => {
  1907. this.checkTranscriptionStatus(task, requestData, retryCount + 1);
  1908. }, retryInterval);
  1909. }
  1910. });
  1911. },
  1912. // 添加新方法:更新上传状态文本
  1913. updateUploadStatusText() {
  1914. if (this.uploadQueue.length === 0) {
  1915. this.uploadStatusText = "";
  1916. return;
  1917. }
  1918. const currentTask = this.uploadQueue[0];
  1919. const progress = this.uploadProgress[currentTask.id] || 0;
  1920. const status = this.uploadStatus[currentTask.id] || "pending";
  1921. let statusText = "";
  1922. switch (status) {
  1923. case "pending":
  1924. statusText = "等待上传";
  1925. break;
  1926. case "uploading":
  1927. statusText = `上传中 ${progress}%`;
  1928. break;
  1929. case "success":
  1930. statusText = "上传成功,提交中...";
  1931. break;
  1932. case "failed":
  1933. statusText = `上传失败,${currentTask.attempts < currentTask.maxAttempts ? "即将重试" : "已放弃"}`;
  1934. break;
  1935. }
  1936. const questionTypeText = currentTask.isFollowUp ? "追问" : "问题";
  1937. const questionShortText = currentTask.questionText ? currentTask.questionText.length > 10 ? currentTask.questionText.substring(0, 10) + "..." : currentTask.questionText : `${questionTypeText}${currentTask.questionId}`;
  1938. this.uploadStatusText = `${questionTypeText}「${questionShortText}」:${statusText}`;
  1939. if (this.uploadQueue.length > 1) {
  1940. this.uploadStatusText += ` (${this.uploadQueue.length}个视频待处理)`;
  1941. }
  1942. },
  1943. // 修改 proceedToNextQuestion 方法,确保在切换视频时重置历史时间
  1944. proceedToNextQuestion() {
  1945. if (this.isVideoSwitching) {
  1946. console.log("正在切换视频中,请等待...");
  1947. return;
  1948. }
  1949. console.log("继续下一个问题");
  1950. this.isVideoSwitching = true;
  1951. const currentVideo = common_vendor.index.createVideoContext("myVideo", this);
  1952. if (currentVideo) {
  1953. currentVideo.stop();
  1954. this.videoPlaying = false;
  1955. }
  1956. this.currentVideoIndex++;
  1957. this.historyTime = 0;
  1958. if (this.currentVideoIndex < this.videoList.length) {
  1959. this.videoUrl = this.videoList[this.currentVideoIndex];
  1960. setTimeout(() => {
  1961. this.videoPlaying = true;
  1962. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  1963. if (videoContext) {
  1964. videoContext.play();
  1965. }
  1966. this.isVideoSwitching = false;
  1967. }, 100);
  1968. } else {
  1969. console.log("所有视频已播放完毕");
  1970. this.stopUserCamera();
  1971. this.clearCountdown();
  1972. const currentJobDetail = JSON.parse(common_vendor.index.getStorageSync("selectedJob"));
  1973. console.log("当前职位ID:", currentJobDetail);
  1974. const jobId = currentJobDetail ? currentJobDetail.id : null;
  1975. console.log("当前职位ID:", jobId);
  1976. setTimeout(() => {
  1977. this.isVideoSwitching = false;
  1978. if (jobId === 9) {
  1979. common_vendor.index.navigateTo({
  1980. url: "/pages/interview-question/interview-question",
  1981. success: () => {
  1982. console.log("成功跳转到interview-question页面");
  1983. },
  1984. fail: (err) => {
  1985. console.error("跳转到interview-question页面失败:", err);
  1986. common_vendor.index.redirectTo({
  1987. url: "/pages/interview-question/interview-question",
  1988. fail: (redirectErr) => {
  1989. console.error("重定向到interview-question页面也失败:", redirectErr);
  1990. common_vendor.index.navigateBack({
  1991. delta: 1
  1992. });
  1993. }
  1994. });
  1995. }
  1996. });
  1997. } else {
  1998. common_vendor.index.navigateTo({
  1999. url: "/pages/camera/camera",
  2000. success: () => {
  2001. console.log("成功跳转到camera页面");
  2002. },
  2003. fail: (err) => {
  2004. console.error("跳转到camera页面失败:", err);
  2005. common_vendor.index.redirectTo({
  2006. url: "/pages/camera/camera",
  2007. fail: (redirectErr) => {
  2008. console.error("重定向到camera页面也失败:", redirectErr);
  2009. common_vendor.index.switchTab({
  2010. url: "/pages/camera/camera",
  2011. fail: (switchErr) => {
  2012. console.error("所有跳转方式都失败:", switchErr);
  2013. common_vendor.index.navigateBack({
  2014. delta: 1
  2015. });
  2016. }
  2017. });
  2018. }
  2019. });
  2020. }
  2021. });
  2022. }
  2023. }, 200);
  2024. }
  2025. },
  2026. // 修改 handleAnswerButtonClick 方法,确保在切换视频时重置历史时间
  2027. handleAnswerButtonClick() {
  2028. console.log("点击开始回答按钮");
  2029. this.showAnswerButton = false;
  2030. this.currentVideoIndex++;
  2031. this.historyTime = 0;
  2032. if (this.currentVideoIndex < this.videoList.length) {
  2033. this.videoUrl = this.videoList[this.currentVideoIndex];
  2034. this.videoPlaying = true;
  2035. this.$nextTick(() => {
  2036. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  2037. if (videoContext) {
  2038. videoContext.play();
  2039. }
  2040. });
  2041. }
  2042. },
  2043. // 处理相机错误
  2044. handleCameraError(e) {
  2045. console.error("相机错误:", e);
  2046. const systemInfo = common_vendor.index.getSystemInfoSync();
  2047. const isIOS = systemInfo.platform === "ios";
  2048. if (isIOS) {
  2049. console.log("iOS相机错误,尝试重新初始化");
  2050. common_vendor.index.showToast({
  2051. title: "相机初始化中...",
  2052. icon: "loading",
  2053. duration: 2e3
  2054. });
  2055. this.resetCamera();
  2056. if (this.isRecording) {
  2057. this.isRecording = false;
  2058. this.showStopRecordingButton = false;
  2059. setTimeout(() => {
  2060. this.useAlternativeRecordingMethod();
  2061. }, 1e3);
  2062. }
  2063. } else {
  2064. common_vendor.index.showToast({
  2065. title: "相机初始化失败,请检查权限设置",
  2066. icon: "none"
  2067. });
  2068. this.tryFallbackOptions();
  2069. }
  2070. },
  2071. // 添加新方法:尝试备用选项
  2072. tryFallbackOptions() {
  2073. const systemInfo = common_vendor.index.getSystemInfoSync();
  2074. if (systemInfo.uniPlatform === "mp-weixin" || systemInfo.uniPlatform === "mp-alipay") {
  2075. this.useMiniProgramCamera();
  2076. } else {
  2077. this.showStaticCameraPlaceholder();
  2078. }
  2079. },
  2080. // 添加新方法:使用小程序相机API
  2081. useMiniProgramCamera() {
  2082. console.log("尝试使用小程序相机组件");
  2083. this.useMiniProgramCameraComponent = true;
  2084. },
  2085. // 添加新方法:显示静态图像
  2086. showStaticCameraPlaceholder() {
  2087. console.log("显示静态摄像头占位图");
  2088. const img = document.createElement("img");
  2089. img.src = "/static/images/camera-placeholder.png";
  2090. img.className = "static-camera-image";
  2091. img.style.width = "100%";
  2092. img.style.height = "100%";
  2093. img.style.objectFit = "cover";
  2094. const container = this.$refs.userCameraVideo.parentNode;
  2095. container.appendChild(img);
  2096. },
  2097. // 修改 handleTimeUpdate 方法
  2098. handleTimeUpdate(e) {
  2099. const currentTime = e.detail.currentTime || e.target.currentTime;
  2100. if (this.isRecording && this.recordingTimerCount) {
  2101. this.recordingTimeDisplay = this.formatTime(this.recordingTimerCount);
  2102. }
  2103. if (this.isPlayingLowScoreVideo) {
  2104. if (this.lowScoreVideoSubtitles && this.lowScoreVideoSubtitles.length > 0) {
  2105. const subtitle = this.lowScoreVideoSubtitles[0];
  2106. this.currentSubtitle = subtitle.text;
  2107. }
  2108. return;
  2109. }
  2110. let currentSubtitles = null;
  2111. if (this.isFollowUpQuestion && this.currentFollowUpQuestion) {
  2112. const subtitleKey = `followUpSubtitles_${this.currentFollowUpQuestion.id}`;
  2113. currentSubtitles = this[subtitleKey] || [{
  2114. startTime: 0,
  2115. endTime: 30,
  2116. text: this.currentFollowUpQuestion.digital_human_video_subtitle || this.currentFollowUpQuestion.question
  2117. }];
  2118. } else {
  2119. if (this.currentVideoIndex === 0) {
  2120. currentSubtitles = this.subtitles;
  2121. } else {
  2122. const subtitleArrayName = `question${this.currentVideoIndex}Subtitles`;
  2123. currentSubtitles = this[subtitleArrayName];
  2124. }
  2125. }
  2126. if (currentSubtitles && currentSubtitles.length > 0) {
  2127. const subtitle = currentSubtitles.find(
  2128. (sub) => currentTime >= sub.startTime && currentTime <= sub.endTime
  2129. ) || currentSubtitles[0];
  2130. if (subtitle) {
  2131. this.currentSubtitle = subtitle.text;
  2132. }
  2133. }
  2134. this.historyTime = currentTime;
  2135. this.lastUpdateTime = Date.now();
  2136. },
  2137. // Add a new method to handle the "Start Recording" button click
  2138. handleStartRecordingClick() {
  2139. this.showStartRecordingButton = false;
  2140. this.clearCountdown();
  2141. this.isWaitingForAnswer = false;
  2142. this.startRecordingAnswer();
  2143. },
  2144. // 修改 checkAudioPermission 方法,确保在录制前获取音频权限
  2145. checkAudioPermission() {
  2146. const systemInfo = common_vendor.index.getSystemInfoSync();
  2147. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith("mp-");
  2148. if (isMiniProgram) {
  2149. common_vendor.index.getSetting({
  2150. success: (res) => {
  2151. if (!res.authSetting["scope.record"]) {
  2152. common_vendor.index.authorize({
  2153. scope: "scope.record",
  2154. success: () => {
  2155. console.log("录音权限已获取");
  2156. },
  2157. fail: (err) => {
  2158. console.error("录音权限获取失败:", err);
  2159. this.showPermissionDialog("录音");
  2160. }
  2161. });
  2162. }
  2163. if (!res.authSetting["scope.camera"]) {
  2164. common_vendor.index.authorize({
  2165. scope: "scope.camera",
  2166. success: () => {
  2167. console.log("相机权限已获取");
  2168. },
  2169. fail: (err) => {
  2170. console.error("相机权限获取失败:", err);
  2171. this.showPermissionDialog("相机");
  2172. }
  2173. });
  2174. }
  2175. }
  2176. });
  2177. }
  2178. },
  2179. // 添加新方法:测试音频输入
  2180. testAudioInput() {
  2181. if (!this.cameraStream) {
  2182. console.warn("没有可用的媒体流,无法测试音频");
  2183. return;
  2184. }
  2185. const audioTracks = this.cameraStream.getAudioTracks();
  2186. if (audioTracks.length === 0) {
  2187. console.warn("没有检测到音频轨道,尝试重新获取");
  2188. this.tryGetAudioOnly();
  2189. return;
  2190. }
  2191. console.log("音频轨道信息:", audioTracks[0].getSettings());
  2192. try {
  2193. const AudioContext = window.AudioContext || window.webkitAudioContext;
  2194. if (!AudioContext) {
  2195. console.warn("浏览器不支持AudioContext");
  2196. return;
  2197. }
  2198. const audioContext = new AudioContext();
  2199. const analyser = audioContext.createAnalyser();
  2200. const microphone = audioContext.createMediaStreamSource(this.cameraStream);
  2201. microphone.connect(analyser);
  2202. analyser.fftSize = 256;
  2203. const bufferLength = analyser.frequencyBinCount;
  2204. const dataArray = new Uint8Array(bufferLength);
  2205. let silenceCounter = 0;
  2206. const checkAudio = () => {
  2207. if (this.isRecording)
  2208. return;
  2209. analyser.getByteFrequencyData(dataArray);
  2210. let sum = 0;
  2211. for (let i = 0; i < bufferLength; i++) {
  2212. sum += dataArray[i];
  2213. }
  2214. const average = sum / bufferLength;
  2215. if (average > 10) {
  2216. console.log("检测到音频输入,音量:", average);
  2217. silenceCounter = 0;
  2218. } else {
  2219. silenceCounter++;
  2220. if (silenceCounter > 10) {
  2221. console.warn("持续检测不到音频输入,可能麦克风未正常工作");
  2222. silenceCounter = 0;
  2223. }
  2224. }
  2225. requestAnimationFrame(checkAudio);
  2226. };
  2227. checkAudio();
  2228. } catch (e) {
  2229. console.error("音频测试失败:", e);
  2230. }
  2231. },
  2232. // 添加新方法:尝试单独获取音频
  2233. tryGetAudioOnly() {
  2234. navigator.mediaDevices.getUserMedia({ audio: true }).then((audioStream) => {
  2235. if (this.cameraStream) {
  2236. const videoTrack = this.cameraStream.getVideoTracks()[0];
  2237. const audioTrack = audioStream.getAudioTracks()[0];
  2238. const combinedStream = new MediaStream();
  2239. if (videoTrack)
  2240. combinedStream.addTrack(videoTrack);
  2241. if (audioTrack)
  2242. combinedStream.addTrack(audioTrack);
  2243. this.cameraStream = combinedStream;
  2244. const videoElement = this.$refs.userCameraVideo;
  2245. if (videoElement) {
  2246. videoElement.srcObject = combinedStream;
  2247. videoElement.muted = true;
  2248. }
  2249. console.log("成功合并音频和视频轨道");
  2250. } else {
  2251. console.warn("没有视频流可合并");
  2252. }
  2253. }).catch((err) => {
  2254. console.error("单独获取音频失败:", err);
  2255. });
  2256. },
  2257. // 添加新方法:显示权限对话框
  2258. showPermissionDialog(permissionType) {
  2259. common_vendor.index.showModal({
  2260. title: "需要权限",
  2261. content: `请允许使用${permissionType}权限,否则可能影响面试功能`,
  2262. confirmText: "去设置",
  2263. success: (res) => {
  2264. if (res.confirm) {
  2265. common_vendor.index.openSetting({
  2266. success: (settingRes) => {
  2267. console.log("设置页面打开成功", settingRes);
  2268. }
  2269. });
  2270. }
  2271. }
  2272. });
  2273. },
  2274. // 添加重试上传方法
  2275. retryVideoUpload() {
  2276. if (this.lastVideoToRetry) {
  2277. this.showRetryButton = false;
  2278. common_vendor.index.showLoading({
  2279. title: "正在重新提交...",
  2280. mask: true
  2281. });
  2282. this.submitVideoToInterview(this.lastVideoToRetry);
  2283. } else {
  2284. common_vendor.index.showToast({
  2285. title: "没有可重试的视频",
  2286. icon: "none"
  2287. });
  2288. }
  2289. },
  2290. // 添加一个新方法用于压缩视频
  2291. async compressVideo(videoBlob) {
  2292. if (videoBlob.size < 5 * 1024 * 1024) {
  2293. return videoBlob;
  2294. }
  2295. console.log("开始压缩视频,原始大小:", videoBlob.size);
  2296. const videoElement = document.createElement("video");
  2297. videoElement.muted = true;
  2298. videoElement.autoplay = false;
  2299. const canvas = document.createElement("canvas");
  2300. const ctx = canvas.getContext("2d");
  2301. videoElement.src = URL.createObjectURL(videoBlob);
  2302. return new Promise((resolve) => {
  2303. videoElement.onloadedmetadata = () => {
  2304. const width = Math.floor(videoElement.videoWidth / 2);
  2305. const height = Math.floor(videoElement.videoHeight / 2);
  2306. canvas.width = width;
  2307. canvas.height = height;
  2308. const stream = canvas.captureStream(15);
  2309. if (videoElement.captureStream) {
  2310. const originalStream = videoElement.captureStream();
  2311. const audioTracks = originalStream.getAudioTracks();
  2312. if (audioTracks.length > 0) {
  2313. stream.addTrack(audioTracks[0]);
  2314. }
  2315. }
  2316. const options = {
  2317. mimeType: "video/webm;codecs=vp8,opus",
  2318. audioBitsPerSecond: 64e3,
  2319. videoBitsPerSecond: 8e5
  2320. // 800kbps
  2321. };
  2322. const mediaRecorder = new MediaRecorder(stream, options);
  2323. const chunks = [];
  2324. mediaRecorder.ondataavailable = (e) => {
  2325. if (e.data.size > 0) {
  2326. chunks.push(e.data);
  2327. }
  2328. };
  2329. mediaRecorder.onstop = () => {
  2330. const compressedBlob = new Blob(chunks, { type: "video/webm" });
  2331. console.log("视频压缩完成,压缩后大小:", compressedBlob.size);
  2332. resolve(compressedBlob);
  2333. };
  2334. videoElement.onplay = () => {
  2335. mediaRecorder.start(10);
  2336. const drawFrame = () => {
  2337. if (videoElement.paused || videoElement.ended) {
  2338. mediaRecorder.stop();
  2339. return;
  2340. }
  2341. ctx.drawImage(videoElement, 0, 0, width, height);
  2342. requestAnimationFrame(drawFrame);
  2343. };
  2344. drawFrame();
  2345. };
  2346. videoElement.play();
  2347. };
  2348. });
  2349. },
  2350. // 修改 checkIOSCameraRecordPermission 方法
  2351. checkIOSCameraRecordPermission() {
  2352. const systemInfo = common_vendor.index.getSystemInfoSync();
  2353. if (systemInfo.platform !== "ios")
  2354. return;
  2355. common_vendor.index.getSetting({
  2356. success: (res) => {
  2357. if (!res.authSetting["scope.camera"]) {
  2358. common_vendor.index.authorize({
  2359. scope: "scope.camera",
  2360. success: () => {
  2361. console.log("iOS相机权限已获取");
  2362. },
  2363. fail: (err) => {
  2364. console.error("iOS相机权限获取失败:", err);
  2365. this.showPermissionDialog("相机");
  2366. }
  2367. });
  2368. }
  2369. if (!res.authSetting["scope.record"]) {
  2370. common_vendor.index.authorize({
  2371. scope: "scope.record",
  2372. success: () => {
  2373. console.log("iOS录音权限已获取");
  2374. },
  2375. fail: (err) => {
  2376. console.error("iOS录音权限获取失败:", err);
  2377. this.showPermissionDialog("录音");
  2378. }
  2379. });
  2380. }
  2381. }
  2382. });
  2383. },
  2384. // 添加新方法:检查并修复渲染问题
  2385. checkAndFixRenderingIssues() {
  2386. try {
  2387. if (typeof u !== "undefined" && u) {
  2388. if (!u.currentQuestion) {
  2389. console.log("修复: 创建缺失的currentQuestion对象");
  2390. u.currentQuestion = {};
  2391. }
  2392. if (u.currentQuestion && typeof u.currentQuestion.isImportant === "undefined") {
  2393. console.log("修复: 设置缺失的isImportant属性");
  2394. u.currentQuestion.isImportant = false;
  2395. }
  2396. }
  2397. } catch (e) {
  2398. console.log("防御性检查异常:", e);
  2399. }
  2400. },
  2401. // 添加格式化时间的辅助方法
  2402. formatTime(seconds) {
  2403. if (!seconds && seconds !== 0)
  2404. return "03:30";
  2405. const minutes = Math.floor(seconds / 60);
  2406. const remainingSeconds = seconds % 60;
  2407. return `${minutes.toString().padStart(2, "0")}:${remainingSeconds.toString().padStart(2, "0")}`;
  2408. },
  2409. // 添加获取问题数据的方法
  2410. fetchQuestions() {
  2411. this.loading = true;
  2412. const tenant_id = JSON.parse(common_vendor.index.getStorageSync("userInfo")).tenant_id || "1";
  2413. let position_id = 1;
  2414. try {
  2415. const selectedJob = JSON.parse(common_vendor.index.getStorageSync("selectedJob") || "{}");
  2416. if (selectedJob && selectedJob.id) {
  2417. position_id = selectedJob.id;
  2418. console.log("使用选择的职位ID获取问题:", position_id);
  2419. } else {
  2420. console.warn("未找到选择的职位信息,使用默认职位ID:", position_id);
  2421. }
  2422. } catch (e) {
  2423. console.error("解析职位信息失败:", e);
  2424. }
  2425. const timestamp = Date.now();
  2426. const requestUrl = `${common_config.apiBaseUrl}/api/wechat/open_questions/?position_id=${position_id}&tenant_id=${tenant_id}&question_form=0&_t=${timestamp}`;
  2427. console.log("完整的请求URL:", requestUrl);
  2428. common_vendor.index.request({
  2429. url: requestUrl,
  2430. method: "GET",
  2431. success: (res) => {
  2432. if (res.data && res.data.code === 2e3 && res.data.data && res.data.data.items) {
  2433. console.log("获取问题数据成功:", res.data.data.items);
  2434. this.questions = res.data.data.items;
  2435. this.processQuestionData();
  2436. this.playIntroVideo();
  2437. } else {
  2438. console.error("获取问题数据失败:", res.data);
  2439. common_vendor.index.showToast({
  2440. title: "获取问题数据失败",
  2441. icon: "none"
  2442. });
  2443. }
  2444. },
  2445. fail: (err) => {
  2446. console.error("请求问题数据失败:", err);
  2447. common_vendor.index.showToast({
  2448. title: "网络错误,请检查网络连接",
  2449. icon: "none"
  2450. });
  2451. },
  2452. complete: () => {
  2453. this.loading = false;
  2454. }
  2455. });
  2456. },
  2457. // 处理问题数据,提取视频URL和字幕
  2458. processQuestionData() {
  2459. this.videoList = [];
  2460. this.videoList.push(this.introVideoUrl);
  2461. this.subtitles = [
  2462. {
  2463. startTime: 0,
  2464. endTime: 5,
  2465. text: "你好,我是本次面试的面试官,欢迎参加本公司的线上面试!"
  2466. },
  2467. {
  2468. startTime: 5,
  2469. endTime: 13,
  2470. text: "面试预计需要15分钟,请你提前安排在网络良好、光线亮度合适、且相对安静的环境参加这次面试"
  2471. },
  2472. {
  2473. startTime: 13,
  2474. endTime: 20,
  2475. text: "以免影响本次面试的结果。如果你在面试过程中遇到问题,请与我们的招聘人员联系。"
  2476. }
  2477. ];
  2478. const sortedQuestions = [...this.questions].sort((a, b) => a.sequence_number - b.sequence_number);
  2479. const questionsToUse = sortedQuestions.slice(0, 5);
  2480. questionsToUse.forEach((question, index) => {
  2481. if (question.digital_human_video_url) {
  2482. this.videoList.push(question.digital_human_video_url);
  2483. const subtitleArray = [{
  2484. startTime: 0,
  2485. endTime: 30,
  2486. // 延长字幕显示时间到30秒
  2487. text: question.digital_human_video_subtitle || question.question
  2488. }];
  2489. const videoIndex = this.videoList.length - 1;
  2490. this[`question${videoIndex}Subtitles`] = subtitleArray;
  2491. this.subtitleMap[question.digital_human_video_url] = subtitleArray;
  2492. }
  2493. });
  2494. if (this.videoList.length <= 1)
  2495. ;
  2496. else {
  2497. console.log("处理后的视频列表:", this.videoList);
  2498. console.log("处理后的字幕:", this.subtitles);
  2499. }
  2500. },
  2501. // 使用默认视频和字幕(作为备用)
  2502. useDefaultVideosAndSubtitles() {
  2503. console.log("使用默认视频和字幕");
  2504. this.subtitles = [
  2505. {
  2506. startTime: 0,
  2507. endTime: 5,
  2508. text: "你好,我是本次面试的面试官,欢迎参加本公司的线上面试!"
  2509. },
  2510. {
  2511. startTime: 5,
  2512. endTime: 13,
  2513. text: "面试预计需要15分钟,请你提前安排在网络良好、光线亮度合适、且相对安静的环境参加这次面试"
  2514. },
  2515. {
  2516. startTime: 13,
  2517. endTime: 20,
  2518. text: "以免影响本次面试的结果。如果你在面试过程中遇到问题,请与我们的招聘人员联系。"
  2519. }
  2520. ];
  2521. this.question1Subtitles = [{
  2522. startTime: 0,
  2523. endTime: 10,
  2524. text: "请结合您的基本信息与过往履历进行简单的自我介绍,并讲一讲您有哪些优势胜任本岗位:"
  2525. }];
  2526. this.question2Subtitles = [{
  2527. startTime: 0,
  2528. endTime: 4,
  2529. text: "在工作中,你如何确保个人防护装备的正确使用?"
  2530. }];
  2531. this.question3Subtitles = [{
  2532. startTime: 0,
  2533. endTime: 4,
  2534. text: "描述一次你与团队合作改善生产流程的经历。"
  2535. }];
  2536. this.question4Subtitles = [{
  2537. startTime: 0,
  2538. endTime: 6,
  2539. text: "你在团队合作中曾遇到过哪些挑战?如何解决团队内部的分歧?"
  2540. }];
  2541. this.question5Subtitles = [{
  2542. startTime: 0,
  2543. endTime: 5,
  2544. text: "您已完成本次面试全部题目,请问您对于这个岗位还有什么想要了解的吗?"
  2545. }];
  2546. },
  2547. // 播放介绍视频
  2548. playIntroVideo() {
  2549. this.videoUrl = this.videoList[0];
  2550. this.videoPlaying = true;
  2551. this.$nextTick(() => {
  2552. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  2553. if (videoContext) {
  2554. videoContext.play();
  2555. }
  2556. });
  2557. },
  2558. // 添加新方法:获取默认问题ID
  2559. getDefaultQuestionId(videoIndex) {
  2560. switch (videoIndex) {
  2561. case 1:
  2562. return 10;
  2563. case 2:
  2564. return 11;
  2565. case 3:
  2566. return 12;
  2567. case 4:
  2568. return 13;
  2569. default:
  2570. return 10;
  2571. }
  2572. },
  2573. // 添加新方法:根据索引获取当前问题
  2574. getCurrentQuestionByIndex(videoIndex) {
  2575. const questionIndex = videoIndex - 1;
  2576. const sortedQuestions = [...this.questions].sort((a, b) => a.sequence_number - b.sequence_number);
  2577. if (questionIndex >= 0 && questionIndex < sortedQuestions.length) {
  2578. return sortedQuestions[questionIndex];
  2579. }
  2580. return null;
  2581. },
  2582. // 添加新方法:重置录制状态,准备重新回答
  2583. resetForRerecording() {
  2584. console.log("重置录制状态,准备重新回答");
  2585. this.isRecording = false;
  2586. this.showStopRecordingButton = false;
  2587. this.showStartRecordingButton = true;
  2588. this.clearCountdown();
  2589. if (this.recordingTimer) {
  2590. clearInterval(this.recordingTimer);
  2591. this.recordingTimer = null;
  2592. }
  2593. this.recordingTimerCount = 0;
  2594. this.recordingTimeDisplay = "00:00 ";
  2595. this.remainingTime = this.maxRecordingTime;
  2596. if (this.mediaRecorder && this.mediaRecorder.state !== "inactive") {
  2597. this.mediaRecorder.stop();
  2598. this.recordedChunks = [];
  2599. }
  2600. if (this.cameraContext) {
  2601. this.cameraContext.stopRecord({
  2602. success: () => {
  2603. console.log("相机录制已停止");
  2604. },
  2605. fail: (err) => {
  2606. console.error("停止相机录制失败:", err);
  2607. }
  2608. });
  2609. }
  2610. this.questionRetryMap = {};
  2611. },
  2612. // 修改 playLowScoreVideo 方法,优化字幕显示并添加重试次数限制
  2613. playLowScoreVideo() {
  2614. var _a;
  2615. console.log("播放低分提示视频");
  2616. const currentQuestionId = (_a = this.getCurrentQuestionByIndex(this.currentVideoIndex)) == null ? void 0 : _a.id;
  2617. if (!currentQuestionId) {
  2618. console.error("无法获取当前问题ID");
  2619. return;
  2620. }
  2621. if (!this.questionRetryMap[currentQuestionId]) {
  2622. this.questionRetryMap[currentQuestionId] = 1;
  2623. } else {
  2624. this.questionRetryMap[currentQuestionId]++;
  2625. }
  2626. if (this.questionRetryMap[currentQuestionId] > this.maxQuestionRetries) {
  2627. console.log(`问题 ${currentQuestionId} 已超过最大重试次数,自动进入下一题`);
  2628. this.isPlayingLowScoreVideo = false;
  2629. this.isFollowUpQuestion = false;
  2630. this.currentFollowUpQuestion = null;
  2631. this.followUpQuestion = "";
  2632. this.parentQuestion = "";
  2633. this.currentVideoIndex++;
  2634. if (this.currentVideoIndex < this.videoList.length) {
  2635. const nextQuestion = this.getCurrentQuestionByIndex(this.currentVideoIndex);
  2636. if (nextQuestion) {
  2637. this.currentSubtitle = nextQuestion.digital_human_video_subtitle || nextQuestion.question;
  2638. }
  2639. this.videoUrl = this.videoList[this.currentVideoIndex];
  2640. this.videoPlaying = true;
  2641. this.$nextTick(() => {
  2642. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  2643. if (videoContext) {
  2644. videoContext.play();
  2645. }
  2646. });
  2647. } else {
  2648. this.finishInterview();
  2649. }
  2650. return;
  2651. }
  2652. this.isPlayingLowScoreVideo = true;
  2653. this.showStartRecordingButton = false;
  2654. this.showStopRecordingButton = false;
  2655. this.showRerecordButton = false;
  2656. this.videoUrl = this.lowScoreVideoUrl;
  2657. this.videoPlaying = true;
  2658. const currentQuestion = this.getCurrentQuestionByIndex(this.currentVideoIndex);
  2659. const originalSubtitle = currentQuestion ? currentQuestion.digital_human_video_subtitle || currentQuestion.question : this.currentSubtitle;
  2660. this.currentSubtitle = "";
  2661. this.$nextTick(() => {
  2662. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  2663. if (videoContext) {
  2664. videoContext.play();
  2665. setTimeout(() => {
  2666. this.currentSubtitle = "我未听清楚您在说什么,请您再说一遍!";
  2667. this.lowScoreVideoSubtitles = [
  2668. {
  2669. startTime: 0,
  2670. endTime: 30,
  2671. text: "我未听清楚您在说什么,请您再说一遍!",
  2672. translation: "I didn't quite catch what you said, could you please repeat it?"
  2673. }
  2674. ];
  2675. }, 500);
  2676. }
  2677. });
  2678. this.originalQuestionSubtitle = originalSubtitle;
  2679. },
  2680. // 添加新方法:处理重新录制按钮点击
  2681. handleRerecordButtonClick() {
  2682. console.log("点击重新录制按钮");
  2683. this.retryCount++;
  2684. console.log(`当前重试次数: ${this.retryCount}/${this.maxRetryAttempts}`);
  2685. this.showRerecordButton = false;
  2686. this.handleStartRecordingClick();
  2687. },
  2688. // 页面卸载时关闭WebSocket连接
  2689. onUnload() {
  2690. console.log("页面卸载,关闭WebSocket连接");
  2691. this.cleanupPersonDetectionWebSocket();
  2692. this.stopUserCamera();
  2693. this.clearCountdown();
  2694. if (this.recordingTimer) {
  2695. clearInterval(this.recordingTimer);
  2696. this.recordingTimer = null;
  2697. }
  2698. if (this.mediaRecorder && this.mediaRecorder.state !== "inactive") {
  2699. this.mediaRecorder.stop();
  2700. }
  2701. common_vendor.index.setKeepScreenOn({
  2702. keepScreenOn: false
  2703. });
  2704. },
  2705. // 页面隐藏时关闭WebSocket连接
  2706. onHide() {
  2707. console.log("页面隐藏,关闭WebSocket连接");
  2708. this.cleanupPersonDetectionWebSocket();
  2709. if (this.isRecording) {
  2710. console.log("页面隐藏时正在录制,录制将继续");
  2711. common_vendor.index.showToast({
  2712. title: "请不要离开面试页面",
  2713. icon: "none",
  2714. duration: 2e3
  2715. });
  2716. }
  2717. },
  2718. // 页面显示时重新初始化WebSocket连接
  2719. onShow() {
  2720. console.log("identity-verify页面onShow");
  2721. console.log("当前本地存储中的职位信息:", common_vendor.index.getStorageSync("selectedJob"));
  2722. this.fetchQuestions();
  2723. const systemInfo = common_vendor.index.getSystemInfoSync();
  2724. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith("mp-");
  2725. if (isMiniProgram) {
  2726. if (!this.personDetectionSocket) {
  2727. console.log("重新初始化WebSocket连接");
  2728. this.initPersonDetectionWebSocket();
  2729. } else if (!this.personDetectionInterval) {
  2730. console.log("重新启动人脸检测定时器");
  2731. this.startPersonDetectionInterval();
  2732. }
  2733. }
  2734. },
  2735. // 添加新方法:阻止视频控制
  2736. preventVideoControl(e) {
  2737. e.preventDefault();
  2738. e.stopPropagation();
  2739. console.log("阻止视频控制操作");
  2740. return false;
  2741. },
  2742. // 添加获取追问问题的方法
  2743. fetchFollowUpQuestions() {
  2744. const tenant_id = JSON.parse(common_vendor.index.getStorageSync("userInfo")).tenant_id || "1";
  2745. let position_id = 1;
  2746. try {
  2747. const selectedJob = JSON.parse(common_vendor.index.getStorageSync("selectedJob") || "{}");
  2748. if (selectedJob && selectedJob.id) {
  2749. position_id = selectedJob.id;
  2750. console.log("使用选择的职位ID获取追问问题:", position_id);
  2751. } else {
  2752. console.warn("未找到选择的职位信息,使用默认职位ID:", position_id);
  2753. }
  2754. } catch (e) {
  2755. console.error("解析职位信息失败:", e);
  2756. }
  2757. const timestamp = Date.now();
  2758. const requestUrl = `${common_config.apiBaseUrl}/api/wechat/open_questions/?position_id=${position_id}&tenant_id=${tenant_id}&question_form=5&_t=${timestamp}`;
  2759. console.log("获取追问问题的请求URL:", requestUrl);
  2760. common_vendor.index.request({
  2761. url: requestUrl,
  2762. method: "GET",
  2763. success: (res) => {
  2764. if (res.data && res.data.code === 2e3 && res.data.data && res.data.data.items) {
  2765. console.log("获取追问问题数据成功:", res.data.data.items);
  2766. this.followUpQuestions = res.data.data.items.map((item) => ({
  2767. ...item,
  2768. question_form: 5
  2769. // 确保每个追问问题都有正确的question_form值
  2770. }));
  2771. this.processFollowUpQuestions();
  2772. } else {
  2773. console.error("获取追问问题数据失败:", res.data);
  2774. this.followUpQuestions = [];
  2775. }
  2776. },
  2777. fail: (err) => {
  2778. console.error("请求追问问题数据失败:", err);
  2779. this.followUpQuestions = [];
  2780. }
  2781. });
  2782. },
  2783. // 改进处理追问问题数据的方法
  2784. processFollowUpQuestions() {
  2785. if (!this.followUpQuestions || this.followUpQuestions.length === 0) {
  2786. console.log("没有追问问题数据");
  2787. this.followUpQuestions = [];
  2788. return;
  2789. }
  2790. console.log("处理追问问题数据,总数:", this.followUpQuestions.length);
  2791. this.followUpQuestions = this.followUpQuestions.filter((q) => q.parent_question_id);
  2792. const parentQuestionIds = /* @__PURE__ */ new Set();
  2793. this.followUpQuestions.forEach((question) => {
  2794. if (question.parent_question_id) {
  2795. parentQuestionIds.add(question.parent_question_id);
  2796. }
  2797. });
  2798. console.log("有追问的父问题ID:", Array.from(parentQuestionIds));
  2799. this.hasPlayedFollowUp = {};
  2800. },
  2801. // 修改检查并播放追问问题的方法
  2802. checkAndPlayFollowUpQuestion(parentQuestionId) {
  2803. console.log("检查是否有追问问题,父问题ID:", parentQuestionId);
  2804. if (this.isWaitingForAnswer) {
  2805. console.log("正在等待用户回答,暂不处理追问");
  2806. return;
  2807. }
  2808. if (!parentQuestionId) {
  2809. console.warn("没有父问题ID,无法检查追问问题");
  2810. this.proceedToNextQuestion();
  2811. return;
  2812. }
  2813. if (this.hasPlayedFollowUp[parentQuestionId]) {
  2814. console.log("已经播放过此问题的追问,直接进入下一个问题");
  2815. this.retryCount = 0;
  2816. this.proceedToNextQuestion();
  2817. return;
  2818. }
  2819. const followUpQuestion = this.followUpQuestions.find(
  2820. (q) => q.parent_question_id === parentQuestionId && q.digital_human_video_url && q.question_form === 5
  2821. );
  2822. if (followUpQuestion) {
  2823. console.log("找到追问问题:", followUpQuestion);
  2824. const recordingDuration = this.getRecordingDuration();
  2825. const lowScoreDuration = 7;
  2826. const minDuration = 3;
  2827. if (recordingDuration < lowScoreDuration) {
  2828. let message = recordingDuration < minDuration ? `录制时间 ${recordingDuration} 秒,少于最小时长 ${minDuration} 秒` : `录制时间 ${recordingDuration} 秒,少于标准时长 ${lowScoreDuration} 秒`;
  2829. console.log(message + ",将播放低分提示视频");
  2830. this.retryCount++;
  2831. this.needPlayLowScoreVideo = true;
  2832. this.playLowScoreVideo();
  2833. return;
  2834. }
  2835. this.retryCount = 0;
  2836. this.hasPlayedFollowUp[parentQuestionId] = true;
  2837. this.isFollowUpQuestion = true;
  2838. this.currentParentQuestionId = parentQuestionId;
  2839. this.currentFollowUpQuestion = followUpQuestion;
  2840. this.playFollowUpQuestionVideo(followUpQuestion);
  2841. } else {
  2842. console.log("没有找到对应的追问问题,继续下一个问题");
  2843. this.retryCount = 0;
  2844. this.proceedToNextQuestion();
  2845. }
  2846. },
  2847. // 修改播放追问问题视频的方法
  2848. playFollowUpQuestionVideo(followUpQuestion) {
  2849. console.log("播放追问问题视频:", followUpQuestion.digital_human_video_url);
  2850. this.parentQuestion = this.currentSubtitle;
  2851. this.videoUrl = followUpQuestion.digital_human_video_url;
  2852. this.videoPlaying = true;
  2853. this.isFollowUpQuestion = true;
  2854. this.currentFollowUpQuestion = followUpQuestion;
  2855. const followUpSubtitles = [{
  2856. startTime: 0,
  2857. endTime: 60,
  2858. // 延长显示时间到60秒
  2859. text: followUpQuestion.digital_human_video_subtitle || followUpQuestion.question
  2860. }];
  2861. const subtitleKey = `followUpSubtitles_${followUpQuestion.id}`;
  2862. this[subtitleKey] = followUpSubtitles;
  2863. this.$nextTick(() => {
  2864. const videoContext = common_vendor.index.createVideoContext("myVideo", this);
  2865. if (videoContext) {
  2866. videoContext.play();
  2867. this.currentSubtitle = followUpSubtitles[0].text;
  2868. }
  2869. });
  2870. },
  2871. // 添加作废面试的方法
  2872. invalidateInterview() {
  2873. if (this.isRecording) {
  2874. this.stopRecordingAnswer();
  2875. }
  2876. if (this.recordingTimer) {
  2877. clearInterval(this.recordingTimer);
  2878. }
  2879. this.isRecording = false;
  2880. this.showStopRecordingButton = false;
  2881. this.showStartRecordingButton = false;
  2882. setTimeout(() => {
  2883. common_vendor.index.switchTab({
  2884. url: "/pages/index/index"
  2885. });
  2886. }, 500);
  2887. },
  2888. initPersonDetectionWebSocket() {
  2889. if (this.personDetectionSocket) {
  2890. this.cleanupPersonDetectionWebSocket();
  2891. }
  2892. try {
  2893. this.personDetectionSocket = common_vendor.index.connectSocket({
  2894. url: `${common_config.personDetectionWsUrl}/ws/interview-room/room_${common_vendor.index.getStorageSync("appId")}/${common_vendor.index.getStorageSync("appId")}/`,
  2895. success: () => {
  2896. console.log("WebSocket connection initiated");
  2897. },
  2898. fail: (error) => {
  2899. console.error("WebSocket connection failed:", error);
  2900. }
  2901. });
  2902. this.personDetectionSocket.onOpen(() => {
  2903. console.log("WebSocket connection opened");
  2904. this.startPersonDetectionInterval();
  2905. });
  2906. this.personDetectionSocket.onError((error) => {
  2907. console.error("WebSocket error:", error);
  2908. this.cleanupPersonDetectionWebSocket();
  2909. });
  2910. this.personDetectionSocket.onClose(() => {
  2911. console.log("WebSocket connection closed");
  2912. this.cleanupPersonDetectionWebSocket();
  2913. });
  2914. this.personDetectionSocket.onMessage((res) => {
  2915. try {
  2916. const data = JSON.parse(res.data);
  2917. if (data.type === "person_detection_result") {
  2918. this.handlePersonDetectionResult(data);
  2919. }
  2920. } catch (error) {
  2921. console.error("Error parsing WebSocket message:", error);
  2922. }
  2923. });
  2924. } catch (error) {
  2925. console.error("Error initializing WebSocket:", error);
  2926. this.cleanupPersonDetectionWebSocket();
  2927. }
  2928. },
  2929. startPersonDetectionInterval() {
  2930. if (this.personDetectionInterval) {
  2931. clearInterval(this.personDetectionInterval);
  2932. }
  2933. this.personDetectionInterval = setInterval(() => {
  2934. try {
  2935. if (!this.personDetectionSocket || !this.cameraContext) {
  2936. console.warn("人脸检测:相机上下文或WebSocket连接未就绪");
  2937. return;
  2938. }
  2939. this.cameraContext.takePhoto({
  2940. quality: "low",
  2941. success: (res) => {
  2942. try {
  2943. const tempFilePath = res.tempImagePath;
  2944. if (!tempFilePath) {
  2945. console.warn("人脸检测:未获取到有效的图片路径");
  2946. return;
  2947. }
  2948. common_vendor.index.getFileSystemManager().readFile({
  2949. filePath: tempFilePath,
  2950. encoding: "base64",
  2951. success: (res2) => {
  2952. try {
  2953. const base64Image = res2.data;
  2954. if (!this.personDetectionSocket || this.personDetectionSocket.readyState !== 1) {
  2955. console.warn("人脸检测:WebSocket连接已断开或未就绪");
  2956. return;
  2957. }
  2958. this.personDetectionSocket.send({
  2959. data: JSON.stringify({
  2960. type: "person_detection",
  2961. image_data: base64Image
  2962. })
  2963. });
  2964. } catch (wsError) {
  2965. console.error("人脸检测:发送WebSocket数据时出错:", wsError);
  2966. }
  2967. },
  2968. fail: (error) => {
  2969. console.error("人脸检测:读取图片文件失败:", error);
  2970. }
  2971. });
  2972. } catch (fileError) {
  2973. console.error("人脸检测:处理图片文件时出错:", fileError);
  2974. }
  2975. },
  2976. fail: (error) => {
  2977. console.error("人脸检测:拍照失败:", error);
  2978. }
  2979. });
  2980. } catch (mainError) {
  2981. console.error("人脸检测:主流程执行出错:", mainError);
  2982. }
  2983. }, 5e3);
  2984. },
  2985. cleanupPersonDetectionWebSocket() {
  2986. if (this.personDetectionInterval) {
  2987. clearInterval(this.personDetectionInterval);
  2988. this.personDetectionInterval = null;
  2989. }
  2990. if (this.personDetectionSocket) {
  2991. try {
  2992. this.personDetectionSocket.close();
  2993. } catch (error) {
  2994. console.error("Error closing WebSocket:", error);
  2995. }
  2996. this.personDetectionSocket = null;
  2997. }
  2998. },
  2999. handlePersonDetectionResult(data) {
  3000. if (data.data.identity.status !== "identity_verified") {
  3001. this.showPageWarning = true;
  3002. common_vendor.index.showToast({
  3003. title: data.data.identity.message,
  3004. icon: "none",
  3005. duration: 3e3
  3006. });
  3007. common_vendor.index.vibrateLong({
  3008. success: function() {
  3009. console.log("Vibration successful");
  3010. },
  3011. fail: function(err) {
  3012. console.error("Vibration failed:", err);
  3013. }
  3014. });
  3015. setTimeout(() => {
  3016. this.showPageWarning = false;
  3017. }, 3e3);
  3018. }
  3019. },
  3020. // 进入追问模式
  3021. enterFollowUpMode() {
  3022. this.isFollowUpMode = true;
  3023. this.mainQuestionIndex = this.currentVideoIndex;
  3024. console.log("进入追问模式,保存主问题索引:", this.mainQuestionIndex);
  3025. },
  3026. // 修改 handleFollowUpQuestion 方法
  3027. async handleFollowUpQuestion(questionData) {
  3028. console.log("处理追问:", questionData);
  3029. this.enterFollowUpMode();
  3030. console.log("处理追问问题数据:", questionData);
  3031. if (!questionData || !questionData.follow_up_voice_url || !questionData.follow_up_question) {
  3032. console.error("追问数据不完整:", questionData);
  3033. common_vendor.index.showToast({
  3034. title: "获取追问数据失败",
  3035. icon: "none"
  3036. });
  3037. return;
  3038. }
  3039. this.parentQuestion = questionData.original_question || "";
  3040. let audioUrl = "";
  3041. if (questionData.follow_up_voice_url.direct_url) {
  3042. audioUrl = questionData.follow_up_voice_url.direct_url;
  3043. } else if (questionData.follow_up_voice_url.file_url) {
  3044. audioUrl = questionData.follow_up_voice_url.file_url;
  3045. }
  3046. if (!audioUrl.startsWith("http")) {
  3047. audioUrl = common_config.apiBaseUrl + audioUrl;
  3048. }
  3049. console.log("处理后的音频URL:", audioUrl);
  3050. const followUpQuestionObj = {
  3051. id: Date.now(),
  3052. question: questionData.follow_up_question.trim(),
  3053. // 去除可能的空白字符
  3054. audioUrl,
  3055. originalQuestion: questionData.original_question,
  3056. sessionId: questionData.session_id
  3057. };
  3058. console.log("创建的追问问题对象:", followUpQuestionObj);
  3059. this.followUpQuestions.push(followUpQuestionObj);
  3060. this.currentFollowUpIndex = this.followUpQuestions.length - 1;
  3061. this.followUpQuestion = followUpQuestionObj.question;
  3062. this.followUpAudioUrl = followUpQuestionObj.audioUrl;
  3063. this.isFollowUpQuestion = true;
  3064. this.currentFollowUpQuestion = followUpQuestionObj;
  3065. this.showSubtitle(followUpQuestionObj.question, true);
  3066. try {
  3067. await this.playFollowUpAudio();
  3068. console.log("音频播放完成,准备录制回答");
  3069. this.prepareToAnswer(true, followUpQuestionObj);
  3070. } catch (error) {
  3071. console.error("音频播放失败:", error);
  3072. this.prepareToAnswer(true, followUpQuestionObj);
  3073. }
  3074. },
  3075. // 播放追问音频
  3076. async playFollowUpAudio() {
  3077. return new Promise((resolve, reject) => {
  3078. console.log("开始播放追问音频, URL:", this.followUpAudioUrl);
  3079. if (!this.followUpAudioUrl) {
  3080. console.error("没有音频URL");
  3081. reject(new Error("没有音频URL"));
  3082. return;
  3083. }
  3084. common_vendor.index.showLoading({
  3085. title: "思考中..."
  3086. });
  3087. this.stopAndDestroyAudio();
  3088. try {
  3089. const innerAudioContext = common_vendor.index.createInnerAudioContext();
  3090. this.audioContext = innerAudioContext;
  3091. innerAudioContext.autoplay = true;
  3092. innerAudioContext.obeyMuteSwitch = false;
  3093. innerAudioContext.volume = 1;
  3094. innerAudioContext.onCanplay(() => {
  3095. console.log("音频可以播放");
  3096. common_vendor.index.hideLoading();
  3097. this.isAudioPlaying = true;
  3098. });
  3099. innerAudioContext.onEnded(() => {
  3100. console.log("追问音频播放完成");
  3101. this.isAudioPlaying = false;
  3102. resolve();
  3103. setTimeout(() => {
  3104. this.stopAndDestroyAudio();
  3105. this.prepareToAnswer(true, this.currentFollowUpQuestion);
  3106. }, 100);
  3107. });
  3108. innerAudioContext.onError((res) => {
  3109. console.error("音频播放错误:", res);
  3110. this.isAudioPlaying = false;
  3111. common_vendor.index.hideLoading();
  3112. common_vendor.index.showToast({
  3113. title: "音频播放失败",
  3114. icon: "none"
  3115. });
  3116. reject(res);
  3117. this.stopAndDestroyAudio();
  3118. });
  3119. console.log("设置音频源:", this.followUpAudioUrl);
  3120. innerAudioContext.src = this.followUpAudioUrl;
  3121. } catch (error) {
  3122. console.error("创建或播放音频失败:", error);
  3123. this.isAudioPlaying = false;
  3124. common_vendor.index.hideLoading();
  3125. common_vendor.index.showToast({
  3126. title: "音频播放失败",
  3127. icon: "none"
  3128. });
  3129. this.stopAndDestroyAudio();
  3130. reject(error);
  3131. }
  3132. });
  3133. },
  3134. // 停止并销毁音频
  3135. stopAndDestroyAudio() {
  3136. if (!this.audioContext) {
  3137. return;
  3138. }
  3139. const ctx = this.audioContext;
  3140. this.audioContext = null;
  3141. try {
  3142. if (this.isAudioPlaying) {
  3143. ctx.stop();
  3144. }
  3145. } catch (error) {
  3146. console.error("停止音频播放失败:", error);
  3147. }
  3148. try {
  3149. ctx.destroy();
  3150. } catch (error) {
  3151. console.error("销毁音频实例失败:", error);
  3152. }
  3153. this.isAudioPlaying = false;
  3154. },
  3155. // 显示字幕
  3156. showSubtitle(text, isFollowUp = true) {
  3157. console.log("显示字幕:", text);
  3158. this.subtitleText = text;
  3159. this.showSubtitleText = true;
  3160. this.isFollowUpQuestion = isFollowUp;
  3161. this.$nextTick(() => {
  3162. setTimeout(() => {
  3163. this.showSubtitleText = false;
  3164. }, 8e3);
  3165. });
  3166. },
  3167. // 显示问题对话框
  3168. showQuestionDialog() {
  3169. if (this.followUpQuestion) {
  3170. common_vendor.index.showModal({
  3171. title: "追问问题",
  3172. content: this.followUpQuestion,
  3173. showCancel: false,
  3174. success: () => {
  3175. this.prepareToAnswer(true, this.followUpQuestions[this.currentFollowUpIndex]);
  3176. }
  3177. });
  3178. }
  3179. },
  3180. // 显示面试官思考中loading
  3181. showThinkingLoading() {
  3182. this.isThinking = true;
  3183. common_vendor.index.showLoading({
  3184. title: "面试官正在思考中",
  3185. mask: false
  3186. });
  3187. },
  3188. // 隐藏面试官思考中loading
  3189. hideThinkingLoading() {
  3190. this.isThinking = false;
  3191. common_vendor.index.hideLoading();
  3192. if (this.thinkingTimer) {
  3193. clearTimeout(this.thinkingTimer);
  3194. this.thinkingTimer = null;
  3195. }
  3196. }
  3197. },
  3198. computed: {
  3199. // 计算进度比例
  3200. progressRatio() {
  3201. return this.recordingTimerCount / this.maxRecordingTime;
  3202. },
  3203. // 右半圆旋转角度
  3204. half1Turn() {
  3205. if (this.progressRatio <= 0.5) {
  3206. return this.progressRatio * 2 * 180;
  3207. } else {
  3208. return 180;
  3209. }
  3210. },
  3211. // 左半圆旋转角度
  3212. half2Turn() {
  3213. if (this.progressRatio <= 0.5) {
  3214. return 0;
  3215. } else {
  3216. return (this.progressRatio - 0.5) * 2 * 180;
  3217. }
  3218. },
  3219. // 修改进度百分比的计算方式
  3220. progressPercent() {
  3221. return Math.min(Math.round(this.recordingTimerCount / this.maxRecordingTime * 100), 100);
  3222. },
  3223. // 添加总题数计算属性
  3224. totalQuestions() {
  3225. return this.questions.length || 5;
  3226. }
  3227. }
  3228. };
  3229. function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
  3230. return common_vendor.e({
  3231. a: $data.videoUrl,
  3232. b: common_vendor.o((...args) => $options.handleVideoError && $options.handleVideoError(...args)),
  3233. c: common_vendor.o((...args) => $options.handleVideoEnded && $options.handleVideoEnded(...args)),
  3234. d: common_vendor.o((...args) => $options.handleTimeUpdate && $options.handleTimeUpdate(...args)),
  3235. e: common_vendor.o((...args) => $options.preventVideoControl && $options.preventVideoControl(...args)),
  3236. f: common_vendor.o((...args) => $options.preventVideoControl && $options.preventVideoControl(...args)),
  3237. g: $data.showAnswerButton
  3238. }, $data.showAnswerButton ? {
  3239. h: common_vendor.o((...args) => $options.handleAnswerButtonClick && $options.handleAnswerButtonClick(...args))
  3240. } : {}, {
  3241. i: $data.currentSubtitle || $data.showSubtitleText && $data.subtitleText
  3242. }, $data.currentSubtitle || $data.showSubtitleText && $data.subtitleText ? common_vendor.e({
  3243. j: $data.currentVideoIndex > 0
  3244. }, $data.currentVideoIndex > 0 ? {
  3245. k: common_vendor.t($data.currentVideoIndex),
  3246. l: common_vendor.t($options.totalQuestions)
  3247. } : {}, {
  3248. m: !$data.isFollowUpQuestion
  3249. }, !$data.isFollowUpQuestion ? {
  3250. n: common_vendor.t($data.currentSubtitle)
  3251. } : {
  3252. o: common_vendor.t($data.parentQuestion),
  3253. p: common_vendor.t($data.subtitleText || $data.currentSubtitle)
  3254. }) : {}, {
  3255. q: $data.useMiniProgramCameraComponent
  3256. }, $data.useMiniProgramCameraComponent ? {
  3257. r: common_vendor.o((...args) => $options.handleCameraError && $options.handleCameraError(...args))
  3258. } : {}, {
  3259. s: $data.showPageWarning ? 1 : "",
  3260. t: $data.loading
  3261. }, $data.loading ? {} : {}, {
  3262. v: $data.showDebugInfo
  3263. }, $data.showDebugInfo ? common_vendor.e({
  3264. w: $data.assistantResponse
  3265. }, $data.assistantResponse ? {
  3266. x: common_vendor.t($data.assistantResponse)
  3267. } : {}, {
  3268. y: $data.audioTranscript
  3269. }, $data.audioTranscript ? {
  3270. z: common_vendor.t($data.audioTranscript)
  3271. } : {}, {
  3272. A: common_vendor.f($data.processedResponses, (item, index, i0) => {
  3273. return common_vendor.e({
  3274. a: item.role
  3275. }, item.role ? {
  3276. b: common_vendor.t(item.role)
  3277. } : {}, {
  3278. c: item.transcript
  3279. }, item.transcript ? {
  3280. d: common_vendor.t(item.transcript)
  3281. } : {}, {
  3282. e: index
  3283. });
  3284. })
  3285. }) : {}, {
  3286. B: $data.showStopRecordingButton
  3287. }, $data.showStopRecordingButton ? {
  3288. C: common_vendor.o((...args) => $options.stopRecordingAnswer && $options.stopRecordingAnswer(...args))
  3289. } : {}, {
  3290. D: $data.isRecording
  3291. }, $data.isRecording ? {
  3292. E: common_vendor.t($data.recordingTimeDisplay),
  3293. F: `conic-gradient(${$data.progressColor} ${$options.progressPercent}%, ${$data.progressBgColor} 0%)`
  3294. } : {}, {
  3295. G: $data.showStartRecordingButton
  3296. }, $data.showStartRecordingButton ? {
  3297. H: common_vendor.o((...args) => $options.handleStartRecordingClick && $options.handleStartRecordingClick(...args))
  3298. } : {}, {
  3299. I: $data.showRetryButton
  3300. }, $data.showRetryButton ? {
  3301. J: common_vendor.o((...args) => $options.retryVideoUpload && $options.retryVideoUpload(...args))
  3302. } : {}, {
  3303. K: $data.showCountdown
  3304. }, $data.showCountdown ? {
  3305. L: common_vendor.t($data.countdownValue)
  3306. } : {}, {
  3307. M: $data.showRerecordButton
  3308. }, $data.showRerecordButton ? {
  3309. N: common_vendor.o((...args) => $options.handleRerecordButtonClick && $options.handleRerecordButtonClick(...args))
  3310. } : {}, {
  3311. O: $data.showPageWarning ? 1 : ""
  3312. });
  3313. }
  3314. const MiniProgramPage = /* @__PURE__ */ common_vendor._export_sfc(_sfc_main, [["render", _sfc_render], ["__scopeId", "data-v-464e78c6"]]);
  3315. wx.createPage(MiniProgramPage);