identity-verify.js 125 KB

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