identity-verify.js 115 KB

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