demo.js 144 KB

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