demo.js 142 KB

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