identity-verify.js 139 KB

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