identity-verify.js 115 KB

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