demo.vue 195 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931
  1. <template>
  2. <view class="custom-navbar" :style="{paddingTop: statusBarHeight + 'px'}">
  3. <!-- <view class="navbar-title">我的标题</view>1 -->
  4. </view>
  5. <div class="identity-verify-container" :class="{ 'page-warning': showPageWarning }">
  6. <div class="digital-human-container">
  7. <!-- 添加题号显示 -->
  8. <!-- <div class="question-counter" v-if="currentVideoIndex > 0">
  9. <span class="question-number">{{ currentVideoIndex }}/{{ totalQuestions }}</span>
  10. </div> -->
  11. <!-- AI数字人视频/图像显示区域 -->
  12. <div class="digital-human-video">
  13. <!-- 添加GIF图片显示区域 -->
  14. <!-- <img v-if="showGif && gifUrl" :src="gifUrl" class="gif-player" alt="面试官GIF" /> -->
  15. <!-- <video
  16. v-if="showGif && gifUrl"
  17. :src="gifUrl"
  18. id="mpVideo"
  19. autoplay
  20. class="video-player"
  21. :controls="false"
  22. loop
  23. muted
  24. object-fit="contain"
  25. ></video> v-if="!showGif"-->
  26. <!-- 视频播放区域,当showGif为false时显示 -->
  27. <video
  28. :src="videoUrl"
  29. id="myVideo"
  30. ref="videoPlayer"
  31. autoplay
  32. playsinline
  33. disablePictureInPicture
  34. controlsList="nodownload nofullscreen noremoteplayback"
  35. class="video-player"
  36. :controls="false"
  37. @error="handleVideoError"
  38. @ended="handleVideoEnded"
  39. @timeupdate="handleTimeUpdate"
  40. @click.prevent="preventVideoControl"
  41. @touchstart.prevent="preventVideoControl">
  42. </video>
  43. <!-- 添加透明蒙层 -->
  44. <div class="video-overlay"></div>
  45. <div class="answer-button-container" v-if="showAnswerButton">
  46. <button class="answer-button" @click="handleAnswerButtonClick">
  47. 开始回答
  48. </button>
  49. </div>
  50. <!-- 添加字幕覆盖层 -->
  51. <div class="subtitle-overlay" v-if="currentSubtitle || (showSubtitleText && subtitleText)">
  52. <!-- 添加题号显示 -->
  53. <div class="subtitle-header" v-if="currentVideoIndex > 0">
  54. <span class="question-tag">{{ currentVideoIndex }}/{{ totalQuestions }}</span>
  55. </div>
  56. <!-- 显示父问题 -->
  57. <div class="subtitle-main" v-if="!isFollowUpQuestion">{{ currentSubtitle }}</div>
  58. <!-- 当是追问时显示父问题和追问问题 -->
  59. <template v-else>
  60. <div class="parent-question">{{ parentQuestion }}</div>
  61. <div class="followup-container">
  62. <div class="followup-content">
  63. <span class="followup-label">追问:</span>
  64. <span class="followup-text">{{ subtitleText || currentSubtitle }}</span>
  65. </div>
  66. </div>
  67. </template>
  68. </div>
  69. <!-- 添加答题按钮 -->
  70. </div>
  71. <!-- 用户摄像头视频显示区域 -->
  72. <div class="user-camera-container" :class="{ 'camera-warning': showPageWarning }">
  73. <!-- 在小程序环境中使用camera组件 -->
  74. <camera v-if="useMiniProgramCameraComponent"
  75. device-position="front"
  76. flash="off"
  77. class="user-camera-video"
  78. @error="handleCameraError"
  79. :record-audio="true"
  80. frame-size="small"
  81. resolution="low"
  82. :disable-zoom="true"
  83. :enable-camera="true"
  84. :enable-record="true"
  85. mode="normal">
  86. </camera>
  87. <!-- 在H5/App环境中使用video元素 -->
  88. <video v-else
  89. id="userCamera"
  90. ref="userCameraVideo"
  91. autoplay
  92. playsinline
  93. muted
  94. class="user-camera-video"
  95. :controls="false">
  96. </video>
  97. </div>
  98. <!-- 字幕/文本覆盖区域 -->
  99. <!-- <div class="subtitle-overlay" v-if="assistantResponse">
  100. {{ assistantResponse }}
  101. </div> -->
  102. </div>
  103. <!-- 加载状态 -->
  104. <div v-if="loading" class="loading">加载中...</div>
  105. <!-- 控制面板(可选,可以隐藏) -->
  106. <!-- 响应数据(可以设为隐藏,仅用于调试) -->
  107. <div v-if="showDebugInfo" class="response-container">
  108. <div v-if="assistantResponse" class="response-item">
  109. <div class="response-content">
  110. <span>助手回复: {{ assistantResponse }}</span>
  111. </div>
  112. </div>
  113. <div v-if="audioTranscript" class="response-item">
  114. <div class="response-content">
  115. <span>音频转写: {{ audioTranscript }}</span>
  116. </div>
  117. </div>
  118. <div v-for="(item, index) in processedResponses" :key="index" class="response-item">
  119. <div class="response-content">
  120. <span v-if="item.role">角色: {{ item.role }}</span>
  121. <span v-if="item.transcript">文本: {{ item.transcript }}</span>
  122. </div>
  123. </div>
  124. </div>
  125. <!-- 添加停止录制按钮 -->
  126. <div class="stop-recording-button-container" v-if="showStopRecordingButton">
  127. <button class="stop-recording-button" @click="stopRecordingAnswer">
  128. 完成作答
  129. </button>
  130. </div>
  131. <!-- 添加录制指示器 -->
  132. <div class="recording-indicator" v-if="isRecording">
  133. <!-- 替换原有的progress组件为自定义环形进度条 -->
  134. <div class="circle-progress-container">
  135. <div class="circle-progress" :style="{
  136. background: `conic-gradient(${progressColor} ${progressPercent}%, ${progressBgColor} 0%)`
  137. }">
  138. <div class="circle-progress-inner">
  139. <span class="progress-text">{{ recordingTimeDisplay }}</span><!-- -->
  140. </div>
  141. </div>
  142. </div>
  143. <!-- <span class="timer-text">{{ recordingTimeDisplay || '00:00 / 05:00' }}</span> -->
  144. </div>
  145. <!-- 添加开始回答按钮 -->
  146. <div class="start-recording-button-container" v-if="showStartRecordingButton">
  147. <button class="start-recording-button" @click="handleStartRecordingClick">
  148. 开始作答
  149. </button>
  150. </div>
  151. <!-- 添加重试上传按钮 -->
  152. <div class="retry-button-container" v-if="showRetryButton">
  153. <button class="retry-button" @click="retryVideoUpload">
  154. 重新上传
  155. </button>
  156. </div>
  157. <!-- 在模板部分添加录制时长显示 -->
  158. <!-- <div class="recording-timer" v-if="isRecording">
  159. <span class="timer-text">{{ recordingTimeDisplay || '00:00' }}</span>
  160. </div> -->
  161. <!-- 添加上传状态指示器 -->
  162. <!-- <div class="upload-status-indicator" v-if="showUploadStatus && uploadStatusText">
  163. <div class="upload-status-content">
  164. <div class="upload-status-icon" :class="{'uploading': isUploading}"></div>
  165. <span class="upload-status-text">{{ uploadStatusText }}</span>
  166. </div>
  167. </div> -->
  168. <!-- 修改录制时长显示 -->
  169. <!-- <div class="recording-timer" v-if="isRecording">
  170. <span class="timer-text">{{ recordingTimeDisplay || '00:00 / 05:00' }}</span>
  171. <span class="remaining-time" :class="{'warning': remainingTime <= 10}">
  172. 剩余: {{ formatTime(remainingTime) }}
  173. </span>
  174. </div> -->
  175. <!-- 在模板部分添加倒计时蒙层 -->
  176. <div class="countdown-overlay" v-if="showCountdown">
  177. <div class="countdown-content">
  178. <div class="countdown-number">{{ countdownValue }}</div>
  179. <div class="countdown-text">准备开始回答</div>
  180. </div>
  181. </div>
  182. <!-- 添加重新录制按钮 -->
  183. <div class="rerecord-button-container" v-if="showRerecordButton">
  184. <button class="rerecord-button" @click="handleRerecordButtonClick">
  185. 重新作答
  186. </button>
  187. </div>
  188. </div>
  189. </template>
  190. <script>
  191. import { apiBaseUrl, personDetectionWsUrl } from '@/common/config.js';
  192. export default {
  193. name: 'IdentityVerify',
  194. data() {
  195. return {
  196. followUpQuestion: '', // 追问问题
  197. followUpAudioUrl: '', // 追问音频URL
  198. audioContext: null, // 音频上下文
  199. followUpQuestions: [], // 追问问题列表
  200. isWaitingForAnswer: false, // 添加新的状态来控制是否在等待用户回答
  201. currentFollowUpIndex: -1, // 当前追问问题索引
  202. showSubtitleText: false, // 是否显示字幕
  203. subtitleText: '', // 字幕文本
  204. parentQuestion: '', // 父问题文本
  205. isFollowUpQuestion: false, // 是否是追问问题
  206. loading: false,
  207. responses: [],
  208. processedResponses: [],
  209. assistantResponse: '',
  210. audioTranscript: '',
  211. videoPlaying: false,
  212. showDebugInfo: false, // 设置为true可以显示调试信息
  213. videoUrl: '', // 修改为空字符串,将通过API获取
  214. showReplayButton: false,
  215. cameraStream: null, // 存储摄像头流
  216. cameraError: null, // 存储摄像头错误信息
  217. useMiniProgramCameraComponent: false, // 添加小程序相机组件标志
  218. cameraContext: null, // 添加相机上下文
  219. currentSubtitle: '',
  220. currentTranslation: '', // 添加翻译文本
  221. subtitles: [], // 修改为空数组,将通过API获取
  222. // 移除硬编码的字幕数组
  223. // secondVideoSubtitles: [...],
  224. // thirdVideoSubtitles: [...],
  225. // 等等...
  226. showAnswerButton: false, // 控制答题按钮显示
  227. currentVideoIndex: 0, // 当前播放的视频索引
  228. videoList: [], // 修改为空数组,将通过API获取
  229. // 其他属性保持不变...
  230. questions: [], // 添加新属性存储API返回的问题数据
  231. introVideoUrl: (() => {
  232. const DEFAULT_VIDEO_URL = 'https://data.qicai321.com/minlong/ee4d9cce-c3d5-4350-8c6e-684283827897.mp4';
  233. try {
  234. const configStr = uni.getStorageSync('configData');
  235. if (!configStr) return DEFAULT_VIDEO_URL;
  236. const config = JSON.parse(configStr);
  237. return config.digital_human_opening_video_url || DEFAULT_VIDEO_URL;
  238. } catch (error) {
  239. console.warn('解析配置数据失败:', error);
  240. return DEFAULT_VIDEO_URL;
  241. }
  242. })(),//'https://data.qicai321.com/minlong/ee4d9cce-c3d5-4350-8c6e-684283827897.mp4', // 保留介绍视频
  243. isRecording: false,
  244. recordingTimer: null,
  245. showStopRecordingButton: false,
  246. mediaRecorder: null,
  247. recordedChunks: [],
  248. recorder: null,
  249. lastUploadedVideoUrl: '',
  250. showStartRecordingButton: false,
  251. showRetryButton: false, // 控制重试按钮显示
  252. lastVideoToRetry: null, // 存储上次失败的视频URL,用于重试
  253. recordingStartTime: null, // 录制开始时间
  254. recordingTimerCount: 0, // 录制计时器计数
  255. recordingTimeDisplay: '00:00', // 格式化的录制时间显示
  256. // 添加上传队列相关数据
  257. uploadQueue: [], // 存储待上传的视频
  258. backgroundUploadQueue: [], // 存储后台上传的视频
  259. isUploading: false, // 标记是否正在上传
  260. uploadProgress: {}, // 存储每个视频的上传进度
  261. uploadStatus: {}, // 存储每个视频的上传状态
  262. showUploadStatus: false, // 是否显示上传状态指示器
  263. uploadStatusText: '', // 上传状态文本
  264. mediaRecorderTimeout: null, // 用于存储MediaRecorder的超时机制
  265. maxRecordingTime: 300, // 最大录制时间(秒)- 从60秒改为300秒(5分钟)
  266. remainingTime: 300, // 剩余录制时间(秒)- 从60秒改为300秒
  267. countdownValue: 10, // 倒计时数值
  268. showCountdown: false, // 是否显示倒计时蒙层
  269. countdownTimer: null,
  270. showGif: false, // 控制是否显示GIF
  271. gifUrl: '', // GIF图片的URL
  272. globalSocketTask: null, // 添加全局 WebSocket 连接对象
  273. lowScoreVideoUrl: (() => {
  274. const DEFAULT_VIDEO_URL = 'https://data.qicai321.com/minlong/latentsync/0530e7f5-1957-422d-8f34-ba4a92608081_result.mp4';
  275. try {
  276. const configStr = uni.getStorageSync('configData');
  277. if (!configStr) return DEFAULT_VIDEO_URL;
  278. const config = JSON.parse(configStr);
  279. return config.digital_human?.middle_video_url || DEFAULT_VIDEO_URL;
  280. } catch (error) {
  281. console.warn('解析配置数据失败:', error);
  282. return DEFAULT_VIDEO_URL;
  283. }
  284. })(),//'https://data.qicai321.com/minlong/latentsync/0530e7f5-1957-422d-8f34-ba4a92608081_result.mp4', // 低分提示视频URL
  285. showRerecordButton: false, // 控制重新录制按钮显示
  286. isPlayingLowScoreVideo: false, // 标记是否正在播放低分提示视频
  287. lowScoreVideoSubtitles: [
  288. {
  289. startTime: 0,
  290. endTime: 10, // 假设视频长度为10秒,可根据实际情况调整
  291. text: '我未听清楚您在说什么,请您再说一遍!'
  292. }
  293. ], // 用于存储低分提示视频的字幕
  294. retryCount: 0, // 添加重试次数计数器
  295. maxRetryAttempts: 2, // 最大重试次数限制
  296. needPlayLowScoreVideo: false, // 是否需要播放低分视频
  297. finalRecordingDuration: 0, // 最终录制时长
  298. historyTime: 0, // 添加历史时间记录
  299. followUpQuestions: [], // 存储追问问题数据
  300. currentParentQuestionId: null, // 当前父问题ID
  301. hasPlayedFollowUp: {}, // 记录已播放的追问,格式: {questionId: true}
  302. isFollowUpQuestion: false, // 标记当前是否正在播放追问问题
  303. currentFollowUpQuestion: null, // 添加当前追问问题的完整信息
  304. lastQuestionWasFollowUp: false,
  305. lastFollowUpQuestionId: null,
  306. // 追问次数控制
  307. defaultFollowUpLimit: 1, // 默认每个主题目最多2次追问
  308. followUpLimitMap: {}, // { parentJobPositionQuestionId: limit }
  309. followUpAskedCountMap: {}, // { parentJobPositionQuestionId: askedCount }
  310. followUpRequestInFlight: {}, // { parentJobPositionQuestionId: boolean }
  311. lastUpdateTime: Date.now(), // 添加最后更新时间戳
  312. subtitleMap: {}, // 用于存储字幕和翻译的映射
  313. progressPercent: 0, // 录制进度百分比
  314. progressColor: '#05dc8b', // 进度条颜色
  315. progressBgColor: 'rgba(0, 0, 0,0.3)', // 进度条背景色
  316. parentQuestion: '', // 添加父问题存储
  317. screenCaptureCount: 0, // 添加截屏次数记录
  318. personDetectionSocket: null, // WebSocket对象
  319. personDetectionInterval: null, // 定时器对象
  320. showCameraWarning: false, // 添加新的数据属性
  321. showPageWarning: false, // 添加新的数据属性
  322. followUpQuestion: '', // 追问问题
  323. followUpAudioUrl: '', // 追问音频URL
  324. audioContext: null, // 音频上下文
  325. followUpQuestions: [], // 追问问题列表
  326. currentFollowUpIndex: -1, // 当前追问问题索引
  327. showSubtitleText: false, // 是否显示字幕
  328. subtitleText: '', // 字幕文本
  329. isAudioPlaying: false,
  330. isWaitingForAnswer: false, // 添加新的状态来控制是否在等待用户回答
  331. currentRecordingDuration: 0, // 添加当前录制时长
  332. parentJobPositionQuestionId: null, // 添加父问题的job_position_question_id
  333. isFollowUpMode: false, // 是否处于追问模式
  334. mainQuestionIndex: 0, // 当前主问题的索引
  335. isVideoSwitching: false, // 添加视频切换状态锁
  336. originalQuestionSubtitle: null, // 保存原始字幕信息
  337. isThinking: false, // 面试官思考中状态
  338. thinkingTimer: null, // 思考计时器
  339. questionRetryMap: {}, // 用于跟踪每个问题的重试次数
  340. maxQuestionRetries: 2, // 每个问题最大重试次数
  341. statusBarHeight: 0
  342. }
  343. },
  344. onLoad() {
  345. // 获取状态栏高度
  346. this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight || 0
  347. },
  348. mounted() {
  349. this.fetchQuestions();
  350. //this.fetchFollowUpQuestions();
  351. this.checkAudioPermission();
  352. this.initCamera();
  353. this.checkIOSCameraRecordPermission();
  354. this.checkAndFixRenderingIssues();
  355. setTimeout(() => {
  356. if (this.cameraStream && !this.useMiniProgramCameraComponent) {
  357. this.testAudioInput();
  358. }
  359. }, 3e3);
  360. this.historyTime = 0;
  361. uni.setKeepScreenOn({
  362. keepScreenOn: true
  363. });
  364. // 添加截屏监听
  365. uni.onUserCaptureScreen(() => {
  366. console.log('User captured screen');
  367. this.screenCaptureCount++;
  368. if (this.screenCaptureCount === 1) {
  369. uni.showModal({
  370. title: 'Warning',
  371. content: '检测到屏幕截图。如果你再次捕捉屏幕,你的面试将无效.',
  372. showCancel: false,
  373. confirmText: 'OK'
  374. });
  375. } else if (this.screenCaptureCount >= 2) {
  376. uni.showModal({
  377. title: 'Interview Invalid',
  378. content: '由于多次屏幕截图,您的面试已无效。请联系招聘人员寻求帮助.',
  379. showCancel: false,
  380. confirmText: 'OK',
  381. success: () => {
  382. this.invalidateInterview();
  383. }
  384. });
  385. }
  386. });
  387. const systemInfo = uni.getSystemInfoSync();
  388. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
  389. console.log('isMiniProgram', isMiniProgram);
  390. if (isMiniProgram) {
  391. this.initPersonDetectionWebSocket();
  392. }
  393. },
  394. beforeDestroy() {
  395. // 移除截屏监听
  396. uni.offUserCaptureScreen();
  397. this.cleanupPersonDetectionWebSocket();
  398. },
  399. methods: {
  400. // ===== 追问次数控制:工具方法 =====
  401. getFollowUpLimit(parentId) {
  402. if (!parentId) return this.defaultFollowUpLimit;
  403. return this.followUpLimitMap[parentId] || this.defaultFollowUpLimit;
  404. },
  405. setFollowUpLimit(parentId, limit) {
  406. if (!parentId) return;
  407. const parsed = parseInt(limit);
  408. this.followUpLimitMap[parentId] = Number.isFinite(parsed) && parsed > 0 ? parsed : this.defaultFollowUpLimit;
  409. },
  410. resetFollowUpAskedCount(parentId) {
  411. if (!parentId) return;
  412. this.followUpAskedCountMap[parentId] = 0;
  413. },
  414. incrementFollowUpCount(parentId) {
  415. if (!parentId) return;
  416. const current = this.followUpAskedCountMap[parentId] || 0;
  417. this.followUpAskedCountMap[parentId] = current + 1;
  418. },
  419. canAskMoreFollowUps(parentId) {
  420. if (!parentId) return false;
  421. const asked = this.followUpAskedCountMap[parentId] || 0;
  422. const limit = this.getFollowUpLimit(parentId);
  423. return asked < limit;
  424. },
  425. async maybeRequestNextFollowUp(parentId) {
  426. if (!parentId) {
  427. this.proceedToNextQuestion();
  428. return;
  429. }
  430. if (this.canAskMoreFollowUps(parentId)) {
  431. // 避免重复触发并发请求
  432. if (this.followUpRequestInFlight[parentId]) {
  433. console.log('已有追问请求进行中,跳过重复触发');
  434. return;
  435. }
  436. // 交由 callInterviewInteraction 统一处理并发标记
  437. const ok = await this.callInterviewInteraction(parentId);
  438. if (!ok) {
  439. console.log('未获取到下一条追问或调用失败,进入下一题');
  440. this.isFollowUpMode = false;
  441. this.isFollowUpQuestion = false;
  442. this.currentFollowUpQuestion = null;
  443. this.proceedToNextQuestion();
  444. }
  445. } else {
  446. // 已达上限,进入下一题
  447. this.isFollowUpMode = false;
  448. this.isFollowUpQuestion = false;
  449. this.currentFollowUpQuestion = null;
  450. this.proceedToNextQuestion();
  451. }
  452. },
  453. // 处理音频播放完成
  454. handleAudioEnd() {
  455. console.log('音频播放完成');
  456. // 设置等待回答状态
  457. this.isWaitingForAnswer = true;
  458. // 显示开始作答按钮
  459. this.showStartRecordingButton = true;
  460. // 延迟一下再开始倒计时,避免重复触发
  461. setTimeout(() => {
  462. // 开始倒计时
  463. this.startCountdown();
  464. }, 100);
  465. },
  466. // 开始倒计时
  467. startCountdown() {
  468. this.showCountdown = true;
  469. this.countdownValue = 5; // 重置倒计时值
  470. this.countdownTimer = setInterval(() => {
  471. this.countdownValue--;
  472. if (this.countdownValue <= 0) {
  473. // 倒计时结束,清除定时器
  474. this.clearCountdown();
  475. // 隐藏开始作答按钮
  476. this.showStartRecordingButton = false;
  477. // 开始录制
  478. this.startRecordingAnswer();
  479. }
  480. }, 1000);
  481. },
  482. // 清除倒计时
  483. clearCountdown() {
  484. if (this.countdownTimer) {
  485. clearInterval(this.countdownTimer);
  486. this.countdownTimer = null;
  487. }
  488. this.showCountdown = false;
  489. },
  490. // 处理追问问题
  491. async handleFollowUpQuestion(questionData) {
  492. console.log('处理追问:', questionData);
  493. this.enterFollowUpMode();
  494. console.log('处理追问问题数据:', questionData);
  495. // 检查数据完整性
  496. if (!questionData || !questionData.follow_up_voice_url || !questionData.follow_up_question) {
  497. console.error('追问数据不完整:', questionData);
  498. uni.showToast({
  499. title: '获取追问数据失败',
  500. icon: 'none'
  501. });
  502. return;
  503. }
  504. // 保存父问题
  505. this.parentQuestion = questionData.original_question || '';
  506. // 确保音频URL正确
  507. let audioUrl = '';
  508. if (questionData.follow_up_voice_url.direct_url) {
  509. audioUrl = questionData.follow_up_voice_url.direct_url;
  510. } else if (questionData.follow_up_voice_url.file_url) {
  511. audioUrl = questionData.follow_up_voice_url.file_url;
  512. }
  513. // 确保音频URL是完整的
  514. if (!audioUrl.startsWith('http')) {
  515. audioUrl = apiBaseUrl + audioUrl;
  516. }
  517. console.log('处理后的音频URL:', audioUrl);
  518. // 创建追问问题对象
  519. const followUpQuestionObj = {
  520. id: Date.now(),
  521. question: questionData.follow_up_question.trim(), // 去除可能的空白字符
  522. audioUrl: audioUrl,
  523. originalQuestion: questionData.original_question,
  524. sessionId: questionData.session_id
  525. };
  526. console.log('创建的追问问题对象:', followUpQuestionObj);
  527. // 添加到追问问题列表
  528. this.followUpQuestions.push(followUpQuestionObj);
  529. this.currentFollowUpIndex = this.followUpQuestions.length - 1;
  530. // 更新当前追问问题
  531. this.followUpQuestion = followUpQuestionObj.question;
  532. this.followUpAudioUrl = followUpQuestionObj.audioUrl;
  533. // 标记当前是追问问题
  534. this.isFollowUpQuestion = true;
  535. this.currentFollowUpQuestion = followUpQuestionObj;
  536. // 显示字幕
  537. this.showSubtitle(followUpQuestionObj.question, true);
  538. // 等待音频播放完成
  539. try {
  540. await this.playFollowUpAudio();
  541. console.log('音频播放完成,准备录制回答');
  542. // 开始准备录制回答
  543. this.prepareToAnswer(true, followUpQuestionObj);
  544. } catch (error) {
  545. console.error('音频播放失败:', error);
  546. // 即使音频播放失败,也继续准备录制回答
  547. this.prepareToAnswer(true, followUpQuestionObj);
  548. }
  549. },
  550. // 准备回答问题
  551. prepareToAnswer(isFollowUp = false, questionData = null) {
  552. console.log('准备回答问题:', { isFollowUp, questionData });
  553. // 重置录制状态
  554. this.isRecording = false;
  555. this.recordedTime = 0;
  556. this.showStopRecordingButton = false;
  557. // 设置当前问题状态
  558. if (isFollowUp && questionData) {
  559. this.currentFollowUpQuestion = questionData;
  560. this.isFollowUpQuestion = true;
  561. }
  562. // 设置等待回答状态
  563. this.isWaitingForAnswer = true;
  564. // 显示开始回答按钮和倒计时
  565. this.handleAudioEnd();
  566. },
  567. // 调用面试互动接口
  568. async callInterviewInteraction(questionId, retryCount = 0, maxRetries = 3) {
  569. // 防重入:同一父问题并发保护
  570. if (questionId && this.followUpRequestInFlight[questionId]) {
  571. console.log('追问请求已在进行中,跳过本次调用');
  572. return false;
  573. }
  574. if (questionId) {
  575. this.followUpRequestInFlight[questionId] = true;
  576. }
  577. const userInfo = JSON.parse(uni.getStorageSync('userInfo'));
  578. const appId = uni.getStorageSync('appId');
  579. const positionConfigId = JSON.parse(uni.getStorageSync('configData')).id;
  580. try {
  581. // 显示思考中loading
  582. this.showThinkingLoading();
  583. console.log('开始调用面试互动接口', { questionId, appId });
  584. const res = await uni.request({
  585. url: `${apiBaseUrl}/api/voice_interview_interaction/`,
  586. method: 'POST',
  587. data: {
  588. tenant_id: userInfo.tenant_id || 1,
  589. question_id: questionId,
  590. position_config_id: positionConfigId,
  591. application_id: appId
  592. },
  593. header: {
  594. 'content-type': 'application/json'
  595. }
  596. });
  597. console.log('面试互动接口返回数据:', res);
  598. // 处理4000状态码(视频未转写完成)的情况
  599. if (res.statusCode === 400) {
  600. if (retryCount < maxRetries) {
  601. console.log(`视频转写未完成,${retryCount + 1}次重试中...`);
  602. // 等待3秒后重试
  603. await new Promise(resolve => setTimeout(resolve, 3000));
  604. return this.callInterviewInteraction(questionId, retryCount + 1, maxRetries);
  605. } else {
  606. console.log('达到最大重试次数,视频转写仍未完成');
  607. uni.showToast({
  608. title: '视频转写处理中,请稍后再试',
  609. icon: 'none',
  610. duration: 2000
  611. });
  612. return false;
  613. }
  614. }
  615. if (res.data.success) {
  616. // 成功获取到一条追问,计数 +1(表示“已请求”这条追问)
  617. if (questionId) {
  618. this.incrementFollowUpCount(questionId);
  619. }
  620. // 处理本次追问(即便已达到上限,也应该播放本次追问)
  621. await this.handleFollowUpQuestion(res.data);
  622. this.hideThinkingLoading();
  623. return true;
  624. } else {
  625. console.error('面试互动接口返回错误:', res.data);
  626. this.hideThinkingLoading();
  627. return false;
  628. }
  629. } catch (error) {
  630. console.error('调用面试互动接口失败:', error);
  631. this.hideThinkingLoading();
  632. return false;
  633. } finally {
  634. if (questionId) {
  635. this.followUpRequestInFlight[questionId] = false;
  636. }
  637. }
  638. },
  639. // 播放追问音频
  640. async playFollowUpAudio() {
  641. return new Promise((resolve, reject) => {
  642. console.log('开始播放追问音频, URL:', this.followUpAudioUrl);
  643. // 检查音频URL
  644. if (!this.followUpAudioUrl) {
  645. console.error('没有音频URL');
  646. /* uni.showToast({
  647. title: '音频URL无效',
  648. icon: 'none'
  649. }); */
  650. reject(new Error('没有音频URL'));
  651. return;
  652. }
  653. // 显示加载提示
  654. uni.showLoading({
  655. title: '思考中...'
  656. });
  657. // 停止并销毁之前的音频实例
  658. this.stopAndDestroyAudio();
  659. try {
  660. // 创建新的音频上下文
  661. const innerAudioContext = uni.createInnerAudioContext();
  662. this.audioContext = innerAudioContext;
  663. // 设置音频属性
  664. innerAudioContext.autoplay = true;
  665. innerAudioContext.obeyMuteSwitch = false;
  666. innerAudioContext.volume = 1.0;
  667. // 监听音频加载状态
  668. innerAudioContext.onCanplay(() => {
  669. console.log('音频可以播放');
  670. uni.hideLoading();
  671. this.isAudioPlaying = true;
  672. /* uni.showToast({
  673. title: '正在播放追问',
  674. icon: 'none',
  675. duration: 2000
  676. }); */
  677. });
  678. // 监听音频播放完成
  679. innerAudioContext.onEnded(() => {
  680. console.log('追问音频播放完成');
  681. this.isAudioPlaying = false;
  682. resolve();
  683. // 延迟清理资源,确保不会影响播放完成的回调
  684. setTimeout(() => {
  685. this.stopAndDestroyAudio();
  686. // 音频播放完成后,自动准备录制回答
  687. this.prepareToAnswer(true, this.currentFollowUpQuestion);
  688. }, 100);
  689. });
  690. // 监听音频播放错误
  691. innerAudioContext.onError((res) => {
  692. console.error('音频播放错误:', res);
  693. this.isAudioPlaying = false;
  694. uni.hideLoading();
  695. /* uni.showToast({
  696. title: '音频播放失败',
  697. icon: 'none'
  698. }); */
  699. reject(res);
  700. this.stopAndDestroyAudio();
  701. });
  702. // 设置音频源
  703. console.log('设置音频源:', this.followUpAudioUrl);
  704. innerAudioContext.src = this.followUpAudioUrl;
  705. } catch (error) {
  706. console.error('创建或播放音频失败:', error);
  707. this.isAudioPlaying = false;
  708. uni.hideLoading();
  709. /* uni.showToast({
  710. title: '音频播放失败',
  711. icon: 'none'
  712. }); */
  713. this.stopAndDestroyAudio();
  714. reject(error);
  715. }
  716. });
  717. },
  718. // 停止并销毁音频
  719. stopAndDestroyAudio() {
  720. if (!this.audioContext) {
  721. return;
  722. }
  723. const ctx = this.audioContext;
  724. this.audioContext = null; // 先清除引用
  725. try {
  726. if (this.isAudioPlaying) {
  727. ctx.stop();
  728. }
  729. } catch (error) {
  730. console.error('停止音频播放失败:', error);
  731. }
  732. try {
  733. ctx.destroy();
  734. } catch (error) {
  735. console.error('销毁音频实例失败:', error);
  736. }
  737. this.isAudioPlaying = false;
  738. },
  739. // 绑定音频事件
  740. bindAudioEvents(audioContext, resolve, reject) {
  741. // 监听音频加载状态
  742. audioContext.onCanplay(() => {
  743. console.log('音频可以播放');
  744. /* uni.showToast({
  745. title: '正在播放追问',
  746. icon: 'none',
  747. duration: 2000
  748. }); */
  749. });
  750. // 监听播放进度
  751. audioContext.onTimeUpdate(() => {
  752. console.log('音频播放进度:', audioContext.currentTime);
  753. });
  754. // 监听音频播放完成
  755. audioContext.onEnded(() => {
  756. console.log('追问音频播放完成');
  757. this.cleanupAudioContext();
  758. resolve();
  759. });
  760. // 监听音频播放错误
  761. audioContext.onError((res) => {
  762. console.error('音频播放错误:', res);
  763. /* uni.showToast({
  764. title: '音频播放失败',
  765. icon: 'none'
  766. }); */
  767. this.cleanupAudioContext();
  768. reject(res);
  769. });
  770. },
  771. // 修改准备回答方法
  772. prepareToAnswer(isFollowUp = false, questionData = null) {
  773. // 重置录制状态
  774. this.isRecording = false;
  775. this.recordedTime = 0;
  776. this.showStopRecordingButton = false;
  777. // 设置当前问题状态
  778. if (isFollowUp && questionData) {
  779. this.currentFollowUpQuestion = questionData;
  780. this.isFollowUpQuestion = true;
  781. }
  782. // 设置等待回答状态
  783. this.isWaitingForAnswer = true;
  784. // 显示开始回答按钮和倒计时
  785. this.handleAudioEnd();
  786. },
  787. // 初始化相机
  788. async initCamera() {
  789. // 检查平台
  790. const systemInfo = uni.getSystemInfoSync();
  791. // 判断是否在小程序环境中
  792. const isMiniProgram = systemInfo.uniPlatform === 'mp-weixin' ||
  793. systemInfo.uniPlatform === 'mp-alipay' ||
  794. systemInfo.uniPlatform === 'mp-baidu';
  795. if (isMiniProgram) {
  796. // 小程序环境使用小程序的相机API
  797. this.useMiniProgramCameraComponent = true;
  798. // 创建相机上下文
  799. this.cameraContext = uni.createCameraContext();
  800. // 确保已获取录音和相机权限
  801. uni.getSetting({
  802. success: (res) => {
  803. // 检查录音权限
  804. if (!res.authSetting['scope.record']) {
  805. uni.authorize({
  806. scope: 'scope.record',
  807. success: () => {
  808. console.log('录音权限已获取');
  809. },
  810. fail: (err) => {
  811. console.error('录音权限获取失败:', err);
  812. this.showPermissionDialog('录音');
  813. }
  814. });
  815. }
  816. // 检查相机权限
  817. if (!res.authSetting['scope.camera']) {
  818. uni.authorize({
  819. scope: 'scope.camera',
  820. success: () => {
  821. console.log('相机权限已获取');
  822. },
  823. fail: (err) => {
  824. console.error('相机权限获取失败:', err);
  825. this.showPermissionDialog('相机');
  826. }
  827. });
  828. }
  829. // 在iOS上,可能需要额外的权限检查
  830. const systemInfo = uni.getSystemInfoSync();
  831. if (systemInfo.platform === 'ios') {
  832. // 在iOS上,不要使用无效的权限范围
  833. // 移除以下代码块
  834. /*
  835. if (!res.authSetting['scope.camera.record']) {
  836. uni.authorize({
  837. scope: 'scope.camera.record',
  838. success: () => {
  839. console.log('相机录制权限已获取');
  840. },
  841. fail: (err) => {
  842. console.error('相机录制权限获取失败:', err);
  843. this.showPermissionDialog('相机录制');
  844. }
  845. });
  846. }
  847. */
  848. // 确保同时获取了相机和录音权限
  849. if (!res.authSetting['scope.camera'] || !res.authSetting['scope.record']) {
  850. console.log('iOS需要同时获取相机和录音权限');
  851. }
  852. }
  853. }
  854. });
  855. } else {
  856. // H5/App环境使用浏览器的API
  857. try {
  858. // 请求摄像头和麦克风权限并获取媒体流,添加更多约束
  859. const constraints = {
  860. audio: {
  861. echoCancellation: true,
  862. noiseSuppression: true,
  863. autoGainControl: true
  864. },
  865. video: {
  866. width: { ideal: 640, max: 1280 }, // 控制视频宽度
  867. height: { ideal: 480, max: 720 }, // 控制视频高度
  868. frameRate: { ideal: 15, max: 24 }, // 控制帧率
  869. facingMode: 'user'
  870. }
  871. };
  872. const stream = await navigator.mediaDevices.getUserMedia(constraints);
  873. // 保存流以便后续使用
  874. this.cameraStream = stream;
  875. // 检查音频轨道
  876. const audioTracks = stream.getAudioTracks();
  877. console.log('音频轨道数量:', audioTracks.length);
  878. if (audioTracks.length > 0) {
  879. console.log('音频轨道已获取:', audioTracks[0].label);
  880. // 确保音频轨道已启用
  881. audioTracks[0].enabled = true;
  882. } else {
  883. console.warn('未检测到音频轨道,尝试单独获取音频');
  884. this.tryGetAudioOnly();
  885. }
  886. // 将流设置到视频元素
  887. const videoElement = this.$refs.userCameraVideo;
  888. if (videoElement) {
  889. videoElement.srcObject = stream;
  890. videoElement.muted = true; // 避免回声,但仍然录制声音
  891. }
  892. } catch (error) {
  893. console.error('获取摄像头失败:', error);
  894. this.cameraError = error.message || '无法访问摄像头';
  895. // 显示错误提示
  896. uni.showToast({
  897. title: '无法访问摄像头,请检查权限设置',
  898. icon: 'none'
  899. });
  900. }
  901. }
  902. },
  903. // 停止用户摄像头
  904. stopUserCamera() {
  905. if (this.cameraStream) {
  906. // 停止所有轨道
  907. this.cameraStream.getTracks().forEach(track => {
  908. track.stop();
  909. });
  910. this.cameraStream = null;
  911. }
  912. },
  913. async fetchData() {
  914. this.loading = true
  915. this.assistantResponse = ''
  916. this.audioTranscript = ''
  917. this.processedResponses = []
  918. // 显示加载提示
  919. uni.showLoading({
  920. title: '面试官思考中...',
  921. mask: true // 添加遮罩,防止用户触摸界面
  922. })
  923. try {
  924. // 使用uni.request代替fetch
  925. const requestTask = uni.request({
  926. url: 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions',
  927. method: 'POST',
  928. header: {
  929. 'Content-Type': 'application/json',
  930. 'Authorization': 'Bearer sk-9e1ec73a7d97493b8613c63f06b6110c'
  931. },
  932. data: {
  933. "model": "qwen-omni-turbo",
  934. "messages": [
  935. {
  936. "role": "user",
  937. "content": [
  938. {
  939. "type": "input_audio",
  940. "input_audio": {
  941. "data": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250211/tixcef/cherry.wav",
  942. "format": "wav"
  943. }
  944. },
  945. {
  946. "type": "text",
  947. "text": "这段音频在说什么"
  948. }
  949. ]
  950. }
  951. ],
  952. "stream":true,
  953. "stream_options":{
  954. "include_usage":true
  955. },
  956. "modalities":["text","audio"],
  957. "audio":{"voice":"Cherry","format":"wav"}
  958. },
  959. success: (res) => {
  960. console.log('请求成功,响应数据:', res.data);
  961. // 检查响应数据是否包含多个JSON对象
  962. if (typeof res.data === 'string' && res.data.includes('data: {')) {
  963. // 处理包含多个JSON对象的情况
  964. const chunks = res.data.split('data: ').filter(chunk => chunk.trim() !== '');
  965. chunks.forEach(chunk => {
  966. this.handleStreamResponse(chunk);
  967. });
  968. } else {
  969. // 处理单个响应对象的情况
  970. this.handleStreamResponse(res.data);
  971. }
  972. // 模拟获取到数字人视频并播放
  973. this.playDigitalHumanVideo();
  974. },
  975. fail: (err) => {
  976. console.error('请求失败:', err);
  977. uni.showToast({
  978. title: '请求失败,请重试',
  979. icon: 'none'
  980. });
  981. },
  982. complete: () => {
  983. this.loading = false;
  984. // 隐藏加载提示
  985. uni.hideLoading();
  986. }
  987. });
  988. } catch (error) {
  989. console.error('获取数据失败:', error);
  990. this.loading = false;
  991. // 隐藏加载提示
  992. uni.hideLoading();
  993. uni.showToast({
  994. title: '系统错误,请重试',
  995. icon: 'none'
  996. });
  997. }
  998. },
  999. handleStreamResponse(data) {
  1000. // 处理流式响应数据
  1001. if (typeof data === 'string') {
  1002. // 处理字符串格式的响应
  1003. if (data === '[DONE]') return;
  1004. try {
  1005. // 移除可能存在的换行符和多余空格
  1006. const cleanData = data.trim();
  1007. // 检查是否是有效的JSON字符串
  1008. if (cleanData.startsWith('{') && cleanData.endsWith('}')) {
  1009. const jsonData = JSON.parse(cleanData);
  1010. this.processStreamChunk(jsonData);
  1011. }
  1012. } catch (e) {
  1013. console.error('解析JSON失败:', e, '原始数据:', data);
  1014. }
  1015. } else {
  1016. // 处理对象格式的响应
  1017. this.processStreamChunk(data);
  1018. }
  1019. },
  1020. processStreamChunk(chunk) {
  1021. if (chunk.choices && chunk.choices.length > 0) {
  1022. const choice = chunk.choices[0];
  1023. // 处理助手回复内容
  1024. if (choice.delta && choice.delta.content) {
  1025. this.assistantResponse += choice.delta.content;
  1026. }
  1027. // 处理音频转写内容
  1028. if (choice.delta && choice.delta.audio && choice.delta.audio.transcript) {
  1029. this.audioTranscript += choice.delta.audio.transcript;
  1030. }
  1031. // 处理角色和音频转写
  1032. if (choice.delta) {
  1033. const result = {};
  1034. if (choice.delta.role) {
  1035. result.role = choice.delta.role;
  1036. }
  1037. if (choice.delta.audio && choice.delta.audio.transcript) {
  1038. result.transcript = choice.delta.audio.transcript;
  1039. }
  1040. if (Object.keys(result).length > 0) {
  1041. this.processedResponses.push(result);
  1042. }
  1043. }
  1044. }
  1045. },
  1046. processResponseData() {
  1047. // 处理返回的数据
  1048. this.processedResponses = this.responses.map(item => {
  1049. const result = {}
  1050. // 处理角色信息
  1051. if (item.delta && item.delta.role) {
  1052. result.role = item.delta.role
  1053. }
  1054. // 处理音频转写文本
  1055. if (item.delta && item.delta.audio && item.delta.audio.transcript) {
  1056. result.transcript = item.delta.audio.transcript
  1057. }
  1058. return result
  1059. }).filter(item => Object.keys(item).length > 0)
  1060. },
  1061. // 播放数字人视频
  1062. playDigitalHumanVideo() {
  1063. // 如果还没有加载问题数据,先获取问题数据
  1064. if (this.videoList.length === 0) {
  1065. this.fetchQuestions();
  1066. return;
  1067. }
  1068. // 设置当前视频
  1069. this.videoUrl = this.videoList[this.currentVideoIndex];
  1070. this.videoPlaying = true;
  1071. // 使用 uni.createVideoContext 来控制视频
  1072. this.$nextTick(() => {
  1073. const videoContext = uni.createVideoContext('myVideo', this);
  1074. if (videoContext) {
  1075. videoContext.play();
  1076. // 设置超时检查,确认视频是否真的在播放
  1077. setTimeout(() => {
  1078. if (this.videoPlaying && this.$refs.videoPlayer) {
  1079. console.log('视频应该正在播放');
  1080. } else {
  1081. console.log('视频可能未成功播放,尝试替代方案');
  1082. this.tryAlternativeVideoPath();
  1083. }
  1084. }, 1000);
  1085. } else {
  1086. console.error('无法创建视频上下文');
  1087. this.tryAlternativeVideoPath();
  1088. }
  1089. });
  1090. },
  1091. // 修改 tryAlternativeVideoPath 方法
  1092. tryAlternativeVideoPath() {
  1093. console.log('尝试使用替代路径');
  1094. // 尝试不同的路径格式
  1095. const alternativePaths = [
  1096. './static/demo.mp4',
  1097. '../static/demo.mp4',
  1098. 'static/demo.mp4',
  1099. '/static/demo.mp4',
  1100. // 添加绝对路径
  1101. `${window.location.origin}/static/demo.mp4`
  1102. ];
  1103. // 获取当前路径索引
  1104. const currentPathIndex = alternativePaths.indexOf(this.videoUrl);
  1105. const nextPathIndex = (currentPathIndex + 1) % alternativePaths.length;
  1106. // 设置下一个路径
  1107. this.videoUrl = alternativePaths[nextPathIndex];
  1108. console.log('尝试新路径:', this.videoUrl);
  1109. this.$nextTick(() => {
  1110. const videoContext = uni.createVideoContext('myVideo', this);
  1111. if (videoContext) {
  1112. videoContext.stop();
  1113. videoContext.play();
  1114. // 检查是否成功播放
  1115. setTimeout(() => {
  1116. if (nextPathIndex === alternativePaths.length - 1 && !this.videoPlaying) {
  1117. console.log('所有路径均失败,尝试使用uni.getVideoInfo检查视频');
  1118. this.checkVideoWithAPI();
  1119. }
  1120. }, 1000);
  1121. }
  1122. });
  1123. },
  1124. // 添加新方法:使用uni API检查视频
  1125. checkVideoWithAPI() {
  1126. // 尝试使用uni.getVideoInfo API检查视频是否可用
  1127. uni.getVideoInfo({
  1128. src: '/static/demo.mp4',
  1129. success: (res) => {
  1130. console.log('视频信息获取成功:', res);
  1131. // 如果能获取到视频信息,再次尝试播放
  1132. this.videoUrl = '/static/demo.mp4';
  1133. this.$nextTick(() => {
  1134. const videoContext = uni.createVideoContext('myVideo', this);
  1135. if (videoContext) {
  1136. videoContext.play();
  1137. }
  1138. });
  1139. },
  1140. fail: (err) => {
  1141. console.error('视频信息获取失败:', err);
  1142. // 最后尝试使用uni.chooseVideo API
  1143. this.fallbackToLocalVideo();
  1144. }
  1145. });
  1146. },
  1147. // 添加新方法:回退到本地视频
  1148. fallbackToLocalVideo() {
  1149. console.log('尝试使用本地视频资源');
  1150. // 检查平台
  1151. const platform = uni.getSystemInfoSync().platform;
  1152. if (platform === 'android' || platform === 'ios') {
  1153. // 移动端可以尝试使用本地资源
  1154. this.videoUrl = platform === 'android' ? 'android.resource://package_name/raw/demo' : 'file:///assets/demo.mp4';
  1155. this.$nextTick(() => {
  1156. const videoContext = uni.createVideoContext('myVideo', this);
  1157. if (videoContext) {
  1158. videoContext.play();
  1159. }
  1160. });
  1161. } else {
  1162. // 最终回退到静态图片
  1163. this.videoPlaying = false;
  1164. uni.showToast({
  1165. title: '视频加载失败,显示静态图片',
  1166. icon: 'none'
  1167. });
  1168. }
  1169. },
  1170. // 修改 handleVideoError 方法
  1171. handleVideoError(e) {
  1172. console.error('视频加载错误:', e);
  1173. // 记录更详细的错误信息
  1174. if (e && e.detail) {
  1175. console.error('详细错误信息:', e.detail);
  1176. }
  1177. // 检查视频文件是否存在
  1178. uni.getFileInfo({
  1179. filePath: this.videoUrl.startsWith('/') ? this.videoUrl.substring(1) : this.videoUrl,
  1180. success: (res) => {
  1181. console.log('文件存在,大小:', res.size);
  1182. // 文件存在但播放失败,可能是格式问题
  1183. this.tryDifferentFormat();
  1184. },
  1185. fail: (err) => {
  1186. console.error('文件不存在或无法访问:', err);
  1187. // 尝试不同路径
  1188. this.tryAlternativeVideoPath();
  1189. }
  1190. });
  1191. // 如果多次尝试后仍然失败,显示错误信息
  1192. uni.showToast({
  1193. title: '视频加载失败,请检查文件是否存在',
  1194. icon: 'none',
  1195. duration: 2000
  1196. });
  1197. },
  1198. // 添加新方法:尝试不同格式
  1199. tryDifferentFormat() {
  1200. console.log('尝试不同的视频格式');
  1201. // 尝试不同的视频格式
  1202. const formats = [
  1203. { ext: 'mp4', mime: 'video/mp4' },
  1204. { ext: 'webm', mime: 'video/webm' },
  1205. { ext: 'ogg', mime: 'video/ogg' },
  1206. { ext: 'mov', mime: 'video/quicktime' }
  1207. ];
  1208. // 获取当前文件名(不含扩展名)
  1209. const currentPath = this.videoUrl;
  1210. const basePath = currentPath.substring(0, currentPath.lastIndexOf('.')) || '/static/demo';
  1211. // 尝试下一个格式
  1212. let nextFormat = formats.find(f => !currentPath.endsWith(f.ext));
  1213. if (nextFormat) {
  1214. this.videoUrl = `${basePath}.${nextFormat.ext}`;
  1215. console.log('尝试新格式:', this.videoUrl);
  1216. this.$nextTick(() => {
  1217. const videoContext = uni.createVideoContext('myVideo', this);
  1218. if (videoContext) {
  1219. videoContext.stop();
  1220. videoContext.play();
  1221. }
  1222. });
  1223. } else {
  1224. // 所有格式都尝试过了,使用内置资源
  1225. this.useBuiltInResource();
  1226. }
  1227. },
  1228. // 添加新方法:使用内置资源
  1229. useBuiltInResource() {
  1230. console.log('尝试使用内置资源');
  1231. // 检查平台
  1232. const platform = uni.getSystemInfoSync().platform;
  1233. // 根据平台选择合适的视频源
  1234. if (platform === 'windows') {
  1235. // Windows平台特定处理
  1236. // 尝试使用相对于应用根目录的路径
  1237. const appRoot = process.env.UNI_INPUT_DIR || '';
  1238. this.videoUrl = `./static/demo.mp4`;
  1239. // 或者尝试使用file://协议
  1240. // this.videoUrl = `file:///${appRoot.replace(/\\/g, '/')}/static/demo.mp4`;
  1241. console.log('Windows平台尝试路径:', this.videoUrl);
  1242. } else if (platform === 'android' || platform === 'ios') {
  1243. // 移动端
  1244. this.useNativeVideo();
  1245. } else {
  1246. // Web平台
  1247. // 尝试使用完整URL
  1248. const baseUrl = window.location.origin;
  1249. this.videoUrl = `${baseUrl}/static/demo.mp4`;
  1250. console.log('Web平台尝试URL:', this.videoUrl);
  1251. }
  1252. this.$nextTick(() => {
  1253. const videoContext = uni.createVideoContext('myVideo', this);
  1254. if (videoContext) {
  1255. videoContext.play();
  1256. }
  1257. });
  1258. },
  1259. // 添加新方法:使用原生视频能力
  1260. useNativeVideo() {
  1261. console.log('尝试使用原生视频能力');
  1262. // 在移动端,可以尝试使用原生视频播放器
  1263. uni.chooseVideo({
  1264. sourceType: ['album'],
  1265. success: (res) => {
  1266. this.videoUrl = res.tempFilePath;
  1267. this.$nextTick(() => {
  1268. const videoContext = uni.createVideoContext('myVideo', this);
  1269. if (videoContext) {
  1270. videoContext.play();
  1271. }
  1272. });
  1273. },
  1274. fail: () => {
  1275. // 如果用户取消选择,回退到静态图片
  1276. this.videoPlaying = false;
  1277. /* uni.showToast({
  1278. title: '无法加载视频,显示静态图片',
  1279. icon: 'none'
  1280. }); */
  1281. }
  1282. });
  1283. },
  1284. // 处理视频结束事件
  1285. handleVideoEnded() {
  1286. console.log('视频播放结束事件触发');
  1287. // 获取视频元素和当前时间
  1288. const videoElement = this.$refs.videoPlayer;
  1289. if (videoElement) {
  1290. const currentTime = videoElement.currentTime || 0;
  1291. const duration = videoElement.duration || 0;
  1292. // 更严格的检查:只有当前时间非常接近视频总时长时才认为是真正结束
  1293. if (duration > 0 && (duration - currentTime > 0.5)) {
  1294. console.log('检测到可能的误触发结束事件,继续播放', currentTime, duration);
  1295. // 继续播放视频
  1296. setTimeout(() => {
  1297. const videoContext = uni.createVideoContext('myVideo', this);
  1298. if (videoContext) {
  1299. // 如果距离结束还很远,回到历史位置
  1300. if (duration - currentTime > 2) {
  1301. videoContext.seek(this.historyTime || 0);
  1302. } else {
  1303. // 如果接近结束但还没完全结束,继续播放
  1304. videoContext.play();
  1305. }
  1306. }
  1307. }, 100);
  1308. return;
  1309. }
  1310. console.log('视频确认结束,当前时间:', currentTime, '总时长:', duration);
  1311. }
  1312. this.videoPlaying = false;
  1313. // 检查是否是低分提示视频
  1314. if (this.isPlayingLowScoreVideo) {
  1315. console.log('低分提示视频播放完成');
  1316. // 检查重试次数
  1317. if (this.retryCount < this.maxRetryAttempts) {
  1318. console.log(`显示重新录制按钮 (重试次数: ${this.retryCount + 1}/${this.maxRetryAttempts})`);
  1319. // 显示重新录制按钮
  1320. this.showRerecordButton = true;
  1321. // 恢复原始问题的字幕
  1322. if (this.isFollowUpQuestion && this.currentFollowUpQuestion) {
  1323. this.currentSubtitle = this.currentFollowUpQuestion.question || this.currentFollowUpQuestion.question;
  1324. } else if (this.originalQuestionSubtitle) {
  1325. this.currentSubtitle = this.originalQuestionSubtitle;
  1326. }
  1327. } else {
  1328. console.log('已达到最大重试次数,继续下一题');
  1329. // 重置重试次数
  1330. this.retryCount = 0;
  1331. // 继续下一个问题
  1332. this.proceedToNextQuestion();
  1333. }
  1334. // 重置标记
  1335. this.isPlayingLowScoreVideo = false;
  1336. this.originalQuestionSubtitle = null;
  1337. return;
  1338. }
  1339. // 检查是否是追问问题视频
  1340. if (this.isFollowUpQuestion) {
  1341. console.log('追问问题视频播放完成');
  1342. // 不重置追问状态,保持显示
  1343. // this.isFollowUpQuestion = false;
  1344. // this.currentFollowUpQuestion = null;
  1345. // 显示"开始回答"按钮,准备回答追问
  1346. this.showStartRecordingButton = true;
  1347. this.startCountdown();
  1348. return;
  1349. }
  1350. // 恢复原有的视频结束处理逻辑
  1351. // 对于所有视频,都显示相应的按钮
  1352. if (this.currentVideoIndex >= 1) {
  1353. // 对于问题视频,显示"开始回答"按钮
  1354. this.showStartRecordingButton = true;
  1355. this.startCountdown();
  1356. } else {
  1357. // 对于介绍视频(第一个视频),显示"开始面试"按钮
  1358. this.showAnswerButton = true;
  1359. }
  1360. // 重置追问状态
  1361. if (this.isFollowUpQuestion) {
  1362. this.isFollowUpQuestion = false;
  1363. this.currentFollowUpQuestion = null;
  1364. }
  1365. },
  1366. // 添加新方法:开始倒计时
  1367. startCountdown() {
  1368. // 先清除可能存在的倒计时
  1369. this.clearCountdown();
  1370. // 显示倒计时蒙层
  1371. this.showCountdown = true;
  1372. this.countdownValue = 10;
  1373. // 开始倒计时
  1374. this.countdownTimer = setInterval(() => {
  1375. if (!this.showStartRecordingButton) {
  1376. // 如果开始回答按钮已经被点击,清除倒计时
  1377. this.clearCountdown();
  1378. return;
  1379. }
  1380. this.countdownValue--;
  1381. if (this.countdownValue <= 0) {
  1382. // 倒计时结束,清除定时器
  1383. this.clearCountdown();
  1384. // 自动开始录制
  1385. this.showStartRecordingButton = false;
  1386. this.startRecordingAnswer();
  1387. }
  1388. }, 1000);
  1389. },
  1390. // 添加新方法:清除倒计时
  1391. clearCountdown() {
  1392. if (this.countdownTimer) {
  1393. clearInterval(this.countdownTimer);
  1394. this.countdownTimer = null;
  1395. }
  1396. this.showCountdown = false;
  1397. },
  1398. // 修改 handleStartRecordingClick 方法,使其可以终止倒计时
  1399. handleStartRecordingClick() {
  1400. // 隐藏"开始回答"按钮
  1401. this.showStartRecordingButton = false;
  1402. // 如果倒计时正在进行,清除倒计时
  1403. this.clearCountdown();
  1404. // 重置等待回答状态
  1405. this.isWaitingForAnswer = false;
  1406. // 直接开始录制
  1407. this.startRecordingAnswer();
  1408. },
  1409. // 修改 stopRecordingAnswer 方法,添加录制时长检查
  1410. stopRecordingAnswer() {
  1411. // 如果倒计时正在进行,先清除倒计时
  1412. this.clearCountdown();
  1413. // 重置等待回答状态
  1414. this.isWaitingForAnswer = false;
  1415. // 检查录制时长
  1416. const recordingDuration = this.getRecordingDuration();
  1417. const minimumDuration = 3; // 最小录制时长(秒),改为3秒
  1418. const lowScoreDuration = 7; // 低分阈值时长(秒),少于7秒视为低分
  1419. // 保存录制时长,用于上传
  1420. this.currentRecordingDuration = recordingDuration;
  1421. if (recordingDuration < minimumDuration) {
  1422. // 录制时间过短,显示提示
  1423. uni.showToast({
  1424. title: '录制时间过短,请至少录制3秒',
  1425. icon: 'none',
  1426. duration: 2000
  1427. });
  1428. // 不执行停止录制逻辑,继续录制
  1429. return;
  1430. }
  1431. // 检查是否需要播放低分视频(录制时间少于7秒)
  1432. if (recordingDuration < lowScoreDuration) {
  1433. console.log(`录制时间 ${recordingDuration} 秒,少于 ${lowScoreDuration} 秒,将播放低分提示视频`);
  1434. // 停止录制但不上传
  1435. this.completeRecordingStop(false);
  1436. // 直接播放低分视频
  1437. this.playLowScoreVideo();
  1438. } else {
  1439. // 录制时长足够,正常停止录制并上传
  1440. this.completeRecordingStop(true);
  1441. this.needPlayLowScoreVideo = false;
  1442. this.recordingTimeDisplay='00:00'
  1443. }
  1444. },
  1445. // 添加新方法:开始录制用户回答
  1446. startRecordingAnswer() {
  1447. console.log('开始录制用户回答');
  1448. this.isRecording = true;
  1449. // 记录录制开始时间
  1450. this.recordingStartTime = Date.now();
  1451. this.recordingTimerCount = 0;
  1452. // 获取当前问题的推荐录制时长
  1453. this.maxRecordingTime = this.getCurrentQuestionRecommendedDuration();
  1454. this.remainingTime = this.maxRecordingTime;
  1455. // 启动计时器,每秒更新计时
  1456. this.recordingTimer = setInterval(() => {
  1457. this.recordingTimerCount++;
  1458. this.remainingTime = Math.max(0, this.maxRecordingTime - this.recordingTimerCount);
  1459. // 更新UI显示录制时长和剩余时间
  1460. this.recordingTimeDisplay = this.formatTime(this.recordingTimerCount)/* +
  1461. ' / ' + this.formatTime(this.maxRecordingTime) */;
  1462. // 更新进度百分比 - 确保值在0-100之间
  1463. this.progressPercent = Math.min((this.recordingTimerCount / this.maxRecordingTime) * 100, 100);
  1464. // 检查是否达到最大录制时间
  1465. if (this.recordingTimerCount >= this.maxRecordingTime) {
  1466. console.log(`已达到最大录制时间(${this.maxRecordingTime}秒),自动停止录制`);
  1467. this.stopRecordingAnswer();
  1468. }
  1469. }, 1000);
  1470. // 显示录制中的提示
  1471. // uni.showLoading({
  1472. // title: '正在录制...',
  1473. // mask: true
  1474. // });
  1475. // 根据平台选择不同的录制方法
  1476. const systemInfo = uni.getSystemInfoSync();
  1477. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
  1478. if (isMiniProgram) {
  1479. // 小程序环境使用小程序的录制API
  1480. this.startMiniProgramRecording();
  1481. } else {
  1482. // H5/App环境使用MediaRecorder API
  1483. this.startBrowserRecording();
  1484. }
  1485. // 显示停止录制按钮
  1486. this.showStopRecordingButton = true;
  1487. },
  1488. // 添加一个新方法:重置相机组件
  1489. resetCamera() {
  1490. console.log('重置相机组件');
  1491. // 先完全移除相机组件
  1492. this.useMiniProgramCameraComponent = false;
  1493. // 释放相机上下文
  1494. if (this.cameraContext) {
  1495. this.cameraContext = null;
  1496. }
  1497. // 延迟后重新创建相机组件
  1498. setTimeout(() => {
  1499. this.useMiniProgramCameraComponent = true;
  1500. // 再次延迟创建相机上下文,确保组件已完全渲染
  1501. setTimeout(() => {
  1502. this.cameraContext = uni.createCameraContext();
  1503. console.log('相机组件已重置');
  1504. }, 500);
  1505. }, 500);
  1506. },
  1507. // 修改 startMiniProgramRecording 方法
  1508. startMiniProgramRecording() {
  1509. console.log('开始小程序录制方法');
  1510. // 获取平台信息
  1511. const systemInfo = uni.getSystemInfoSync();
  1512. const isIOS = systemInfo.platform === 'ios';
  1513. // 在iOS上,先重置相机
  1514. if (isIOS) {
  1515. // 先重置相机组件
  1516. this.resetCamera();
  1517. // 延迟执行录制,给相机组件足够的初始化时间
  1518. setTimeout(() => {
  1519. this.actualStartRecording(isIOS);
  1520. }, 1000);
  1521. } else {
  1522. // Android直接开始
  1523. this.actualStartRecording(isIOS);
  1524. }
  1525. },
  1526. // 添加新方法:实际开始录制
  1527. actualStartRecording(isIOS) {
  1528. if (!this.cameraContext) {
  1529. this.cameraContext = uni.createCameraContext();
  1530. console.log('创建新的相机上下文');
  1531. }
  1532. // 确保有录音权限
  1533. uni.getSetting({
  1534. success: (res) => {
  1535. const hasRecordAuth = res.authSetting['scope.record'];
  1536. const hasCameraAuth = res.authSetting['scope.camera'];
  1537. if (!hasRecordAuth || !hasCameraAuth) {
  1538. console.warn('缺少必要权限,请求权限');
  1539. this.requestMiniProgramPermissions();
  1540. return;
  1541. }
  1542. // 在iOS上,先检查相机状态
  1543. if (isIOS) {
  1544. console.log('iOS: 检查相机状态');
  1545. // 使用最简单的选项,设置最大录制时间为当前问题的推荐时长
  1546. const maxDuration = this.getCurrentQuestionRecommendedDuration() * 1000; // 转换为毫秒
  1547. const options = {
  1548. timeout: maxDuration, // 使用当前问题的推荐时长
  1549. quality: 'low', // 降低质量
  1550. compressed: true,
  1551. success: () => {
  1552. console.log('iOS录制开始成功');
  1553. },
  1554. fail: (err) => {
  1555. console.error('iOS录制失败:', err);
  1556. // 如果失败,尝试使用不同的方法
  1557. this.useAlternativeRecordingMethod();
  1558. }
  1559. };
  1560. try {
  1561. console.log('尝试开始录制');
  1562. this.recorder = this.cameraContext.startRecord(options);
  1563. } catch (e) {
  1564. console.error('开始录制异常:', e);
  1565. this.useAlternativeRecordingMethod();
  1566. }
  1567. } else {
  1568. // Android使用标准选项,设置最大录制时间为当前问题的推荐时长
  1569. const maxDuration = this.getCurrentQuestionRecommendedDuration() * 1000; // 转换为毫秒
  1570. const options = {
  1571. timeout: maxDuration, // 使用当前问题的推荐时长
  1572. quality: 'medium',
  1573. compressed: true,
  1574. success: () => {
  1575. console.log('Android录制开始成功');
  1576. },
  1577. fail: (err) => {
  1578. console.error('Android录制失败:', err);
  1579. uni.showToast({
  1580. title: '录制失败,请检查相机权限',
  1581. icon: 'none'
  1582. });
  1583. this.proceedToNextQuestion();
  1584. }
  1585. };
  1586. this.recorder = this.cameraContext.startRecord(options);
  1587. }
  1588. }
  1589. });
  1590. },
  1591. // 添加新方法:使用替代录制方法
  1592. useAlternativeRecordingMethod() {
  1593. console.log('使用替代录制方法');
  1594. // 在iOS上,可以尝试使用chooseVideo API作为备选
  1595. uni.showActionSheet({
  1596. itemList: ['使用相册中的视频', '跳过此问题'],
  1597. success: (res) => {
  1598. if (res.tapIndex === 0) {
  1599. // 选择相册中的视频
  1600. uni.chooseVideo({
  1601. sourceType: ['album'],
  1602. maxDuration: this.getCurrentQuestionRecommendedDuration(), // 使用当前问题的推荐时长
  1603. camera: 'front',
  1604. success: (res) => {
  1605. console.log('选择视频成功:', res.tempFilePath);
  1606. // 停止录制状态
  1607. this.isRecording = false;
  1608. this.showStopRecordingButton = false;
  1609. // 上传选择的视频
  1610. this.uploadRecordedVideo(res.tempFilePath);
  1611. },
  1612. fail: () => {
  1613. console.log('用户取消选择视频');
  1614. this.proceedToNextQuestion();
  1615. }
  1616. });
  1617. } else {
  1618. // 跳过此问题
  1619. console.log('用户选择跳过问题');
  1620. this.proceedToNextQuestion();
  1621. }
  1622. },
  1623. fail: () => {
  1624. console.log('操作取消');
  1625. this.proceedToNextQuestion();
  1626. }
  1627. });
  1628. },
  1629. // 添加新方法:请求小程序权限
  1630. requestMiniProgramPermissions() {
  1631. // 请求录音权限
  1632. uni.authorize({
  1633. scope: 'scope.record',
  1634. success: () => {
  1635. console.log('录音权限已获取');
  1636. // 请求相机权限
  1637. uni.authorize({
  1638. scope: 'scope.camera',
  1639. success: () => {
  1640. console.log('相机权限已获取');
  1641. // 权限都获取到后,开始录制
  1642. this.startMiniProgramRecording();
  1643. },
  1644. fail: (err) => {
  1645. console.error('相机权限获取失败:', err);
  1646. this.showPermissionDialog('相机');
  1647. }
  1648. });
  1649. },
  1650. fail: (err) => {
  1651. console.error('录音权限获取失败:', err);
  1652. this.showPermissionDialog('录音');
  1653. }
  1654. });
  1655. },
  1656. // 修改浏览器环境下的录制方法
  1657. startBrowserRecording() {
  1658. if (!this.cameraStream) {
  1659. console.error('没有可用的摄像头流');
  1660. /* uni.showToast({
  1661. title: '录制失败,摄像头未就绪',
  1662. icon: 'none'
  1663. }); */
  1664. this.proceedToNextQuestion();
  1665. return;
  1666. }
  1667. try {
  1668. // 检查流中是否包含音频轨道
  1669. const hasAudio = this.cameraStream.getAudioTracks().length > 0;
  1670. if (!hasAudio) {
  1671. console.warn('警告:媒体流中没有音频轨道,尝试重新获取带音频的媒体流');
  1672. // 尝试重新获取带音频的媒体流
  1673. navigator.mediaDevices.getUserMedia({
  1674. audio: {
  1675. echoCancellation: true,
  1676. noiseSuppression: true,
  1677. autoGainControl: true
  1678. },
  1679. video: true
  1680. })
  1681. .then(newStream => {
  1682. // 检查新流是否包含音频轨道
  1683. const audioTracks = newStream.getAudioTracks();
  1684. if (audioTracks.length > 0) {
  1685. console.log('成功获取音频轨道:', audioTracks[0].label);
  1686. // 合并视频和音频轨道
  1687. const videoTrack = this.cameraStream.getVideoTracks()[0];
  1688. const audioTrack = newStream.getAudioTracks()[0];
  1689. // 创建新的媒体流,包含视频和音频轨道
  1690. const combinedStream = new MediaStream();
  1691. if (videoTrack) combinedStream.addTrack(videoTrack);
  1692. if (audioTrack) combinedStream.addTrack(audioTrack);
  1693. this.cameraStream = combinedStream;
  1694. // 更新视频元素的源
  1695. const videoElement = this.$refs.userCameraVideo;
  1696. if (videoElement) {
  1697. videoElement.srcObject = combinedStream;
  1698. videoElement.muted = true; // 避免回声,但仍然录制声音
  1699. }
  1700. // 继续录制过程
  1701. this.setupMediaRecorder(combinedStream);
  1702. } else {
  1703. console.warn('仍然无法获取音频轨道');
  1704. // 使用现有流继续
  1705. this.setupMediaRecorder(this.cameraStream);
  1706. }
  1707. })
  1708. .catch(err => {
  1709. console.error('获取音频失败:', err);
  1710. // 使用现有流继续
  1711. this.setupMediaRecorder(this.cameraStream);
  1712. });
  1713. } else {
  1714. console.log('检测到音频轨道,直接使用');
  1715. // 已有音频轨道,直接使用
  1716. this.setupMediaRecorder(this.cameraStream);
  1717. }
  1718. } catch (error) {
  1719. console.error('浏览器录制失败:', error);
  1720. uni.showToast({
  1721. title: '录制失败,浏览器可能不支持此功能',
  1722. icon: 'none'
  1723. });
  1724. this.proceedToNextQuestion();
  1725. }
  1726. },
  1727. // 修改 setupMediaRecorder 方法
  1728. setupMediaRecorder(stream) {
  1729. // 检查流中的轨道
  1730. const videoTracks = stream.getVideoTracks();
  1731. const audioTracks = stream.getAudioTracks();
  1732. console.log('设置MediaRecorder - 视频轨道:', videoTracks.length, '音频轨道:', audioTracks.length);
  1733. // 尝试使用支持度更广的编码格式
  1734. let mimeType = '';
  1735. const supportedTypes = [
  1736. 'video/webm;codecs=vp9,opus',
  1737. 'video/webm;codecs=vp8,opus',
  1738. 'video/webm;codecs=h264,opus',
  1739. 'video/mp4;codecs=h264,aac',
  1740. 'video/webm',
  1741. 'video/mp4'
  1742. ];
  1743. for (const type of supportedTypes) {
  1744. if (MediaRecorder.isTypeSupported(type)) {
  1745. mimeType = type;
  1746. console.log('使用支持的MIME类型:', mimeType);
  1747. break;
  1748. }
  1749. }
  1750. // 创建MediaRecorder实例,设置较低的比特率以减小文件大小
  1751. const options = {
  1752. mimeType: mimeType || '',
  1753. audioBitsPerSecond: 64000, // 降低音频比特率
  1754. videoBitsPerSecond: 1000000, // 降低视频比特率到1Mbps
  1755. };
  1756. try {
  1757. this.mediaRecorder = new MediaRecorder(stream, options);
  1758. console.log('MediaRecorder创建成功,使用选项:', options);
  1759. } catch (e) {
  1760. console.warn('使用指定选项创建MediaRecorder失败,尝试使用默认选项');
  1761. this.mediaRecorder = new MediaRecorder(stream);
  1762. }
  1763. // 存储录制的数据块
  1764. this.recordedChunks = [];
  1765. // 监听数据可用事件
  1766. this.mediaRecorder.ondataavailable = (event) => {
  1767. if (event.data && event.data.size > 0) {
  1768. this.recordedChunks.push(event.data);
  1769. console.log(`收到数据块: ${event.data.size} 字节`);
  1770. }
  1771. };
  1772. // 监听录制停止事件
  1773. this.mediaRecorder.onstop = async () => {
  1774. console.log('MediaRecorder停止,数据块数量:', this.recordedChunks.length);
  1775. if (this.recordedChunks.length === 0) {
  1776. console.error('没有录制到数据');
  1777. /* uni.showToast({
  1778. title: '录制失败,未捕获到数据',
  1779. icon: 'none'
  1780. }); */
  1781. this.proceedToNextQuestion();
  1782. return;
  1783. }
  1784. // 创建Blob对象
  1785. const mimeType = this.mediaRecorder.mimeType || 'video/webm';
  1786. const blob = new Blob(this.recordedChunks, { type: mimeType });
  1787. console.log('创建Blob,原始大小:', blob.size, '类型:', mimeType);
  1788. // 显示压缩中提示
  1789. uni.showLoading({
  1790. title: '正在处理视频...',
  1791. mask: true
  1792. });
  1793. try {
  1794. // 压缩视频
  1795. const compressedBlob = await this.compressVideo(blob);
  1796. // 将Blob转换为File对象
  1797. const fileName = `answer_${this.currentVideoIndex}_${Date.now()}.webm`;
  1798. const file = new File([compressedBlob], fileName, { type: mimeType });
  1799. // 隐藏压缩提示
  1800. uni.hideLoading();
  1801. // 上传文件
  1802. this.uploadRecordedVideo(file);
  1803. } catch (error) {
  1804. console.error('视频处理失败:', error);
  1805. uni.hideLoading();
  1806. // 如果压缩失败,使用原始视频
  1807. const fileName = `answer_${this.currentVideoIndex}_${Date.now()}.webm`;
  1808. const file = new File([blob], fileName, { type: mimeType });
  1809. this.uploadRecordedVideo(file);
  1810. }
  1811. };
  1812. // 监听错误
  1813. this.mediaRecorder.onerror = (event) => {
  1814. console.error('MediaRecorder错误:', event.error);
  1815. };
  1816. // 开始录制
  1817. try {
  1818. this.mediaRecorder.start(1000); // 每秒触发一次dataavailable事件
  1819. console.log('MediaRecorder开始录制');
  1820. // 设置最大录制时间为60秒
  1821. // 注意:我们已经在startRecordingAnswer方法中设置了全局计时器
  1822. // 这里作为备份机制,确保即使全局计时器失效,也能停止录制
  1823. this.mediaRecorderTimeout = setTimeout(() => {
  1824. if (this.mediaRecorder && this.mediaRecorder.state === 'recording') {
  1825. console.log('MediaRecorder备份超时机制触发,停止录制');
  1826. this.mediaRecorder.stop();
  1827. }
  1828. }, 300000); // 300秒 (5分钟)
  1829. } catch (e) {
  1830. console.error('开始录制失败:', e);
  1831. }
  1832. },
  1833. // 添加新方法:获取录制时长
  1834. getRecordingDuration() {
  1835. // 如果有明确的录制开始时间,计算实际录制时长
  1836. if (this.recordingStartTime) {
  1837. return (Date.now() - this.recordingStartTime) / 1000;
  1838. }
  1839. // 如果没有明确记录开始时间,尝试从视频元素获取
  1840. if (this.mediaRecorder && this.$refs.userCameraVideo) {
  1841. return this.$refs.userCameraVideo.currentTime || 0;
  1842. }
  1843. // 如果无法获取准确时长,返回估计值(如果有计时器)
  1844. if (this.recordingTimerCount) {
  1845. return this.recordingTimerCount;
  1846. }
  1847. // 默认返回0
  1848. return 0;
  1849. },
  1850. // 添加新方法:重置录制
  1851. resetRecording() {
  1852. // 保持录制状态,但重置计时器
  1853. if (this.recordingTimer) {
  1854. clearTimeout(this.recordingTimer);
  1855. }
  1856. // 重置录制开始时间
  1857. this.recordingStartTime = Date.now();
  1858. this.recordingTimerCount = 0;
  1859. // 如果是浏览器环境,需要重置MediaRecorder
  1860. if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
  1861. // 停止当前录制
  1862. this.mediaRecorder.stop();
  1863. // 清空已录制的数据块
  1864. this.recordedChunks = [];
  1865. // 短暂延迟后重新开始录制
  1866. setTimeout(() => {
  1867. this.startBrowserRecording();
  1868. }, 500);
  1869. }
  1870. // 如果是小程序环境,需要重置相机录制
  1871. else if (this.cameraContext) {
  1872. // 停止当前录制
  1873. this.cameraContext.stopRecord({
  1874. success: () => {
  1875. console.log('相机录制已停止');
  1876. },
  1877. fail: (err) => {
  1878. console.error('停止相机录制失败:', err);
  1879. }
  1880. });
  1881. }
  1882. // 显示提示
  1883. /* uni.showToast({
  1884. title: '请重新开始回答',
  1885. icon: 'none',
  1886. duration: 2000
  1887. }); */
  1888. },
  1889. // 修改 completeRecordingStop 方法,确保正确处理追问问题ID
  1890. completeRecordingStop(uploadVideo = true) {
  1891. console.log('完成录制停止');
  1892. // 停止录制计时器
  1893. if (this.recordingTimer) {
  1894. clearInterval(this.recordingTimer);
  1895. this.recordingTimer = null;
  1896. }
  1897. // 记录最终录制时长
  1898. this.finalRecordingDuration = this.recordingTimerCount;
  1899. // 隐藏停止录制按钮
  1900. this.showStopRecordingButton = false;
  1901. // 隐藏录制指示器
  1902. this.isRecording = false;
  1903. // 根据平台选择不同的停止录制方法
  1904. const systemInfo = uni.getSystemInfoSync();
  1905. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
  1906. if (isMiniProgram) {
  1907. // 小程序环境停止录制
  1908. if (uploadVideo) {
  1909. this.stopMiniProgramRecording();
  1910. } else {
  1911. // 如果不需要上传,直接停止录制
  1912. if (this.cameraContext) {
  1913. this.cameraContext.stopRecord({
  1914. success: () => {
  1915. console.log('相机录制已停止,不上传视频');
  1916. },
  1917. fail: (err) => {
  1918. console.error('停止相机录制失败:', err);
  1919. }
  1920. });
  1921. }
  1922. }
  1923. } else {
  1924. // H5/App环境停止录制
  1925. if (uploadVideo) {
  1926. this.stopBrowserRecording();
  1927. } else {
  1928. // 如果不需要上传,直接停止录制
  1929. if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
  1930. this.mediaRecorder.stop();
  1931. this.recordedChunks = []; // 清空已录制的数据
  1932. }
  1933. }
  1934. }
  1935. // 记录当前问题ID和类型,确保追问问题使用正确的ID
  1936. if (this.isFollowUpQuestion && this.currentFollowUpQuestion) {
  1937. console.log('当前是追问问题,记录追问问题ID:', this.currentFollowUpQuestion.id);
  1938. this.lastQuestionWasFollowUp = true;
  1939. this.lastFollowUpQuestionId = this.currentFollowUpQuestion.id;
  1940. } else {
  1941. this.lastQuestionWasFollowUp = false;
  1942. this.lastFollowUpQuestionId = null;
  1943. }
  1944. },
  1945. // 修改 stopMiniProgramRecording 方法,确保正确传递追问问题ID
  1946. stopMiniProgramRecording() {
  1947. console.log('停止小程序录制');
  1948. // 检查是否有录制上下文
  1949. if (!this.cameraContext) {
  1950. console.error('相机上下文不存在');
  1951. this.proceedToNextQuestion();
  1952. return;
  1953. }
  1954. // 停止录制
  1955. this.cameraContext.stopRecord({
  1956. success: async (res) => {
  1957. console.log('小程序录制停止成功:', res);
  1958. // 获取录制的视频文件路径
  1959. const videoPath = res.tempVideoPath;
  1960. // 上传视频文件
  1961. if (videoPath) {
  1962. // 等待上传完成后再继续
  1963. await this.uploadRecordedVideo(videoPath);
  1964. } else {
  1965. console.error('未获取到录制视频路径');
  1966. this.proceedToNextQuestion();
  1967. }
  1968. },
  1969. fail: (err) => {
  1970. console.error('小程序录制停止失败:', err);
  1971. this.proceedToNextQuestion();
  1972. }
  1973. });
  1974. },
  1975. // 添加新方法:停止浏览器录制
  1976. stopBrowserRecording() {
  1977. if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
  1978. this.mediaRecorder.stop();
  1979. console.log('浏览器录制停止成功');
  1980. } else {
  1981. console.error('MediaRecorder不存在或已经停止');
  1982. this.proceedToNextQuestion();
  1983. }
  1984. },
  1985. // 修改 uploadRecordedVideo 方法,添加记录父问题ID的逻辑
  1986. uploadRecordedVideo(fileOrPath) {
  1987. console.log('准备上传视频:', typeof fileOrPath === 'string' ? fileOrPath : fileOrPath.name);
  1988. console.log('当前问题ID:', this.currentParentQuestionId);
  1989. console.log('当前问题类型:', this.isFollowUpQuestion);
  1990. console.log('当前追问问题:', this.currentFollowUpQuestion);
  1991. // 获取当前问题ID和相关信息
  1992. let questionId;
  1993. let isFollowUpQuestionUpload = false;
  1994. let questionText = '';
  1995. let questionForm = 0;
  1996. // 检查当前是否是追问问题
  1997. if (this.currentFollowUpQuestion &&
  1998. (this.currentFollowUpQuestion.question_form === 5 || this.isFollowUpQuestion)) {
  1999. // 使用追问问题的信息
  2000. questionId = this.currentFollowUpQuestion.id;
  2001. isFollowUpQuestionUpload = true;
  2002. questionText = this.currentFollowUpQuestion.question || '';
  2003. questionForm = 5; // 追问问题类型
  2004. console.log('正在上传追问问题的回答:', {
  2005. questionId,
  2006. questionText,
  2007. questionForm,
  2008. isFollowUp: true
  2009. });
  2010. } else {
  2011. // 显示思考中loading
  2012. this.showThinkingLoading();
  2013. // 使用常规问题的信息
  2014. const currentQuestion = this.getCurrentQuestionByIndex(this.currentVideoIndex);
  2015. if (currentQuestion && currentQuestion.id) {
  2016. questionId = currentQuestion.id;
  2017. questionText = currentQuestion.question || '';
  2018. console.log('正在上传常规问题的回答:', {
  2019. questionId,
  2020. questionText,
  2021. questionForm: 0
  2022. });
  2023. } else {
  2024. questionId = this.getDefaultQuestionId(this.currentVideoIndex);
  2025. console.log('使用默认问题ID:', questionId);
  2026. }
  2027. }
  2028. // 创建上传任务对象
  2029. const uploadTask = {
  2030. id: Date.now().toString(),
  2031. file: fileOrPath,
  2032. questionId: questionId,
  2033. isFollowUp: isFollowUpQuestionUpload,
  2034. questionText: questionText,
  2035. questionForm: questionForm,
  2036. attempts: 0,
  2037. maxAttempts: 3,
  2038. parentQuestionId: this.currentParentQuestionId,
  2039. videoDuration: this.currentRecordingDuration || 0 // 添加视频时长
  2040. };
  2041. // 如果不是追问问题,记录当前问题ID作为父问题ID
  2042. if (!isFollowUpQuestionUpload) {
  2043. this.currentParentQuestionId = questionId;
  2044. }
  2045. // 添加到上传队列
  2046. this.uploadQueue.push(uploadTask);
  2047. // 初始化上传进度和状态
  2048. this.uploadProgress[uploadTask.id] = 0;
  2049. this.uploadStatus[uploadTask.id] = 'pending';
  2050. // 显示上传状态提示
  2051. /* uni.showToast({
  2052. title: '正在上传回答...',
  2053. icon: 'loading',
  2054. duration: 1500
  2055. }); */
  2056. // 更新上传状态文本
  2057. this.updateUploadStatusText();
  2058. // 如果是追问问题,使用后台上传,不阻塞流程
  2059. if (isFollowUpQuestionUpload) {
  2060. console.log('追问问题使用后台上传,不阻塞流程');
  2061. // 立即执行后续操作,不等待上传完成
  2062. this.handlePostUploadActions(uploadTask);
  2063. // 启动后台上传
  2064. this.startBackgroundUpload(uploadTask);
  2065. // 返回立即解决的Promise
  2066. return Promise.resolve();
  2067. } else {
  2068. // 常规问题保持原有逻辑,等待上传完成
  2069. return new Promise((resolve) => {
  2070. const checkUploadStatus = () => {
  2071. if (!this.isUploading && this.uploadQueue.length === 0) {
  2072. // 上传完成后执行后续操作
  2073. this.handlePostUploadActions(uploadTask);
  2074. resolve();
  2075. } else {
  2076. // 如果还在上传,继续检查
  2077. setTimeout(checkUploadStatus, 100);
  2078. }
  2079. };
  2080. // 如果当前没有上传任务在进行,开始处理队列
  2081. if (!this.isUploading) {
  2082. this.processUploadQueue();
  2083. }
  2084. // 开始检查上传状态
  2085. checkUploadStatus();
  2086. });
  2087. }
  2088. },
  2089. // 添加新方法:启动后台上传
  2090. startBackgroundUpload(task) {
  2091. console.log('启动后台上传任务:', task.id);
  2092. // 标记为后台上传任务
  2093. task.isBackgroundUpload = true;
  2094. // 从主上传队列中移除,避免与常规上传冲突
  2095. const taskIndex = this.uploadQueue.findIndex(t => t.id === task.id);
  2096. if (taskIndex !== -1) {
  2097. this.uploadQueue.splice(taskIndex, 1);
  2098. }
  2099. // 添加到后台上传队列
  2100. if (!this.backgroundUploadQueue) {
  2101. this.backgroundUploadQueue = [];
  2102. }
  2103. this.backgroundUploadQueue.push(task);
  2104. // 启动后台上传处理
  2105. this.processBackgroundUploadQueue();
  2106. },
  2107. // 添加新方法:处理后台上传队列
  2108. processBackgroundUploadQueue() {
  2109. // 如果后台上传队列为空,结束处理
  2110. if (!this.backgroundUploadQueue || this.backgroundUploadQueue.length === 0) {
  2111. return;
  2112. }
  2113. // 获取队列中的第一个任务
  2114. const task = this.backgroundUploadQueue[0];
  2115. console.log('开始后台上传:', task.id);
  2116. // 更新任务状态
  2117. this.uploadStatus[task.id] = 'uploading';
  2118. this.updateUploadStatusText();
  2119. // 增加尝试次数
  2120. task.attempts++;
  2121. // 根据文件类型选择上传方法
  2122. if (typeof task.file === 'string') {
  2123. // 小程序环境,使用uni.uploadFile上传
  2124. this.uploadFileWithUniBackground(task);
  2125. } else {
  2126. // 浏览器环境,使用XMLHttpRequest上传
  2127. this.uploadFileWithXHRBackground(task);
  2128. }
  2129. },
  2130. // 添加新方法:使用XMLHttpRequest后台上传文件
  2131. uploadFileWithXHRBackground(task) {
  2132. // 获取用户信息
  2133. const userInfo = uni.getStorageSync('userInfo');
  2134. const openid = userInfo ? (JSON.parse(userInfo).openid || '') : '';
  2135. const tenant_id = JSON.parse(uni.getStorageSync('userInfo')).tenant_id || '1';
  2136. // 创建FormData
  2137. const formData = new FormData();
  2138. formData.append('file', task.file);
  2139. formData.append('openid', openid);
  2140. formData.append('tenant_id', tenant_id);
  2141. formData.append('application_id', uni.getStorageSync('appId'));
  2142. formData.append('question_id', task.questionId);
  2143. formData.append('video_duration', task.videoDuration || 0);
  2144. formData.append('has_audio', 'true');
  2145. // 创建XMLHttpRequest
  2146. const xhr = new XMLHttpRequest();
  2147. // 监听上传进度
  2148. xhr.upload.onprogress = (event) => {
  2149. if (event.lengthComputable) {
  2150. const progress = Math.round((event.loaded / event.total) * 100);
  2151. this.uploadProgress[task.id] = progress;
  2152. this.updateUploadStatusText();
  2153. }
  2154. };
  2155. // 监听请求完成
  2156. xhr.onload = () => {
  2157. if (xhr.status === 200) {
  2158. try {
  2159. const res = JSON.parse(xhr.responseText);
  2160. console.log('后台上传响应:', res);
  2161. if (res.code === 2000) {
  2162. // 获取上传后的视频URL
  2163. const videoUrl = res.data.url || res.data.photoUrl || '';
  2164. if (videoUrl) {
  2165. // 上传成功,更新状态
  2166. this.uploadStatus[task.id] = 'success';
  2167. this.updateUploadStatusText();
  2168. // 提交到面试接口
  2169. this.submitVideoToInterviewBackground(videoUrl, task);
  2170. } else {
  2171. this.handleBackgroundUploadFailure(task, '视频URL获取失败');
  2172. }
  2173. } else {
  2174. this.handleBackgroundUploadFailure(task, res.msg || '上传失败');
  2175. }
  2176. } catch (e) {
  2177. this.handleBackgroundUploadFailure(task, '解析响应失败');
  2178. }
  2179. } else {
  2180. this.handleBackgroundUploadFailure(task, 'HTTP状态: ' + xhr.status);
  2181. }
  2182. };
  2183. // 监听错误
  2184. xhr.onerror = () => {
  2185. this.handleBackgroundUploadFailure(task, '网络错误');
  2186. };
  2187. // 监听超时
  2188. xhr.ontimeout = () => {
  2189. this.handleBackgroundUploadFailure(task, '上传超时');
  2190. };
  2191. // 发送请求
  2192. xhr.open('POST', `${apiBaseUrl}/api/upload/`);
  2193. xhr.send(formData);
  2194. },
  2195. // 添加新方法:使用uni.uploadFile后台上传文件
  2196. uploadFileWithUniBackground(task) {
  2197. // 获取用户信息
  2198. const userInfo = uni.getStorageSync('userInfo');
  2199. const openid = userInfo ? (JSON.parse(userInfo).openid || '') : '';
  2200. const tenant_id = JSON.parse(uni.getStorageSync('userInfo')).tenant_id || '1';
  2201. // 创建上传任务
  2202. const uploadTask = uni.uploadFile({
  2203. url: `${apiBaseUrl}/api/upload/`,
  2204. filePath: task.file,
  2205. name: 'file',
  2206. formData: {
  2207. openid: openid,
  2208. tenant_id: tenant_id,
  2209. application_id: uni.getStorageSync('appId'),
  2210. question_id: task.questionId,
  2211. video_duration: task.videoDuration || 0,
  2212. has_audio: 'true'
  2213. },
  2214. success: (uploadRes) => {
  2215. try {
  2216. const res = JSON.parse(uploadRes.data);
  2217. console.log('后台上传响应:', res);
  2218. if (res.code === 2000) {
  2219. // 获取上传后的视频URL
  2220. const videoUrl = res.data.permanent_link || res.data.url || '';
  2221. if (videoUrl) {
  2222. // 上传成功,更新状态
  2223. this.uploadStatus[task.id] = 'success';
  2224. this.updateUploadStatusText();
  2225. // 提交到面试接口
  2226. this.submitVideoToInterviewBackground(videoUrl, task);
  2227. } else {
  2228. this.handleBackgroundUploadFailure(task, '视频URL获取失败');
  2229. }
  2230. } else {
  2231. this.handleBackgroundUploadFailure(task, res.msg || '上传失败');
  2232. }
  2233. } catch (e) {
  2234. this.handleBackgroundUploadFailure(task, '解析响应失败');
  2235. }
  2236. },
  2237. fail: (err) => {
  2238. this.handleBackgroundUploadFailure(task, err.errMsg || '上传失败');
  2239. }
  2240. });
  2241. // 监听上传进度
  2242. uploadTask.onProgressUpdate((res) => {
  2243. this.uploadProgress[task.id] = res.progress;
  2244. this.updateUploadStatusText();
  2245. });
  2246. },
  2247. // 添加新方法:处理后台上传失败
  2248. handleBackgroundUploadFailure(task, errorMsg) {
  2249. console.error('后台上传失败:', errorMsg);
  2250. // 更新任务状态
  2251. this.uploadStatus[task.id] = 'failed';
  2252. this.updateUploadStatusText();
  2253. // 检查是否还有重试机会
  2254. if (task.attempts < task.maxAttempts) {
  2255. console.log(`将在5秒后重试后台上传,当前尝试次数: ${task.attempts}/${task.maxAttempts}`);
  2256. // 5秒后重试
  2257. setTimeout(() => {
  2258. // 重置进度
  2259. this.uploadProgress[task.id] = 0;
  2260. // 重新开始上传
  2261. if (typeof task.file !== 'string') {
  2262. this.uploadFileWithXHRBackground(task);
  2263. } else {
  2264. this.uploadFileWithUniBackground(task);
  2265. }
  2266. }, 5000);
  2267. } else {
  2268. // 超过最大重试次数,移除任务
  2269. console.log('超过最大重试次数,放弃后台上传');
  2270. // 从后台上传队列中移除当前任务
  2271. if (this.backgroundUploadQueue) {
  2272. const taskIndex = this.backgroundUploadQueue.findIndex(t => t.id === task.id);
  2273. if (taskIndex !== -1) {
  2274. this.backgroundUploadQueue.splice(taskIndex, 1);
  2275. }
  2276. }
  2277. // 继续处理队列中的下一个任务
  2278. this.processBackgroundUploadQueue();
  2279. }
  2280. },
  2281. // 添加新方法:后台上传提交到面试接口
  2282. submitVideoToInterviewBackground(videoUrl, task) {
  2283. // 准备请求参数
  2284. const followUpRequestData = {
  2285. application_id: uni.getStorageSync('appId'),
  2286. tenant_id: JSON.parse(uni.getStorageSync('userInfo')).tenant_id || '1',
  2287. video_url: videoUrl,
  2288. original_question_id: this.parentJobPositionQuestionId, // 使用保存的job_position_question_id
  2289. follow_up_question: task.questionText,
  2290. video_duration: task.videoDuration,
  2291. openid: JSON.parse(uni.getStorageSync('userInfo')).openid || ''
  2292. };
  2293. console.log('后台上传提交追问视频:', followUpRequestData);
  2294. uni.request({
  2295. url: `${apiBaseUrl}/voice_interview/upload_follow_up_video/`,
  2296. method: 'POST',
  2297. data: followUpRequestData,
  2298. header: {
  2299. 'content-type': 'application/x-www-form-urlencoded'
  2300. },
  2301. success: (res) => {
  2302. if (res.data.code === 200 || res.data.code === 2000) {
  2303. console.log('后台上传追问视频提交成功');
  2304. // 从后台上传队列中移除任务
  2305. if (this.backgroundUploadQueue) {
  2306. const taskIndex = this.backgroundUploadQueue.findIndex(t => t.id === task.id);
  2307. if (taskIndex !== -1) {
  2308. this.backgroundUploadQueue.splice(taskIndex, 1);
  2309. }
  2310. }
  2311. // 继续处理下一个后台上传任务
  2312. this.processBackgroundUploadQueue();
  2313. } else {
  2314. this.handleBackgroundSubmitFailure(task, '提交失败: ' + (res.data.msg || '未知错误'));
  2315. }
  2316. },
  2317. fail: (err) => {
  2318. console.error('后台上传提交失败:', err);
  2319. this.handleBackgroundSubmitFailure(task, '提交失败: ' + err.errMsg);
  2320. }
  2321. });
  2322. },
  2323. // 添加新方法:处理后台上传提交失败
  2324. handleBackgroundSubmitFailure(task, errorMsg) {
  2325. console.error('后台上传提交失败:', errorMsg);
  2326. // 检查是否还有重试机会
  2327. if (task.attempts < task.maxAttempts) {
  2328. console.log(`将在5秒后重试后台上传提交,当前尝试次数: ${task.attempts}/${task.maxAttempts}`);
  2329. // 5秒后重试
  2330. setTimeout(() => {
  2331. this.submitVideoToInterviewBackground(task.videoUrl, task);
  2332. }, 5000);
  2333. } else {
  2334. // 超过最大重试次数,移除任务
  2335. console.log('超过最大重试次数,放弃后台上传提交');
  2336. // 从后台上传队列中移除当前任务
  2337. if (this.backgroundUploadQueue) {
  2338. const taskIndex = this.backgroundUploadQueue.findIndex(t => t.id === task.id);
  2339. if (taskIndex !== -1) {
  2340. this.backgroundUploadQueue.splice(taskIndex, 1);
  2341. }
  2342. }
  2343. // 继续处理队列中的下一个任务
  2344. this.processBackgroundUploadQueue();
  2345. }
  2346. },
  2347. // 添加新方法:处理上传后的逻辑
  2348. handlePostUploadActions(task) {
  2349. // 隐藏思考中loading
  2350. this.hideThinkingLoading();
  2351. // 检查是否需要播放低分视频
  2352. if (this.needPlayLowScoreVideo && this.retryCount < 1) {
  2353. this.playLowScoreVideo();
  2354. this.needPlayLowScoreVideo = false;
  2355. } else {
  2356. // 如果是追问问题的回答,直接进入下一个问题
  2357. if (task.isFollowUp) {
  2358. console.log('追问问题回答完成,进入下一个问题');
  2359. this.retryCount = 0; // 重置重试次数
  2360. this.isFollowUpQuestion = false; // 重置追问标记
  2361. this.currentFollowUpQuestion = null; // 清除当前追问问题信息
  2362. this.videoUrl=''
  2363. // 若未达到上限则继续请求下一条追问,否则进入下一题
  2364. this.maybeRequestNextFollowUp(this.parentJobPositionQuestionId);
  2365. } else {
  2366. // 如果是常规问题,记录父问题ID并检查追问问题
  2367. this.currentParentQuestionId = task.questionId;
  2368. console.log('检查常规问题的追问,父问题ID:', this.currentParentQuestionId);
  2369. // 从题目读取追问上限(若后端提供),否则使用默认
  2370. const currentQuestion = this.getCurrentQuestionByIndex(this.currentVideoIndex);
  2371. if (currentQuestion && typeof currentQuestion.follow_up_limit !== 'undefined') {
  2372. this.setFollowUpLimit(this.currentParentQuestionId, currentQuestion.follow_up_limit);
  2373. } else if (typeof this.defaultFollowUpLimit !== 'undefined') {
  2374. this.setFollowUpLimit(this.currentParentQuestionId, this.defaultFollowUpLimit);
  2375. }
  2376. this.resetFollowUpAskedCount(this.currentParentQuestionId);
  2377. this.checkAndPlayFollowUpQuestion(this.currentParentQuestionId);
  2378. }
  2379. }
  2380. },
  2381. // 修改 processUploadQueue 方法
  2382. processUploadQueue() {
  2383. // 如果队列为空,结束处理
  2384. if (this.uploadQueue.length === 0) {
  2385. this.isUploading = false;
  2386. this.showUploadStatus = false;
  2387. this.hideThinkingLoading(); // 隐藏思考中loading
  2388. return;
  2389. }
  2390. // 标记为正在上传
  2391. this.isUploading = true;
  2392. this.showUploadStatus = true;
  2393. // 获取队列中的第一个任务
  2394. const task = this.uploadQueue[0];
  2395. // 更新任务状态
  2396. this.uploadStatus[task.id] = 'uploading';
  2397. this.updateUploadStatusText();
  2398. // 增加尝试次数
  2399. task.attempts++;
  2400. // 根据文件类型选择上传方法
  2401. if (typeof task.file === 'string') {
  2402. // 小程序环境,使用uni.uploadFile上传
  2403. this.uploadFileWithUni(task);
  2404. } else {
  2405. // 浏览器环境,使用XMLHttpRequest上传
  2406. this.uploadFileWithXHR(task);
  2407. }
  2408. },
  2409. // 添加新方法:使用XMLHttpRequest上传文件
  2410. uploadFileWithXHR(task) {
  2411. // 获取用户信息
  2412. const userInfo = uni.getStorageSync('userInfo');
  2413. const openid = userInfo ? (JSON.parse(userInfo).openid || '') : '';
  2414. const tenant_id = JSON.parse(uni.getStorageSync('userInfo')).tenant_id || '1';
  2415. // 创建FormData
  2416. const formData = new FormData();
  2417. formData.append('file', task.file);
  2418. formData.append('openid', openid);
  2419. formData.append('tenant_id', tenant_id);
  2420. formData.append('application_id', uni.getStorageSync('appId'));
  2421. formData.append('question_id', task.questionId);
  2422. formData.append('video_duration', task.videoDuration);
  2423. formData.append('has_audio', 'true');
  2424. // 创建XMLHttpRequest
  2425. const xhr = new XMLHttpRequest();
  2426. xhr.open('POST', `${apiBaseUrl}/api/upload/`, true);
  2427. xhr.timeout = 120000; // 2分钟超时
  2428. // 监听上传进度
  2429. xhr.upload.onprogress = (event) => {
  2430. if (event.lengthComputable) {
  2431. const percentComplete = Math.round((event.loaded / event.total) * 100);
  2432. this.uploadProgress[task.id] = percentComplete;
  2433. this.updateUploadStatusText();
  2434. }
  2435. };
  2436. // 监听请求完成
  2437. xhr.onload = () => {
  2438. if (xhr.status === 200) {
  2439. try {
  2440. const res = JSON.parse(xhr.responseText);
  2441. console.log('上传响应:', res);
  2442. if (res.code === 2000) {
  2443. // 获取上传后的视频URL
  2444. const videoUrl = res.data.url || res.data.photoUrl || '';
  2445. if (videoUrl) {
  2446. // 上传成功,更新状态
  2447. this.uploadStatus[task.id] = 'success';
  2448. this.updateUploadStatusText();
  2449. // 提交到面试接口
  2450. this.submitVideoToInterview(videoUrl, task);
  2451. } else {
  2452. this.handleUploadFailure(task, '视频URL获取失败');
  2453. }
  2454. } else {
  2455. this.handleUploadFailure(task, res.msg || '上传失败');
  2456. }
  2457. } catch (e) {
  2458. this.handleUploadFailure(task, '解析响应失败');
  2459. }
  2460. } else {
  2461. this.handleUploadFailure(task, 'HTTP状态: ' + xhr.status);
  2462. }
  2463. };
  2464. // 监听错误
  2465. xhr.onerror = () => {
  2466. this.handleUploadFailure(task, '网络错误');
  2467. };
  2468. // 监听超时
  2469. xhr.ontimeout = () => {
  2470. this.handleUploadFailure(task, '上传超时');
  2471. };
  2472. // 发送请求
  2473. xhr.send(formData);
  2474. },
  2475. // 添加新方法:使用uni.uploadFile上传文件
  2476. uploadFileWithUni(task) {
  2477. // 获取用户信息
  2478. const userInfo = uni.getStorageSync('userInfo');
  2479. const openid = userInfo ? (JSON.parse(userInfo).openid || '') : '';
  2480. const tenant_id = JSON.parse(uni.getStorageSync('userInfo')).tenant_id || '1';
  2481. // 创建上传任务
  2482. const uploadTask = uni.uploadFile({
  2483. url: `${apiBaseUrl}/api/upload/`,
  2484. filePath: task.file,
  2485. name: 'file',
  2486. formData: {
  2487. openid: openid,
  2488. tenant_id: tenant_id,
  2489. application_id: uni.getStorageSync('appId'),
  2490. question_id: task.questionId,
  2491. video_duration: 0,
  2492. has_audio: 'true'
  2493. },
  2494. success: (uploadRes) => {
  2495. try {
  2496. const res = JSON.parse(uploadRes.data);
  2497. console.log('上传响应:', res);
  2498. if (res.code === 2000) {
  2499. // 获取上传后的视频URL
  2500. const videoUrl = res.data.permanent_link || res.data.url || '';
  2501. if (videoUrl) {
  2502. // 上传成功,更新状态
  2503. this.uploadStatus[task.id] = 'success';
  2504. this.updateUploadStatusText();
  2505. // 提交到面试接口
  2506. this.submitVideoToInterview(videoUrl, task);
  2507. } else {
  2508. this.handleUploadFailure(task, '视频URL获取失败');
  2509. }
  2510. } else {
  2511. this.handleUploadFailure(task, res.msg || '上传失败');
  2512. }
  2513. } catch (e) {
  2514. this.handleUploadFailure(task, '解析响应失败');
  2515. }
  2516. },
  2517. fail: (err) => {
  2518. this.handleUploadFailure(task, err.errMsg || '上传失败');
  2519. }
  2520. });
  2521. // 监听上传进度
  2522. uploadTask.onProgressUpdate((res) => {
  2523. this.uploadProgress[task.id] = res.progress;
  2524. this.updateUploadStatusText();
  2525. });
  2526. },
  2527. // 添加新方法:处理上传失败
  2528. handleUploadFailure(task, errorMsg) {
  2529. console.error('上传失败:', errorMsg);
  2530. // 更新任务状态
  2531. this.uploadStatus[task.id] = 'failed';
  2532. this.updateUploadStatusText();
  2533. // 检查是否还有重试机会
  2534. if (task.attempts < task.maxAttempts) {
  2535. console.log(`将在5秒后重试上传,当前尝试次数: ${task.attempts}/${task.maxAttempts}`);
  2536. // 5秒后重试
  2537. setTimeout(() => {
  2538. // 重置进度
  2539. this.uploadProgress[task.id] = 0;
  2540. // 重新开始上传
  2541. if (typeof task.file !== 'string') {
  2542. this.uploadFileWithXHR(task);
  2543. } else {
  2544. this.uploadFileWithUni(task);
  2545. }
  2546. }, 5000);
  2547. } else {
  2548. // 超过最大重试次数,移除任务并继续处理队列
  2549. console.log('超过最大重试次数,放弃上传');
  2550. // 显示错误提示
  2551. /* uni.showToast({
  2552. title: '视频上传失败,请稍后重试',
  2553. icon: 'none',
  2554. duration: 2000
  2555. }); */
  2556. // 从队列中移除当前任务
  2557. this.uploadQueue.shift();
  2558. // 继续处理队列中的下一个任务
  2559. this.processUploadQueue();
  2560. }
  2561. },
  2562. // 修改 submitVideoToInterview 方法
  2563. submitVideoToInterview(videoUrl, task) {
  2564. // 准备请求参数
  2565. const requestData = {
  2566. application_id: uni.getStorageSync('appId'),
  2567. question_id: task.questionId,
  2568. video_url: videoUrl,
  2569. tenant_id: JSON.parse(uni.getStorageSync('userInfo')).tenant_id || '1',
  2570. is_follow_up: task.isFollowUp ? 1 : 0,
  2571. question_form: task.questionForm,
  2572. question_text: task.questionText
  2573. };
  2574. console.log('提交视频到面试接口', requestData);
  2575. // 发送请求到面试接口
  2576. if (task.isFollowUp) {
  2577. // 追问视频上传
  2578. const followUpRequestData = {
  2579. application_id: uni.getStorageSync('appId'),
  2580. tenant_id: JSON.parse(uni.getStorageSync('userInfo')).tenant_id || '1',
  2581. video_url: videoUrl,
  2582. original_question_id: this.parentJobPositionQuestionId, // 使用保存的job_position_question_id
  2583. follow_up_question: task.questionText,
  2584. video_duration: task.videoDuration,
  2585. openid: JSON.parse(uni.getStorageSync('userInfo')).openid || ''
  2586. };
  2587. console.log('准备提交追问视频:', followUpRequestData);
  2588. uni.request({
  2589. url: `${apiBaseUrl}/voice_interview/upload_follow_up_video/`,
  2590. method: 'POST',
  2591. data: followUpRequestData,
  2592. header: {
  2593. 'content-type': 'application/x-www-form-urlencoded'
  2594. },
  2595. success: async (res) => {
  2596. try {
  2597. if (res.data.code === 200 || res.data.code === 2000) {
  2598. if (res.data.data && res.data.data.transcription_status === 'pending') {
  2599. // 如果转写状态为pending,5秒后重试
  2600. console.log('视频转写进行中,5秒后重试');
  2601. setTimeout(() => {
  2602. this.checkTranscriptionStatus(task, followUpRequestData);
  2603. }, 5000);
  2604. return;
  2605. }
  2606. console.log('追问视频提交成功');
  2607. this.isFollowUpMode = false;
  2608. this.currentVideoIndex = this.mainQuestionIndex;
  2609. /* uni.showToast({
  2610. title: '回答已提交',
  2611. icon: 'success',
  2612. duration: 1500
  2613. }); */
  2614. this.uploadQueue.shift();
  2615. this.processUploadQueue();
  2616. this.$nextTick(() => {
  2617. if (this.currentVideoIndex < this.videoList.length) {
  2618. this.videoUrl = this.videoList[this.currentVideoIndex];
  2619. this.videoPlaying = true;
  2620. const videoContext = uni.createVideoContext('myVideo', this);
  2621. if (videoContext) {
  2622. videoContext.play();
  2623. }
  2624. }
  2625. });
  2626. } else {
  2627. this.handleSubmitFailure(task, '提交失败: ' + (res.data.msg || '未知错误'));
  2628. }
  2629. } catch (e) {
  2630. this.handleSubmitFailure(task, '解析响应失败: ' + e.message);
  2631. }
  2632. },
  2633. fail: (err) => {
  2634. console.error('提交视频失败:', err);
  2635. this.handleSubmitFailure(task, '提交失败: ' + err.errMsg);
  2636. }
  2637. });
  2638. } else {
  2639. // 原有的视频上传逻辑
  2640. uni.request({
  2641. url: `${apiBaseUrl}/api/job/upload_video`,
  2642. method: 'POST',
  2643. data: requestData,
  2644. header: {
  2645. 'content-type': 'application/x-www-form-urlencoded'
  2646. },
  2647. success: async (res) => {
  2648. if (res.data.code === 200 || res.data.code === 2000) {
  2649. console.log('视频提交成功,准备调用面试互动接口');
  2650. try {
  2651. // 保存job_position_question_id用于后续追问
  2652. this.parentJobPositionQuestionId = res.data.data.job_position_question_id;
  2653. console.log('保存父问题ID:', this.parentJobPositionQuestionId);
  2654. // 初始化该题的追问上限与已问次数
  2655. const limitFromServer = res.data.data.follow_up_limit;
  2656. if (typeof limitFromServer !== 'undefined') {
  2657. this.setFollowUpLimit(this.parentJobPositionQuestionId, limitFromServer);
  2658. } else {
  2659. this.setFollowUpLimit(this.parentJobPositionQuestionId, this.defaultFollowUpLimit);
  2660. }
  2661. this.resetFollowUpAskedCount(this.parentJobPositionQuestionId);
  2662. await this.callInterviewInteraction(res.data.data.job_position_question_id);
  2663. console.log('面试互动接口调用成功');
  2664. } catch (error) {
  2665. console.error('面试互动接口调用失败:', error);
  2666. this.proceedToNextQuestion();
  2667. }
  2668. /* uni.showToast({
  2669. title: '回答已提交',
  2670. icon: 'success',
  2671. duration: 1500
  2672. }); */
  2673. this.uploadQueue.shift();
  2674. this.processUploadQueue();
  2675. } else {
  2676. this.handleSubmitFailure(task, '提交失败: ' + (res.data.msg || '未知错误'));
  2677. }
  2678. },
  2679. fail: (err) => {
  2680. console.error('提交视频失败:', err);
  2681. this.handleSubmitFailure(task, '提交失败: ' + err.errMsg);
  2682. }
  2683. });
  2684. }
  2685. },
  2686. // 添加新方法:处理提交失败
  2687. handleSubmitFailure(task, errorMsg) {
  2688. console.error('提交失败:', errorMsg);
  2689. // 更新任务状态
  2690. this.uploadStatus[task.id] = 'failed';
  2691. this.updateUploadStatusText();
  2692. // 检查是否还有重试机会
  2693. if (task.attempts < task.maxAttempts) {
  2694. console.log(`将在5秒后重试提交,当前尝试次数: ${task.attempts}/${task.maxAttempts}`);
  2695. // 5秒后重试
  2696. setTimeout(() => {
  2697. // 重新提交
  2698. this.submitVideoToInterview(task.videoUrl, task);
  2699. }, 5000);
  2700. } else {
  2701. // 超过最大重试次数,移除任务并继续处理队列
  2702. console.log('超过最大重试次数,放弃提交');
  2703. // 显示错误提示
  2704. /* uni.showToast({
  2705. title: '视频提交失败,请稍后重试',
  2706. icon: 'none',
  2707. duration: 2000
  2708. }); */
  2709. // 从队列中移除当前任务
  2710. this.uploadQueue.shift();
  2711. // 继续处理队列中的下一个任务
  2712. this.processUploadQueue();
  2713. }
  2714. },
  2715. // 添加检查转写状态的方法
  2716. checkTranscriptionStatus(task, requestData, retryCount = 0) {
  2717. const maxRetries = 24; // 最大重试次数(2分钟)
  2718. const retryInterval = 5000; // 重试间隔时间(5秒)
  2719. if (retryCount >= maxRetries) {
  2720. console.log('转写超时,继续下一个问题');
  2721. this.isFollowUpMode = false;
  2722. this.currentVideoIndex = this.mainQuestionIndex;
  2723. this.uploadQueue.shift();
  2724. this.processUploadQueue();
  2725. return;
  2726. }
  2727. uni.request({
  2728. url: `${apiBaseUrl}/voice_interview/check_transcription_status/`,
  2729. method: 'POST',
  2730. data: {
  2731. application_id: requestData.application_id,
  2732. original_question_id: requestData.original_question_id,
  2733. video_url: requestData.video_url
  2734. },
  2735. header: {
  2736. 'content-type': 'application/x-www-form-urlencoded'
  2737. },
  2738. success: (res) => {
  2739. if (res.data.code === 200 || res.data.code === 2000) {
  2740. if (res.data.data && res.data.data.status === 'completed') {
  2741. console.log('视频转写完成');
  2742. this.isFollowUpMode = false;
  2743. this.currentVideoIndex = this.mainQuestionIndex;
  2744. this.uploadQueue.shift();
  2745. this.processUploadQueue();
  2746. this.$nextTick(() => {
  2747. if (this.currentVideoIndex < this.videoList.length) {
  2748. this.videoUrl = this.videoList[this.currentVideoIndex];
  2749. this.videoPlaying = true;
  2750. const videoContext = uni.createVideoContext('myVideo', this);
  2751. if (videoContext) {
  2752. videoContext.play();
  2753. }
  2754. }
  2755. });
  2756. } else {
  2757. // 状态仍为pending,继续重试
  2758. console.log(`转写进行中,${retryInterval/1000}秒后重试 (${retryCount + 1}/${maxRetries})`);
  2759. setTimeout(() => {
  2760. this.checkTranscriptionStatus(task, requestData, retryCount + 1);
  2761. }, retryInterval);
  2762. }
  2763. } else if (res.data.message === "面试视频尚未完成转写" || res.data.success === false) {
  2764. // 特殊处理转写未完成的情况
  2765. console.log(`转写未完成,${retryInterval/1000}秒后重试 (${retryCount + 1}/${maxRetries})`);
  2766. setTimeout(() => {
  2767. this.checkTranscriptionStatus(task, requestData, retryCount + 1);
  2768. }, retryInterval);
  2769. } else {
  2770. this.handleSubmitFailure(task, '检查转写状态失败: ' + (res.data.msg || '未知错误'));
  2771. }
  2772. },
  2773. fail: (err) => {
  2774. console.error('检查转写状态失败:', err);
  2775. // 网络错误时也进行重试
  2776. console.log(`网络请求失败,${retryInterval/1000}秒后重试 (${retryCount + 1}/${maxRetries})`);
  2777. setTimeout(() => {
  2778. this.checkTranscriptionStatus(task, requestData, retryCount + 1);
  2779. }, retryInterval);
  2780. }
  2781. });
  2782. },
  2783. // 添加新方法:更新上传状态文本
  2784. updateUploadStatusText() {
  2785. // 检查主上传队列
  2786. let mainQueueText = '';
  2787. if (this.uploadQueue.length > 0) {
  2788. const currentTask = this.uploadQueue[0];
  2789. const progress = this.uploadProgress[currentTask.id] || 0;
  2790. const status = this.uploadStatus[currentTask.id] || 'pending';
  2791. let statusText = '';
  2792. switch (status) {
  2793. case 'pending':
  2794. statusText = '等待上传';
  2795. break;
  2796. case 'uploading':
  2797. statusText = `上传中 ${progress}%`;
  2798. break;
  2799. case 'success':
  2800. statusText = '上传成功,提交中...';
  2801. break;
  2802. case 'failed':
  2803. statusText = `上传失败,${currentTask.attempts < currentTask.maxAttempts ? '即将重试' : '已放弃'}`;
  2804. break;
  2805. }
  2806. // 添加问题类型和文本的中文释义
  2807. const questionTypeText = currentTask.isFollowUp ? '追问' : '问题';
  2808. const questionShortText = currentTask.questionText ?
  2809. (currentTask.questionText.length > 10 ? currentTask.questionText.substring(0, 10) + '...' : currentTask.questionText) :
  2810. `${questionTypeText}${currentTask.questionId}`;
  2811. mainQueueText = `${questionTypeText}「${questionShortText}」:${statusText}`;
  2812. // 如果队列中有多个任务,显示总数
  2813. if (this.uploadQueue.length > 1) {
  2814. mainQueueText += ` (${this.uploadQueue.length}个视频待处理)`;
  2815. }
  2816. }
  2817. // 检查后台上传队列
  2818. let backgroundQueueText = '';
  2819. if (this.backgroundUploadQueue && this.backgroundUploadQueue.length > 0) {
  2820. const currentTask = this.backgroundUploadQueue[0];
  2821. const progress = this.uploadProgress[currentTask.id] || 0;
  2822. const status = this.uploadStatus[currentTask.id] || 'pending';
  2823. let statusText = '';
  2824. switch (status) {
  2825. case 'pending':
  2826. statusText = '等待后台上传';
  2827. break;
  2828. case 'uploading':
  2829. statusText = `后台上传中 ${progress}%`;
  2830. break;
  2831. case 'success':
  2832. statusText = '后台上传成功,提交中...';
  2833. break;
  2834. case 'failed':
  2835. statusText = `后台上传失败,${currentTask.attempts < currentTask.maxAttempts ? '即将重试' : '已放弃'}`;
  2836. break;
  2837. }
  2838. const questionShortText = currentTask.questionText ?
  2839. (currentTask.questionText.length > 10 ? currentTask.questionText.substring(0, 10) + '...' : currentTask.questionText) :
  2840. `追问${currentTask.questionId}`;
  2841. backgroundQueueText = `追问「${questionShortText}」:${statusText}`;
  2842. // 如果后台上传队列中有多个任务,显示总数
  2843. if (this.backgroundUploadQueue.length > 1) {
  2844. backgroundQueueText += ` (${this.backgroundUploadQueue.length}个追问待后台上传)`;
  2845. }
  2846. }
  2847. // 合并状态文本
  2848. if (mainQueueText && backgroundQueueText) {
  2849. this.uploadStatusText = `${mainQueueText} | ${backgroundQueueText}`;
  2850. } else if (mainQueueText) {
  2851. this.uploadStatusText = mainQueueText;
  2852. } else if (backgroundQueueText) {
  2853. this.uploadStatusText = backgroundQueueText;
  2854. } else {
  2855. this.uploadStatusText = '';
  2856. }
  2857. },
  2858. // 修改 proceedToNextQuestion 方法,确保在切换视频时重置历史时间
  2859. proceedToNextQuestion() {
  2860. // 如果正在切换视频,则返回
  2861. if (this.isVideoSwitching) {
  2862. console.log('正在切换视频中,请等待...');
  2863. return;
  2864. }
  2865. console.log('继续下一个问题');
  2866. this.isVideoSwitching = true; // 设置切换状态锁
  2867. // 停止当前视频播放
  2868. const currentVideo = uni.createVideoContext('myVideo', this);
  2869. if (currentVideo) {
  2870. currentVideo.stop();
  2871. this.videoPlaying = false;
  2872. }
  2873. // 检查是否已经是最后一个视频
  2874. if (this.currentVideoIndex + 1 >= this.videoList.length) {
  2875. // 所有视频都播放完毕,显示完成页面或返回
  2876. console.log('所有视频已播放完毕');
  2877. // 清理资源
  2878. this.stopUserCamera();
  2879. this.clearCountdown();
  2880. // 获取当前职位ID
  2881. const currentJobDetail = JSON.parse(uni.getStorageSync('selectedJob'));
  2882. console.log('当前职位ID:', currentJobDetail);
  2883. const jobId = currentJobDetail ? currentJobDetail.id : null;
  2884. this.handleVideoCompletion(jobId);
  2885. return;
  2886. }
  2887. // 清理当前父题的追问中的并发锁
  2888. if (this.currentParentQuestionId) {
  2889. this.followUpRequestInFlight[this.currentParentQuestionId] = false;
  2890. }
  2891. // 增加当前视频索引,切换到下一个视频
  2892. this.currentVideoIndex++;
  2893. // 重置历史时间,避免触发异常跳转检测
  2894. this.historyTime = 0;
  2895. // 如果还有视频,播放下一个视频
  2896. if (this.currentVideoIndex < this.videoList.length) {
  2897. // 确保先更新视频URL
  2898. this.videoUrl = this.videoList[this.currentVideoIndex];
  2899. // 使用setTimeout确保DOM更新完成
  2900. this.$nextTick(() => {
  2901. this.videoPlaying = true;
  2902. const videoContext = uni.createVideoContext('myVideo', this);
  2903. if (videoContext) {
  2904. videoContext.play();
  2905. }
  2906. this.isVideoSwitching = false; // 重置切换状态锁
  2907. });
  2908. } else {
  2909. // 所有视频都播放完毕,显示完成页面或返回
  2910. console.log('所有视频已播放完毕');
  2911. // 清理资源
  2912. this.stopUserCamera();
  2913. this.clearCountdown();
  2914. // 获取当前职位ID
  2915. const currentJobDetail = JSON.parse(uni.getStorageSync('selectedJob'));
  2916. console.log('当前职位ID:', currentJobDetail);
  2917. const jobId = currentJobDetail ? currentJobDetail.id : null;
  2918. console.log('当前职位ID:', jobId);
  2919. // 延迟后根据职位ID跳转到不同页面
  2920. setTimeout(() => {
  2921. this.isVideoSwitching = false; // 重置切换状态锁
  2922. // 如果职位ID为9,跳转到interview-question页面
  2923. if (jobId === 9) {
  2924. uni.navigateTo({
  2925. url: '/pages/interview-question/interview-question',
  2926. success: () => {
  2927. console.log('成功跳转到interview-question页面');
  2928. },
  2929. fail: (err) => {
  2930. console.error('跳转到interview-question页面失败:', err);
  2931. // 如果跳转失败,尝试使用redirectTo
  2932. uni.redirectTo({
  2933. url: '/pages/interview-question/interview-question',
  2934. fail: (redirectErr) => {
  2935. console.error('重定向到interview-question页面也失败:', redirectErr);
  2936. // 如果所有跳转方式都失败,尝试返回上一页
  2937. uni.navigateBack({
  2938. delta: 1
  2939. });
  2940. }
  2941. });
  2942. }
  2943. });
  2944. } else {
  2945. // 其他职位ID跳转到camera页面
  2946. uni.navigateTo({
  2947. url: '/pages/camera/camera',
  2948. success: () => {
  2949. console.log('成功跳转到camera页面');
  2950. },
  2951. fail: (err) => {
  2952. console.error('跳转到camera页面失败:', err);
  2953. // 如果跳转失败,尝试使用redirectTo
  2954. uni.redirectTo({
  2955. url: '/pages/camera/camera',
  2956. fail: (redirectErr) => {
  2957. console.error('重定向到camera页面也失败:', redirectErr);
  2958. // 最后尝试使用switchTab(如果camera是tabBar页面)
  2959. uni.switchTab({
  2960. url: '/pages/camera/camera',
  2961. fail: (switchErr) => {
  2962. console.error('所有跳转方式都失败:', switchErr);
  2963. // 如果所有跳转方式都失败,尝试返回上一页
  2964. uni.navigateBack({
  2965. delta: 1
  2966. });
  2967. }
  2968. });
  2969. }
  2970. });
  2971. }
  2972. });
  2973. }
  2974. }, 0);
  2975. }
  2976. },
  2977. // 修改 handleAnswerButtonClick 方法,确保在切换视频时重置历史时间
  2978. handleAnswerButtonClick() {
  2979. console.log('点击开始回答按钮');
  2980. // 隐藏开始回答按钮
  2981. this.showAnswerButton = false;
  2982. // 增加当前视频索引,切换到下一个视频
  2983. this.currentVideoIndex++;
  2984. // 重置历史时间,避免触发异常跳转检测
  2985. this.historyTime = 0;
  2986. // 如果还有视频,播放下一个视频
  2987. if (this.currentVideoIndex < this.videoList.length) {
  2988. this.videoUrl = this.videoList[this.currentVideoIndex];
  2989. this.videoPlaying = true;
  2990. this.$nextTick(() => {
  2991. const videoContext = uni.createVideoContext('myVideo', this);
  2992. if (videoContext) {
  2993. videoContext.play();
  2994. }
  2995. });
  2996. }
  2997. },
  2998. // 处理相机错误
  2999. handleCameraError(e) {
  3000. console.error('相机错误:', e);
  3001. // 获取平台信息
  3002. const systemInfo = uni.getSystemInfoSync();
  3003. const isIOS = systemInfo.platform === 'ios';
  3004. if (isIOS) {
  3005. console.log('iOS相机错误,尝试重新初始化');
  3006. // 显示提示
  3007. uni.showToast({
  3008. title: '相机初始化中...',
  3009. icon: 'loading',
  3010. duration: 2000
  3011. });
  3012. // 重置相机
  3013. this.resetCamera();
  3014. // 如果正在录制,停止录制
  3015. if (this.isRecording) {
  3016. this.isRecording = false;
  3017. this.showStopRecordingButton = false;
  3018. // 提供替代选项
  3019. setTimeout(() => {
  3020. this.useAlternativeRecordingMethod();
  3021. }, 1000);
  3022. }
  3023. } else {
  3024. // 显示错误提示
  3025. uni.showToast({
  3026. title: '相机初始化失败,请检查权限设置',
  3027. icon: 'none'
  3028. });
  3029. // 尝试备用选项
  3030. this.tryFallbackOptions();
  3031. }
  3032. },
  3033. // 添加新方法:尝试备用选项
  3034. tryFallbackOptions() {
  3035. // 检查环境
  3036. const systemInfo = uni.getSystemInfoSync();
  3037. // 在小程序环境中使用小程序API
  3038. if (systemInfo.uniPlatform === 'mp-weixin' || systemInfo.uniPlatform === 'mp-alipay') {
  3039. this.useMiniProgramCamera();
  3040. }
  3041. // 在H5环境中显示静态图像
  3042. else {
  3043. this.showStaticCameraPlaceholder();
  3044. }
  3045. },
  3046. // 添加新方法:使用小程序相机API
  3047. useMiniProgramCamera() {
  3048. console.log('尝试使用小程序相机组件');
  3049. // 这里需要在模板中添加小程序相机组件
  3050. // 并设置一个标志来控制显示
  3051. this.useMiniProgramCameraComponent = true;
  3052. },
  3053. // 添加新方法:显示静态图像
  3054. showStaticCameraPlaceholder() {
  3055. console.log('显示静态摄像头占位图');
  3056. // 创建一个图像元素
  3057. const img = document.createElement('img');
  3058. img.src = '/static/images/camera-placeholder.png'; // 确保有这个图片资源
  3059. img.className = 'static-camera-image';
  3060. img.style.width = '100%';
  3061. img.style.height = '100%';
  3062. img.style.objectFit = 'cover';
  3063. // 获取容器并添加图像
  3064. const container = this.$refs.userCameraVideo.parentNode;
  3065. container.appendChild(img);
  3066. },
  3067. // 修改 handleTimeUpdate 方法
  3068. handleTimeUpdate(e) {
  3069. // 获取当前视频播放时间
  3070. const currentTime = e.detail.currentTime || e.target.currentTime;
  3071. // 如果正在录制,更新录制时间显示
  3072. if (this.isRecording && this.recordingTimerCount) {
  3073. this.recordingTimeDisplay = this.formatTime(this.recordingTimerCount);
  3074. }
  3075. // 如果正在播放低分提示视频,使用专门的字幕数组
  3076. if (this.isPlayingLowScoreVideo) {
  3077. if (this.lowScoreVideoSubtitles && this.lowScoreVideoSubtitles.length > 0) {
  3078. const subtitle = this.lowScoreVideoSubtitles[0]; // 使用第一个字幕
  3079. this.currentSubtitle = subtitle.text;
  3080. }
  3081. return;
  3082. }
  3083. // 获取当前视频对应的字幕数组
  3084. let currentSubtitles = null;
  3085. if (this.isFollowUpQuestion && this.currentFollowUpQuestion) {
  3086. // 追问问题字幕处理
  3087. const subtitleKey = `followUpSubtitles_${this.currentFollowUpQuestion.id}`;
  3088. currentSubtitles = this[subtitleKey] || [{
  3089. startTime: 0,
  3090. endTime: 30,
  3091. text: this.currentFollowUpQuestion.question ||
  3092. this.currentFollowUpQuestion.question
  3093. }];
  3094. } else {
  3095. // 常规问题字幕处理
  3096. if (this.currentVideoIndex === 0) {
  3097. currentSubtitles = this.subtitles;
  3098. } else {
  3099. const subtitleArrayName = `question${this.currentVideoIndex}Subtitles`;
  3100. currentSubtitles = this[subtitleArrayName];
  3101. }
  3102. }
  3103. // 确保字幕持续显示
  3104. if (currentSubtitles && currentSubtitles.length > 0) {
  3105. // 找到当前时间对应的字幕
  3106. const subtitle = currentSubtitles.find(sub =>
  3107. currentTime >= sub.startTime && currentTime <= sub.endTime
  3108. ) || currentSubtitles[0]; // 如果找不到对应时间的字幕,使用第一个字幕
  3109. // 只显示字幕文本
  3110. if (subtitle) {
  3111. this.currentSubtitle = subtitle.text;
  3112. }
  3113. }
  3114. // 更新历史时间和时间戳
  3115. this.historyTime = currentTime;
  3116. this.lastUpdateTime = Date.now();
  3117. },
  3118. // Add a new method to handle the "Start Recording" button click
  3119. handleStartRecordingClick() {
  3120. // 隐藏"开始回答"按钮
  3121. this.showStartRecordingButton = false;
  3122. // 如果倒计时正在进行,清除倒计时
  3123. this.clearCountdown();
  3124. // 重置等待回答状态
  3125. this.isWaitingForAnswer = false;
  3126. // 直接开始录制
  3127. this.startRecordingAnswer();
  3128. },
  3129. // 修改 checkAudioPermission 方法,确保在录制前获取音频权限
  3130. checkAudioPermission() {
  3131. // 在小程序环境中
  3132. const systemInfo = uni.getSystemInfoSync();
  3133. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
  3134. if (isMiniProgram) {
  3135. // 小程序环境下的权限请求
  3136. uni.getSetting({
  3137. success: (res) => {
  3138. if (!res.authSetting['scope.record']) {
  3139. uni.authorize({
  3140. scope: 'scope.record',
  3141. success: () => {
  3142. console.log('录音权限已获取');
  3143. },
  3144. fail: (err) => {
  3145. console.error('录音权限获取失败:', err);
  3146. this.showPermissionDialog('录音');
  3147. }
  3148. });
  3149. }
  3150. if (!res.authSetting['scope.camera']) {
  3151. uni.authorize({
  3152. scope: 'scope.camera',
  3153. success: () => {
  3154. console.log('相机权限已获取');
  3155. },
  3156. fail: (err) => {
  3157. console.error('相机权限获取失败:', err);
  3158. this.showPermissionDialog('相机');
  3159. }
  3160. });
  3161. }
  3162. }
  3163. });
  3164. } else {
  3165. // 浏览器环境下的权限请求
  3166. // ... 保持原有代码不变
  3167. }
  3168. },
  3169. // 添加新方法:测试音频输入
  3170. testAudioInput() {
  3171. if (!this.cameraStream) {
  3172. console.warn('没有可用的媒体流,无法测试音频');
  3173. return;
  3174. }
  3175. const audioTracks = this.cameraStream.getAudioTracks();
  3176. if (audioTracks.length === 0) {
  3177. console.warn('没有检测到音频轨道,尝试重新获取');
  3178. this.tryGetAudioOnly();
  3179. return;
  3180. }
  3181. console.log('音频轨道信息:', audioTracks[0].getSettings());
  3182. // 创建音频上下文和分析器
  3183. try {
  3184. const AudioContext = window.AudioContext || window.webkitAudioContext;
  3185. if (!AudioContext) {
  3186. console.warn('浏览器不支持AudioContext');
  3187. return;
  3188. }
  3189. const audioContext = new AudioContext();
  3190. const analyser = audioContext.createAnalyser();
  3191. const microphone = audioContext.createMediaStreamSource(this.cameraStream);
  3192. microphone.connect(analyser);
  3193. // 设置分析器
  3194. analyser.fftSize = 256;
  3195. const bufferLength = analyser.frequencyBinCount;
  3196. const dataArray = new Uint8Array(bufferLength);
  3197. // 检测音频输入
  3198. let silenceCounter = 0;
  3199. const checkAudio = () => {
  3200. if (this.isRecording) return; // 如果正在录制,停止检测
  3201. analyser.getByteFrequencyData(dataArray);
  3202. // 计算平均音量
  3203. let sum = 0;
  3204. for (let i = 0; i < bufferLength; i++) {
  3205. sum += dataArray[i];
  3206. }
  3207. const average = sum / bufferLength;
  3208. if (average > 10) {
  3209. console.log('检测到音频输入,音量:', average);
  3210. silenceCounter = 0;
  3211. } else {
  3212. silenceCounter++;
  3213. if (silenceCounter > 10) {
  3214. console.warn('持续检测不到音频输入,可能麦克风未正常工作');
  3215. silenceCounter = 0;
  3216. }
  3217. }
  3218. // 继续检测
  3219. requestAnimationFrame(checkAudio);
  3220. };
  3221. // 开始检测
  3222. checkAudio();
  3223. } catch (e) {
  3224. console.error('音频测试失败:', e);
  3225. }
  3226. },
  3227. // 添加新方法:尝试单独获取音频
  3228. tryGetAudioOnly() {
  3229. navigator.mediaDevices.getUserMedia({ audio: true })
  3230. .then(audioStream => {
  3231. // 如果已有视频流,合并音频和视频轨道
  3232. if (this.cameraStream) {
  3233. const videoTrack = this.cameraStream.getVideoTracks()[0];
  3234. const audioTrack = audioStream.getAudioTracks()[0];
  3235. // 创建新的媒体流,包含视频和音频轨道
  3236. const combinedStream = new MediaStream();
  3237. if (videoTrack) combinedStream.addTrack(videoTrack);
  3238. if (audioTrack) combinedStream.addTrack(audioTrack);
  3239. // 更新摄像头流
  3240. this.cameraStream = combinedStream;
  3241. // 更新视频元素的源
  3242. const videoElement = this.$refs.userCameraVideo;
  3243. if (videoElement) {
  3244. videoElement.srcObject = combinedStream;
  3245. videoElement.muted = true; // 避免回声,但仍然录制声音
  3246. }
  3247. console.log('成功合并音频和视频轨道');
  3248. } else {
  3249. console.warn('没有视频流可合并');
  3250. }
  3251. })
  3252. .catch(err => {
  3253. console.error('单独获取音频失败:', err);
  3254. });
  3255. },
  3256. // 添加新方法:显示权限对话框
  3257. showPermissionDialog(permissionType) {
  3258. uni.showModal({
  3259. title: '需要权限',
  3260. content: `请允许使用${permissionType}权限,否则可能影响面试功能`,
  3261. confirmText: '去设置',
  3262. success: (res) => {
  3263. if (res.confirm) {
  3264. uni.openSetting({
  3265. success: (settingRes) => {
  3266. console.log('设置页面打开成功', settingRes);
  3267. }
  3268. });
  3269. }
  3270. }
  3271. });
  3272. },
  3273. // 添加重试上传方法
  3274. retryVideoUpload() {
  3275. if (this.lastVideoToRetry) {
  3276. // 隐藏重试按钮
  3277. this.showRetryButton = false;
  3278. // 显示加载提示
  3279. uni.showLoading({
  3280. title: '正在重新提交...',
  3281. mask: true
  3282. });
  3283. // 重新提交视频
  3284. this.submitVideoToInterview(this.lastVideoToRetry);
  3285. } else {
  3286. uni.showToast({
  3287. title: '没有可重试的视频',
  3288. icon: 'none'
  3289. });
  3290. }
  3291. },
  3292. // 添加一个新方法用于压缩视频
  3293. async compressVideo(videoBlob) {
  3294. // 如果视频大小小于某个阈值,直接返回原视频
  3295. if (videoBlob.size < 5 * 1024 * 1024) { // 小于5MB
  3296. return videoBlob;
  3297. }
  3298. console.log('开始压缩视频,原始大小:', videoBlob.size);
  3299. // 创建一个视频元素来加载视频
  3300. const videoElement = document.createElement('video');
  3301. videoElement.muted = true;
  3302. videoElement.autoplay = false;
  3303. // 创建一个canvas元素用于绘制视频帧
  3304. const canvas = document.createElement('canvas');
  3305. const ctx = canvas.getContext('2d');
  3306. // 设置视频源
  3307. videoElement.src = URL.createObjectURL(videoBlob);
  3308. return new Promise((resolve) => {
  3309. videoElement.onloadedmetadata = () => {
  3310. // 设置canvas尺寸为视频的一半
  3311. const width = Math.floor(videoElement.videoWidth / 2);
  3312. const height = Math.floor(videoElement.videoHeight / 2);
  3313. canvas.width = width;
  3314. canvas.height = height;
  3315. // 创建MediaRecorder来录制canvas
  3316. const stream = canvas.captureStream(15); // 15fps
  3317. // 如果原视频有音轨,添加到新流中
  3318. if (videoElement.captureStream) {
  3319. const originalStream = videoElement.captureStream();
  3320. const audioTracks = originalStream.getAudioTracks();
  3321. if (audioTracks.length > 0) {
  3322. stream.addTrack(audioTracks[0]);
  3323. }
  3324. }
  3325. // 设置较低的比特率
  3326. const options = {
  3327. mimeType: 'video/webm;codecs=vp8,opus',
  3328. audioBitsPerSecond: 64000,
  3329. videoBitsPerSecond: 800000 // 800kbps
  3330. };
  3331. const mediaRecorder = new MediaRecorder(stream, options);
  3332. const chunks = [];
  3333. mediaRecorder.ondataavailable = (e) => {
  3334. if (e.data.size > 0) {
  3335. chunks.push(e.data);
  3336. }
  3337. };
  3338. mediaRecorder.onstop = () => {
  3339. const compressedBlob = new Blob(chunks, { type: 'video/webm' });
  3340. console.log('视频压缩完成,压缩后大小:', compressedBlob.size);
  3341. resolve(compressedBlob);
  3342. };
  3343. // 开始播放视频并录制
  3344. videoElement.onplay = () => {
  3345. mediaRecorder.start(10);
  3346. // 绘制视频帧到canvas
  3347. const drawFrame = () => {
  3348. if (videoElement.paused || videoElement.ended) {
  3349. mediaRecorder.stop();
  3350. return;
  3351. }
  3352. ctx.drawImage(videoElement, 0, 0, width, height);
  3353. requestAnimationFrame(drawFrame);
  3354. };
  3355. drawFrame();
  3356. };
  3357. videoElement.play();
  3358. };
  3359. });
  3360. },
  3361. // 修改 checkIOSCameraRecordPermission 方法
  3362. checkIOSCameraRecordPermission() {
  3363. const systemInfo = uni.getSystemInfoSync();
  3364. if (systemInfo.platform !== 'ios') return;
  3365. // 在iOS上,需要同时请求相机和录音权限
  3366. uni.getSetting({
  3367. success: (res) => {
  3368. // 检查相机权限
  3369. if (!res.authSetting['scope.camera']) {
  3370. uni.authorize({
  3371. scope: 'scope.camera',
  3372. success: () => {
  3373. console.log('iOS相机权限已获取');
  3374. },
  3375. fail: (err) => {
  3376. console.error('iOS相机权限获取失败:', err);
  3377. this.showPermissionDialog('相机');
  3378. }
  3379. });
  3380. }
  3381. // 检查录音权限
  3382. if (!res.authSetting['scope.record']) {
  3383. uni.authorize({
  3384. scope: 'scope.record',
  3385. success: () => {
  3386. console.log('iOS录音权限已获取');
  3387. },
  3388. fail: (err) => {
  3389. console.error('iOS录音权限获取失败:', err);
  3390. this.showPermissionDialog('录音');
  3391. }
  3392. });
  3393. }
  3394. }
  3395. });
  3396. },
  3397. // 添加新方法:检查并修复渲染问题
  3398. checkAndFixRenderingIssues() {
  3399. // 检查全局对象,防止渲染错误
  3400. try {
  3401. // 检查是否有全局变量u
  3402. if (typeof u !== 'undefined' && u) {
  3403. // 检查currentQuestion属性
  3404. if (!u.currentQuestion) {
  3405. console.log('修复: 创建缺失的currentQuestion对象');
  3406. u.currentQuestion = {};
  3407. }
  3408. // 确保isImportant属性存在
  3409. if (u.currentQuestion && typeof u.currentQuestion.isImportant === 'undefined') {
  3410. console.log('修复: 设置缺失的isImportant属性');
  3411. u.currentQuestion.isImportant = false;
  3412. }
  3413. }
  3414. } catch (e) {
  3415. console.log('防御性检查异常:', e);
  3416. }
  3417. },
  3418. // 添加格式化时间的辅助方法
  3419. formatTime(seconds) {
  3420. if (!seconds && seconds !== 0) return '03:30'; // 默认显示03:30
  3421. const minutes = Math.floor(seconds / 60);
  3422. const remainingSeconds = seconds % 60;
  3423. return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
  3424. },
  3425. // 添加获取问题数据的方法
  3426. fetchQuestions() {
  3427. this.loading = true;
  3428. // 获取tenant_id,如果没有则使用默认值1
  3429. const tenant_id = JSON.parse(uni.getStorageSync('userInfo')).tenant_id || '1';
  3430. // 获取当前选择的职位ID
  3431. let position_id = 1; // 默认值
  3432. try {
  3433. const selectedJob = JSON.parse(uni.getStorageSync('selectedJob') || '{}');
  3434. if (selectedJob && selectedJob.id) {
  3435. position_id = selectedJob.id;
  3436. console.log('使用选择的职位ID获取问题:', position_id);
  3437. } else {
  3438. console.warn('未找到选择的职位信息,使用默认职位ID:', position_id);
  3439. }
  3440. } catch (e) {
  3441. console.error('解析职位信息失败:', e);
  3442. }
  3443. // 构建完整的请求URL,便于调试
  3444. const timestamp = Date.now();
  3445. const requestUrl = `${apiBaseUrl}/api/wechat/open_questions/?position_id=${position_id}&tenant_id=${tenant_id}&question_form=0&_t=${timestamp}`;
  3446. console.log('完整的请求URL:', requestUrl);
  3447. uni.request({
  3448. url: requestUrl,
  3449. method: 'GET',
  3450. success: (res) => {
  3451. if (res.data && res.data.code === 2000 && res.data.data && res.data.data.items) {
  3452. console.log('获取问题数据成功:', res.data.data.items);
  3453. // 存储问题数据
  3454. this.questions = res.data.data.items;
  3455. // 处理视频列表和字幕
  3456. this.processQuestionData();
  3457. // 播放介绍视频
  3458. this.playIntroVideo();
  3459. } else {
  3460. console.error('获取问题数据失败:', res.data);
  3461. uni.showToast({
  3462. title: '获取问题数据失败',
  3463. icon: 'none'
  3464. });
  3465. /* // 使用默认视频和字幕
  3466. this.useDefaultVideosAndSubtitles(); */
  3467. }
  3468. },
  3469. fail: (err) => {
  3470. console.error('请求问题数据失败:', err);
  3471. uni.showToast({
  3472. title: '网络错误,请检查网络连接',
  3473. icon: 'none'
  3474. });
  3475. /* // 使用默认视频和字幕
  3476. this.useDefaultVideosAndSubtitles(); */
  3477. },
  3478. complete: () => {
  3479. this.loading = false;
  3480. }
  3481. });
  3482. },
  3483. // 处理问题数据,提取视频URL和字幕
  3484. processQuestionData() {
  3485. // 清空视频列表和字幕
  3486. this.videoList = [];
  3487. // 首先添加介绍视频
  3488. this.videoList.push(this.introVideoUrl);
  3489. // 获取配置数据中的开场白
  3490. const configStr = uni.getStorageSync('configData');
  3491. let openingSpeech = [];
  3492. if (configStr) {
  3493. try {
  3494. const configData = JSON.parse(configStr);
  3495. if (configData && configData.digital_human_opening_speech) {
  3496. // 检查是否为数组格式
  3497. if (Array.isArray(configData.digital_human_opening_speech)) {
  3498. // 将配置数据转换为字幕格式
  3499. openingSpeech = configData.digital_human_opening_speech.map((item, index, arr) => {
  3500. const startTime = index === 0 ? 0 : arr[index - 1].end_time || index * 5;
  3501. const endTime = item.end_time || (index + 1) * 5;
  3502. return {
  3503. startTime,
  3504. endTime,
  3505. text: item.content
  3506. };
  3507. });
  3508. } else if (typeof configData.digital_human_opening_speech === 'string') {
  3509. // 使用新的方法处理字符串类型的开场白
  3510. openingSpeech = this.convertStringToSubtitles(configData.digital_human_opening_speech);
  3511. }
  3512. }
  3513. } catch (error) {
  3514. console.error('解析configData失败:', error);
  3515. }
  3516. }
  3517. // 如果成功获取到开场白配置则使用配置的内容,否则使用默认字幕
  3518. this.subtitles = openingSpeech.length > 0 ? openingSpeech : [
  3519. {
  3520. startTime: 0,
  3521. endTime: 5,
  3522. text: '你好,我是本次面试的面试官,欢迎参加本公司的线上面试!'
  3523. },
  3524. {
  3525. startTime: 5,
  3526. endTime: 13,
  3527. text: '面试预计需要15分钟,请你提前安排在网络良好、光线亮度合适、且相对安静的环境参加这次面试'
  3528. },
  3529. {
  3530. startTime: 13,
  3531. endTime: 20,
  3532. text: '以免影响本次面试的结果。如果你在面试过程中遇到问题,请与我们的招聘人员联系。'
  3533. }
  3534. ];
  3535. console.log('处理后的字幕数据:', this.subtitles);
  3536. // 按照sequence_number排序问题
  3537. const sortedQuestions = [...this.questions].sort((a, b) => a.sequence_number - b.sequence_number);
  3538. // 只处理前5个问题(或者更少,如果问题总数不足5个)
  3539. const questionsToUse = sortedQuestions.slice(0, 5);
  3540. // 为每个问题添加视频URL和字幕
  3541. questionsToUse.forEach((question, index) => {
  3542. if (question.digital_human_video_url) {
  3543. this.videoList.push(question.digital_human_video_url);
  3544. // 创建字幕映射,只保留文本
  3545. const subtitleArray = [{
  3546. startTime: 0,
  3547. endTime: 30, // 延长字幕显示时间到30秒
  3548. text: question.question || question.question
  3549. }];
  3550. const videoIndex = this.videoList.length - 1;
  3551. this[`question${videoIndex}Subtitles`] = subtitleArray;
  3552. // 存储字幕映射
  3553. this.subtitleMap[question.digital_human_video_url] = subtitleArray;
  3554. }
  3555. });
  3556. // 如果没有获取到任何问题视频,使用默认视频
  3557. if (this.videoList.length <= 1) {
  3558. /* this.useDefaultVideosAndSubtitles(); */
  3559. } else {
  3560. console.log('处理后的视频列表:', this.videoList);
  3561. console.log('处理后的字幕:', this.subtitles);
  3562. }
  3563. },
  3564. // 将字符串类型的文本转换为字幕格式
  3565. convertStringToSubtitles(text) {
  3566. if (!text || typeof text !== 'string') {
  3567. return [];
  3568. }
  3569. // 按照标点符号分割文本,保留标点符号
  3570. const sentences = text.split(/([。!?!?])/)
  3571. .filter(part => part.trim() !== '')
  3572. .reduce((acc, part, index, arr) => {
  3573. if (index % 2 === 0) {
  3574. // 文本部分
  3575. const nextPart = arr[index + 1] || '';
  3576. acc.push(part + nextPart);
  3577. }
  3578. return acc;
  3579. }, [])
  3580. .filter(sentence => sentence.trim().length > 0);
  3581. // 如果没有明显的分句标点,按长度分割
  3582. if (sentences.length <= 1) {
  3583. const maxLength = 30; // 每段最大字符数
  3584. const textParts = [];
  3585. for (let i = 0; i < text.length; i += maxLength) {
  3586. textParts.push(text.substring(i, i + maxLength));
  3587. }
  3588. sentences.splice(0, sentences.length, ...textParts);
  3589. }
  3590. // 为每个句子分配时间戳
  3591. let currentStartTime = 0;
  3592. return sentences.map((sentence) => {
  3593. const duration = Math.max(3, Math.ceil(sentence.length / 6)); // 根据文本长度计算时长
  3594. const startTime = currentStartTime;
  3595. const endTime = startTime + duration;
  3596. currentStartTime = endTime;
  3597. return {
  3598. startTime,
  3599. endTime,
  3600. text: sentence.trim()
  3601. };
  3602. });
  3603. },
  3604. // 使用默认视频和字幕(作为备用)
  3605. useDefaultVideosAndSubtitles() {
  3606. console.log('使用默认视频和字幕');
  3607. // 设置默认字幕
  3608. this.subtitles = [
  3609. {
  3610. startTime: 0,
  3611. endTime: 5,
  3612. text: '你好,我是本次面试的面试官,欢迎参加本公司的线上面试!'
  3613. },
  3614. {
  3615. startTime: 5,
  3616. endTime: 13,
  3617. text: '面试预计需要15分钟,请你提前安排在网络良好、光线亮度合适、且相对安静的环境参加这次面试'
  3618. },
  3619. {
  3620. startTime: 13,
  3621. endTime: 20,
  3622. text: '以免影响本次面试的结果。如果你在面试过程中遇到问题,请与我们的招聘人员联系。'
  3623. }
  3624. ];
  3625. // 设置默认问题字幕
  3626. this.question1Subtitles = [{
  3627. startTime: 0,
  3628. endTime: 10,
  3629. text: '请结合您的基本信息与过往履历进行简单的自我介绍,并讲一讲您有哪些优势胜任本岗位:'
  3630. }];
  3631. this.question2Subtitles = [{
  3632. startTime: 0,
  3633. endTime: 4,
  3634. text: '在工作中,你如何确保个人防护装备的正确使用?'
  3635. }];
  3636. this.question3Subtitles = [{
  3637. startTime: 0,
  3638. endTime: 4,
  3639. text: '描述一次你与团队合作改善生产流程的经历。'
  3640. }];
  3641. this.question4Subtitles = [{
  3642. startTime: 0,
  3643. endTime: 6,
  3644. text: '你在团队合作中曾遇到过哪些挑战?如何解决团队内部的分歧?'
  3645. }];
  3646. this.question5Subtitles = [{
  3647. startTime: 0,
  3648. endTime: 5,
  3649. text: '您已完成本次面试全部题目,请问您对于这个岗位还有什么想要了解的吗?'
  3650. }];
  3651. },
  3652. // 播放介绍视频
  3653. playIntroVideo() {
  3654. // 设置第一个视频(介绍视频)
  3655. this.videoUrl = this.videoList[0];
  3656. this.videoPlaying = true;
  3657. this.$nextTick(() => {
  3658. const videoContext = uni.createVideoContext('myVideo', this);
  3659. if (videoContext) {
  3660. videoContext.play();
  3661. }
  3662. });
  3663. },
  3664. // 添加新方法:获取默认问题ID
  3665. getDefaultQuestionId(videoIndex) {
  3666. // 根据视频索引映射到默认问题ID
  3667. switch(videoIndex) {
  3668. case 1: // 第一个问题
  3669. return 10;
  3670. case 2: // 第二个问题
  3671. return 11;
  3672. case 3: // 第三个问题
  3673. return 12;
  3674. case 4: // 第四个问题
  3675. return 13;
  3676. default:
  3677. return 10; // 默认值
  3678. }
  3679. },
  3680. // 添加新方法:根据索引获取当前问题
  3681. getCurrentQuestionByIndex(videoIndex) {
  3682. // 视频索引减1,因为第一个视频是介绍视频
  3683. const questionIndex = videoIndex - 1;
  3684. // 按照sequence_number排序问题
  3685. const sortedQuestions = [...this.questions].sort((a, b) => a.sequence_number - b.sequence_number);
  3686. // 检查索引是否有效
  3687. if (questionIndex >= 0 && questionIndex < sortedQuestions.length) {
  3688. return sortedQuestions[questionIndex];
  3689. }
  3690. return null;
  3691. },
  3692. // 添加新方法:获取当前问题的推荐录制时长
  3693. getCurrentQuestionRecommendedDuration() {
  3694. const currentQuestion = this.getCurrentQuestionByIndex(this.currentVideoIndex);
  3695. if (currentQuestion && currentQuestion.recommended_duration) {
  3696. // 如果问题有推荐时长,使用推荐时长(转换为秒)
  3697. const recommendedDuration = parseInt(currentQuestion.recommended_duration);
  3698. console.log(`使用问题推荐时长: ${recommendedDuration}秒`);
  3699. return recommendedDuration;
  3700. }
  3701. // 如果没有推荐时长,使用默认值300秒(5分钟)
  3702. console.log('使用默认录制时长: 300秒');
  3703. return 300;
  3704. },
  3705. // 添加新方法:重置录制状态,准备重新回答
  3706. resetForRerecording() {
  3707. console.log('重置录制状态,准备重新回答');
  3708. // 重置录制状态
  3709. this.isRecording = false;
  3710. this.showStopRecordingButton = false;
  3711. // 显示"开始回答"按钮
  3712. this.showStartRecordingButton = true;
  3713. // 清除倒计时
  3714. this.clearCountdown();
  3715. // 重置录制计时器
  3716. if (this.recordingTimer) {
  3717. clearInterval(this.recordingTimer);
  3718. this.recordingTimer = null;
  3719. }
  3720. // 重置录制时间显示
  3721. this.recordingTimerCount = 0;
  3722. this.recordingTimeDisplay = '00:00 ';/* / 05:00 */
  3723. // 重新获取当前问题的推荐录制时长
  3724. this.maxRecordingTime = this.getCurrentQuestionRecommendedDuration();
  3725. this.remainingTime = this.maxRecordingTime;
  3726. // 如果是浏览器环境,停止MediaRecorder
  3727. if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
  3728. this.mediaRecorder.stop();
  3729. this.recordedChunks = [];
  3730. }
  3731. // 如果是小程序环境,停止相机录制
  3732. if (this.cameraContext) {
  3733. this.cameraContext.stopRecord({
  3734. success: () => {
  3735. console.log('相机录制已停止');
  3736. },
  3737. fail: (err) => {
  3738. console.error('停止相机录制失败:', err);
  3739. }
  3740. });
  3741. }
  3742. // 重置问题重试次数映射
  3743. this.questionRetryMap = {};
  3744. },
  3745. // 修改 playLowScoreVideo 方法,优化字幕显示并添加重试次数限制
  3746. playLowScoreVideo() {
  3747. console.log('播放低分提示视频');
  3748. // 获取当前问题的重试次数
  3749. const currentQuestionId = this.getCurrentQuestionByIndex(this.currentVideoIndex)?.id;
  3750. if (!currentQuestionId) {
  3751. console.error('无法获取当前问题ID');
  3752. return;
  3753. }
  3754. // 初始化或增加重试次数
  3755. if (!this.questionRetryMap[currentQuestionId]) {
  3756. this.questionRetryMap[currentQuestionId] = 1;
  3757. } else {
  3758. this.questionRetryMap[currentQuestionId]++;
  3759. }
  3760. // 检查是否超过最大重试次数
  3761. if (this.questionRetryMap[currentQuestionId] > this.maxQuestionRetries) {
  3762. console.log(`问题 ${currentQuestionId} 已超过最大重试次数,自动进入下一题`);
  3763. // 重置低分视频状态
  3764. this.isPlayingLowScoreVideo = false;
  3765. // 重置追问相关状态
  3766. this.isFollowUpQuestion = false;
  3767. this.currentFollowUpQuestion = null;
  3768. this.followUpQuestion = '';
  3769. this.parentQuestion = '';
  3770. // 增加视频索引,进入下一题
  3771. this.currentVideoIndex++;
  3772. // 检查是否还有下一题
  3773. if (this.currentVideoIndex < this.videoList.length) {
  3774. // 获取下一题的字幕
  3775. const nextQuestion = this.getCurrentQuestionByIndex(this.currentVideoIndex);
  3776. if (nextQuestion) {
  3777. this.currentSubtitle = nextQuestion.question || nextQuestion.question;
  3778. }
  3779. // 播放下一题的视频
  3780. this.videoUrl = this.videoList[this.currentVideoIndex];
  3781. this.videoPlaying = true;
  3782. this.$nextTick(() => {
  3783. const videoContext = uni.createVideoContext('myVideo', this);
  3784. if (videoContext) {
  3785. videoContext.play();
  3786. }
  3787. });
  3788. } else {
  3789. // 如果没有下一题,结束面试
  3790. this.finishInterview();
  3791. }
  3792. return;
  3793. }
  3794. // 标记正在播放低分提示视频
  3795. this.isPlayingLowScoreVideo = true;
  3796. // 隐藏其他按钮
  3797. this.showStartRecordingButton = false;
  3798. this.showStopRecordingButton = false;
  3799. this.showRerecordButton = false;
  3800. // 设置视频URL
  3801. this.videoUrl = this.lowScoreVideoUrl;
  3802. this.videoPlaying = true;
  3803. // 保存当前问题的字幕
  3804. const currentQuestion = this.getCurrentQuestionByIndex(this.currentVideoIndex);
  3805. const originalSubtitle = currentQuestion ? (currentQuestion.question || currentQuestion.question) : this.currentSubtitle;
  3806. // 清除现有字幕
  3807. this.currentSubtitle = '';
  3808. // 使用 nextTick 确保 DOM 更新后再播放视频
  3809. this.$nextTick(() => {
  3810. const videoContext = uni.createVideoContext('myVideo', this);
  3811. if (videoContext) {
  3812. videoContext.play();
  3813. // 视频开始播放后短暂延迟显示字幕,确保用户注意到
  3814. setTimeout(() => {
  3815. // 设置低分提示视频的字幕
  3816. this.currentSubtitle = '我未听清楚您在说什么,请您再说一遍!';
  3817. // 创建专门的字幕数组用于低分提示视频
  3818. this.lowScoreVideoSubtitles = [
  3819. {
  3820. startTime: 0,
  3821. endTime: 30,
  3822. text: '我未听清楚您在说什么,请您再说一遍!',
  3823. translation: 'I didn\'t quite catch what you said, could you please repeat it?'
  3824. }
  3825. ];
  3826. }, 500);
  3827. }
  3828. });
  3829. // 保存原始字幕信息到实例属性,以便在视频结束时恢复
  3830. this.originalQuestionSubtitle = originalSubtitle;
  3831. },
  3832. // 添加新方法:处理重新录制按钮点击
  3833. handleRerecordButtonClick() {
  3834. console.log('点击重新录制按钮');
  3835. // 增加重试计数
  3836. this.retryCount++;
  3837. console.log(`当前重试次数: ${this.retryCount}/${this.maxRetryAttempts}`);
  3838. // 隐藏重新录制按钮
  3839. this.showRerecordButton = false;
  3840. // 直接调用开始录制的方法
  3841. this.handleStartRecordingClick();
  3842. },
  3843. // 页面卸载时关闭WebSocket连接
  3844. onUnload() {
  3845. console.log('页面卸载,关闭WebSocket连接');
  3846. this.cleanupPersonDetectionWebSocket();
  3847. // 清理其他资源
  3848. this.stopUserCamera();
  3849. this.clearCountdown();
  3850. // 清理录制相关定时器
  3851. if (this.recordingTimer) {
  3852. clearInterval(this.recordingTimer);
  3853. this.recordingTimer = null;
  3854. }
  3855. // 停止MediaRecorder
  3856. if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
  3857. this.mediaRecorder.stop();
  3858. }
  3859. // 关闭屏幕常亮
  3860. uni.setKeepScreenOn({
  3861. keepScreenOn: false
  3862. });
  3863. },
  3864. // 页面隐藏时关闭WebSocket连接
  3865. onHide() {
  3866. console.log('页面隐藏,关闭WebSocket连接');
  3867. // 完全关闭WebSocket连接和相关定时器
  3868. this.cleanupPersonDetectionWebSocket();
  3869. // 如果正在录制,给用户提示
  3870. if (this.isRecording) {
  3871. console.log('页面隐藏时正在录制,录制将继续');
  3872. // 可以选择暂停录制或者给用户提示
  3873. uni.showToast({
  3874. title: '请不要离开面试页面',
  3875. icon: 'none',
  3876. duration: 2000
  3877. });
  3878. }
  3879. },
  3880. // 页面显示时重新初始化WebSocket连接
  3881. onShow() {
  3882. console.log('identity-verify页面onShow');
  3883. console.log('当前本地存储中的职位信息:', uni.getStorageSync('selectedJob'));
  3884. // 每次页面显示时重新获取问题
  3885. this.fetchQuestions();
  3886. // this.fetchFollowUpQuestions(); // 添加获取追问问题的调用
  3887. // 重新初始化WebSocket连接(仅在小程序环境中)
  3888. const systemInfo = uni.getSystemInfoSync();
  3889. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
  3890. if (isMiniProgram) {
  3891. // 如果WebSocket未连接,重新初始化
  3892. if (!this.personDetectionSocket) {
  3893. console.log('重新初始化WebSocket连接');
  3894. this.initPersonDetectionWebSocket();
  3895. }
  3896. // 如果WebSocket已连接但检测定时器被停止,重新启动检测
  3897. else if (!this.personDetectionInterval) {
  3898. console.log('重新启动人脸检测定时器');
  3899. this.startPersonDetectionInterval();
  3900. }
  3901. }
  3902. uni.hideHomeButton(); // 隐藏左上角返回按钮
  3903. },
  3904. // 添加新方法:阻止视频控制
  3905. preventVideoControl(e) {
  3906. // 阻止默认行为和事件冒泡
  3907. e.preventDefault();
  3908. e.stopPropagation();
  3909. console.log('阻止视频控制操作');
  3910. return false;
  3911. },
  3912. // 添加获取追问问题的方法
  3913. fetchFollowUpQuestions() {
  3914. // 获取tenant_id,如果没有则使用默认值1
  3915. const tenant_id = JSON.parse(uni.getStorageSync('userInfo')).tenant_id || '1';
  3916. // 获取当前选择的职位ID
  3917. let position_id = 1; // 默认值
  3918. try {
  3919. const selectedJob = JSON.parse(uni.getStorageSync('selectedJob') || '{}');
  3920. if (selectedJob && selectedJob.id) {
  3921. position_id = selectedJob.id;
  3922. console.log('使用选择的职位ID获取追问问题:', position_id);
  3923. } else {
  3924. console.warn('未找到选择的职位信息,使用默认职位ID:', position_id);
  3925. }
  3926. } catch (e) {
  3927. console.error('解析职位信息失败:', e);
  3928. }
  3929. // 构建完整的请求URL,便于调试
  3930. const timestamp = Date.now();
  3931. const requestUrl = `${apiBaseUrl}/api/wechat/open_questions/?position_id=${position_id}&tenant_id=${tenant_id}&question_form=5&_t=${timestamp}`;
  3932. console.log('获取追问问题的请求URL:', requestUrl);
  3933. uni.request({
  3934. url: requestUrl,
  3935. method: 'GET',
  3936. success: (res) => {
  3937. if (res.data && res.data.code === 2000 && res.data.data && res.data.data.items) {
  3938. console.log('获取追问问题数据成功:', res.data.data.items);
  3939. // 存储追问问题数据,并确保每个问题都有question_form=5标记
  3940. this.followUpQuestions = res.data.data.items.map(item => ({
  3941. ...item,
  3942. question_form: 5 // 确保每个追问问题都有正确的question_form值
  3943. }));
  3944. // 处理追问问题数据,建立与父问题的关联
  3945. this.processFollowUpQuestions();
  3946. } else {
  3947. console.error('获取追问问题数据失败:', res.data);
  3948. // 初始化为空数组,避免undefined错误
  3949. this.followUpQuestions = [];
  3950. }
  3951. },
  3952. fail: (err) => {
  3953. console.error('请求追问问题数据失败:', err);
  3954. // 初始化为空数组,避免undefined错误
  3955. this.followUpQuestions = [];
  3956. }
  3957. });
  3958. },
  3959. // 改进处理追问问题数据的方法
  3960. processFollowUpQuestions() {
  3961. if (!this.followUpQuestions || this.followUpQuestions.length === 0) {
  3962. console.log('没有追问问题数据');
  3963. this.followUpQuestions = []; // 确保是数组
  3964. return;
  3965. }
  3966. console.log('处理追问问题数据,总数:', this.followUpQuestions.length);
  3967. // 过滤掉没有parent_question_id的追问问题
  3968. this.followUpQuestions = this.followUpQuestions.filter(q => q.parent_question_id);
  3969. // 可以在这里进行额外的数据处理,如按照parent_question_id分组等
  3970. const parentQuestionIds = new Set();
  3971. this.followUpQuestions.forEach(question => {
  3972. if (question.parent_question_id) {
  3973. parentQuestionIds.add(question.parent_question_id);
  3974. }
  3975. });
  3976. console.log('有追问的父问题ID:', Array.from(parentQuestionIds));
  3977. // 初始化已播放追问记录对象
  3978. this.hasPlayedFollowUp = {};
  3979. },
  3980. // 修改检查并播放追问问题的方法
  3981. checkAndPlayFollowUpQuestion(parentQuestionId) {
  3982. console.log('检查是否有追问问题,父问题ID:', parentQuestionId);
  3983. // 如果正在等待用户回答,不进行任何操作
  3984. if (this.isWaitingForAnswer) {
  3985. console.log('正在等待用户回答,暂不处理追问');
  3986. return;
  3987. }
  3988. // 超过追问上限则直接进入下一题
  3989. if (!this.canAskMoreFollowUps(parentQuestionId)) {
  3990. console.log('追问次数已达上限,进入下一题');
  3991. this.proceedToNextQuestion();
  3992. return;
  3993. }
  3994. if (!parentQuestionId) {
  3995. console.warn('没有父问题ID,无法检查追问问题');
  3996. this.proceedToNextQuestion();
  3997. return;
  3998. }
  3999. // 如果已经播放过这个问题的追问,则直接进入下一个问题
  4000. if (this.hasPlayedFollowUp[parentQuestionId]) {
  4001. console.log('已经播放过此问题的追问,直接进入下一个问题');
  4002. this.retryCount = 0;
  4003. this.proceedToNextQuestion();
  4004. return;
  4005. }
  4006. // 查找对应的追问问题
  4007. const followUpQuestion = this.followUpQuestions.find(q =>
  4008. q.parent_question_id === parentQuestionId &&
  4009. q.digital_human_video_url &&
  4010. q.question_form === 5
  4011. );
  4012. if (followUpQuestion) {
  4013. console.log('找到追问问题:', followUpQuestion);
  4014. // 检查录制时长
  4015. const recordingDuration = this.getRecordingDuration();
  4016. const lowScoreDuration = 7; // 低分阈值时长(秒),少于7秒视为低分
  4017. const minDuration = 3; // 最小录制时长阈值(秒)
  4018. // 如果录制时间少于最小时长或者在最小时长和低分阈值之间,播放"未听清楚"提示视频
  4019. if (recordingDuration < lowScoreDuration) {
  4020. let message = recordingDuration < minDuration ?
  4021. `录制时间 ${recordingDuration} 秒,少于最小时长 ${minDuration} 秒` :
  4022. `录制时间 ${recordingDuration} 秒,少于标准时长 ${lowScoreDuration} 秒`;
  4023. console.log(message + ',将播放低分提示视频');
  4024. // 增加重试次数
  4025. this.retryCount++;
  4026. // 设置需要播放低分提示视频
  4027. this.needPlayLowScoreVideo = true;
  4028. // 播放低分提示视频
  4029. this.playLowScoreVideo();
  4030. return;
  4031. }
  4032. // 如果录制时长足够,重置重试次数
  4033. this.retryCount = 0;
  4034. // 标记此追问已播放
  4035. this.hasPlayedFollowUp[parentQuestionId] = true;
  4036. // 标记当前是追问问题
  4037. this.isFollowUpQuestion = true;
  4038. // 记录当前父问题ID
  4039. this.currentParentQuestionId = parentQuestionId;
  4040. // 保存当前追问问题的完整信息
  4041. this.currentFollowUpQuestion = followUpQuestion;
  4042. // 播放追问问题视频
  4043. this.playFollowUpQuestionVideo(followUpQuestion);
  4044. } else {
  4045. console.log('没有找到对应的追问问题,继续下一个问题');
  4046. this.retryCount = 0;
  4047. this.proceedToNextQuestion();
  4048. }
  4049. },
  4050. // 修改播放追问问题视频的方法
  4051. playFollowUpQuestionVideo(followUpQuestion) {
  4052. console.log('播放追问问题视频:', followUpQuestion.digital_human_video_url);
  4053. // 保存父问题内容
  4054. this.parentQuestion = this.currentSubtitle;
  4055. this.videoUrl = followUpQuestion.digital_human_video_url;
  4056. this.videoPlaying = true;
  4057. this.isFollowUpQuestion = true;
  4058. this.currentFollowUpQuestion = followUpQuestion;
  4059. // 设置追问问题的字幕
  4060. const followUpSubtitles = [{
  4061. startTime: 0,
  4062. endTime: 60, // 延长显示时间到60秒
  4063. text: followUpQuestion.question || followUpQuestion.question
  4064. }];
  4065. const subtitleKey = `followUpSubtitles_${followUpQuestion.id}`;
  4066. this[subtitleKey] = followUpSubtitles;
  4067. this.$nextTick(() => {
  4068. const videoContext = uni.createVideoContext('myVideo', this);
  4069. if (videoContext) {
  4070. videoContext.play();
  4071. // 更新当前字幕为追问内容
  4072. this.currentSubtitle = followUpSubtitles[0].text;
  4073. }
  4074. });
  4075. },
  4076. // 添加作废面试的方法
  4077. invalidateInterview() {
  4078. // 停止录制(如果正在录制)
  4079. if (this.isRecording) {
  4080. this.stopRecordingAnswer();
  4081. }
  4082. // 清除所有计时器
  4083. if (this.recordingTimer) {
  4084. clearInterval(this.recordingTimer);
  4085. }
  4086. // 重置状态
  4087. this.isRecording = false;
  4088. this.showStopRecordingButton = false;
  4089. this.showStartRecordingButton = false;
  4090. // 显示作废提示
  4091. // uni.showToast({
  4092. // title: 'Interview invalidated',
  4093. // icon: 'none',
  4094. // duration: 2000
  4095. // });
  4096. // 延迟后返回上一页
  4097. setTimeout(() => {
  4098. uni.switchTab({
  4099. url: '/pages/index/index'
  4100. });
  4101. }, 500);
  4102. },
  4103. initPersonDetectionWebSocket() {
  4104. if (this.personDetectionSocket) {
  4105. this.cleanupPersonDetectionWebSocket();
  4106. }
  4107. try {
  4108. this.personDetectionSocket = uni.connectSocket({
  4109. url: `${personDetectionWsUrl}/ws/interview-room/room_${uni.getStorageSync('appId')}/${uni.getStorageSync('appId')}/`,
  4110. success: () => {
  4111. console.log('WebSocket connection initiated');
  4112. },
  4113. fail: (error) => {
  4114. console.error('WebSocket connection failed:', error);
  4115. }
  4116. });
  4117. this.personDetectionSocket.onOpen(() => {
  4118. console.log('WebSocket connection opened');
  4119. this.startPersonDetectionInterval();
  4120. });
  4121. this.personDetectionSocket.onError((error) => {
  4122. console.error('WebSocket error:', error);
  4123. this.cleanupPersonDetectionWebSocket();
  4124. });
  4125. this.personDetectionSocket.onClose(() => {
  4126. console.log('WebSocket connection closed');
  4127. this.cleanupPersonDetectionWebSocket();
  4128. });
  4129. this.personDetectionSocket.onMessage((res) => {
  4130. try {
  4131. const data = JSON.parse(res.data);
  4132. /* console.log('data1', data); */
  4133. if (data.type === 'person_detection_result') {
  4134. this.handlePersonDetectionResult(data);
  4135. }
  4136. } catch (error) {
  4137. console.error('Error parsing WebSocket message:', error);
  4138. }
  4139. });
  4140. } catch (error) {
  4141. console.error('Error initializing WebSocket:', error);
  4142. this.cleanupPersonDetectionWebSocket();
  4143. }
  4144. },
  4145. startPersonDetectionInterval() {
  4146. if (this.personDetectionInterval) {
  4147. clearInterval(this.personDetectionInterval);
  4148. }
  4149. this.personDetectionInterval = setInterval(() => {
  4150. try {
  4151. if (!this.personDetectionSocket || !this.cameraContext) {
  4152. console.warn('人脸检测:相机上下文或WebSocket连接未就绪');
  4153. return;
  4154. }
  4155. this.cameraContext.takePhoto({
  4156. quality: 'low',
  4157. success: (res) => {
  4158. try {
  4159. const tempFilePath = res.tempImagePath;
  4160. if (!tempFilePath) {
  4161. console.warn('人脸检测:未获取到有效的图片路径');
  4162. }
  4163. uni.getFileSystemManager().readFile({
  4164. filePath: tempFilePath,
  4165. encoding: 'base64',
  4166. success: (res) => {
  4167. try {
  4168. const base64Image = res.data;
  4169. if (!this.personDetectionSocket || this.personDetectionSocket.readyState !== 1) {
  4170. console.warn('人脸检测:WebSocket连接已断开或未就绪');
  4171. return;
  4172. }
  4173. this.personDetectionSocket.send({
  4174. data: JSON.stringify({
  4175. type: 'person_detection',
  4176. image_data: base64Image
  4177. })
  4178. });
  4179. } catch (wsError) {
  4180. console.error('人脸检测:发送WebSocket数据时出错:', wsError);
  4181. }
  4182. },
  4183. fail: (error) => {
  4184. console.error('人脸检测:读取图片文件失败:', error);
  4185. }
  4186. });
  4187. } catch (fileError) {
  4188. console.error('人脸检测:处理图片文件时出错:', fileError);
  4189. }
  4190. },
  4191. fail: (error) => {
  4192. console.error('人脸检测:拍照失败:', error);
  4193. }
  4194. });
  4195. } catch (mainError) {
  4196. console.error('人脸检测:主流程执行出错:', mainError);
  4197. }
  4198. }, 5000);
  4199. },
  4200. cleanupPersonDetectionWebSocket() {
  4201. if (this.personDetectionInterval) {
  4202. clearInterval(this.personDetectionInterval);
  4203. this.personDetectionInterval = null;
  4204. }
  4205. if (this.personDetectionSocket) {
  4206. try {
  4207. this.personDetectionSocket.close();
  4208. } catch (error) {
  4209. console.error('Error closing WebSocket:', error);
  4210. }
  4211. this.personDetectionSocket = null;
  4212. }
  4213. },
  4214. handlePersonDetectionResult(data) {
  4215. console.log('data', data);
  4216. /* console.log(data.data.detection.has_person);
  4217. console.log(data.data.identity.status);//identity_verified */
  4218. /* // 首先检查是否有人
  4219. if (!data.data.detection.has_person) {
  4220. this.showPageWarning = true;
  4221. uni.showToast({
  4222. title: '请勿离开摄像头',
  4223. icon: 'none',
  4224. duration: 3000
  4225. });
  4226. // 添加震动反馈
  4227. uni.vibrateLong({
  4228. success: function () {
  4229. console.log('Vibration successful');
  4230. },
  4231. fail: function (err) {
  4232. console.error('Vibration failed:', err);
  4233. }
  4234. });
  4235. setTimeout(() => {
  4236. this.showPageWarning = false;
  4237. }, 3000);
  4238. }
  4239. // 然后检查身份验证状态
  4240. else */ if (data.data.identity.status == "no_face") {
  4241. this.showPageWarning = true;
  4242. uni.showToast({/* data.data.identity.message */
  4243. title: '请保持面部完整出现在镜头内',
  4244. icon: 'none',
  4245. duration: 3000
  4246. });
  4247. uni.vibrateLong({
  4248. success: function () {
  4249. console.log('Vibration successful');
  4250. },
  4251. fail: function (err) {
  4252. console.error('Vibration failed:', err);
  4253. }
  4254. });
  4255. setTimeout(() => {
  4256. this.showPageWarning = false;
  4257. }, 3000);
  4258. }
  4259. },
  4260. // 进入追问模式
  4261. enterFollowUpMode() {
  4262. this.isFollowUpMode = true;
  4263. this.mainQuestionIndex = this.currentVideoIndex; // 保存当前主问题的索引
  4264. console.log('进入追问模式,保存主问题索引:', this.mainQuestionIndex);
  4265. },
  4266. // 修改 handleFollowUpQuestion 方法
  4267. async handleFollowUpQuestion(questionData) {
  4268. console.log('处理追问:', questionData);
  4269. this.enterFollowUpMode();
  4270. console.log('处理追问问题数据:', questionData);
  4271. // 检查数据完整性
  4272. if (!questionData || !questionData.follow_up_voice_url || !questionData.follow_up_question) {
  4273. console.error('追问数据不完整:', questionData);
  4274. uni.showToast({
  4275. title: '获取追问数据失败',
  4276. icon: 'none'
  4277. });
  4278. return;
  4279. }
  4280. // 保存父问题
  4281. this.parentQuestion = questionData.original_question || '';
  4282. // 确保音频URL正确
  4283. let audioUrl = '';
  4284. if (questionData.follow_up_voice_url.direct_url) {
  4285. audioUrl = questionData.follow_up_voice_url.direct_url;
  4286. } else if (questionData.follow_up_voice_url.file_url) {
  4287. audioUrl = questionData.follow_up_voice_url.file_url;
  4288. }
  4289. // 确保音频URL是完整的
  4290. if (!audioUrl.startsWith('http')) {
  4291. audioUrl = apiBaseUrl + audioUrl;
  4292. }
  4293. console.log('处理后的音频URL:', audioUrl);
  4294. // 创建追问问题对象
  4295. const followUpQuestionObj = {
  4296. id: Date.now(),
  4297. question: questionData.follow_up_question.trim(), // 去除可能的空白字符
  4298. audioUrl: audioUrl,
  4299. originalQuestion: questionData.original_question,
  4300. sessionId: questionData.session_id
  4301. };
  4302. console.log('创建的追问问题对象:', followUpQuestionObj);
  4303. // 添加到追问问题列表
  4304. this.followUpQuestions.push(followUpQuestionObj);
  4305. this.currentFollowUpIndex = this.followUpQuestions.length - 1;
  4306. // 更新当前追问问题
  4307. this.followUpQuestion = followUpQuestionObj.question;
  4308. this.followUpAudioUrl = followUpQuestionObj.audioUrl;
  4309. // 标记当前是追问问题
  4310. this.isFollowUpQuestion = true;
  4311. this.currentFollowUpQuestion = followUpQuestionObj;
  4312. // 显示字幕
  4313. this.showSubtitle(followUpQuestionObj.question, true);
  4314. // 等待音频播放完成
  4315. try {
  4316. await this.playFollowUpAudio();
  4317. console.log('音频播放完成,准备录制回答');
  4318. // 开始准备录制回答
  4319. this.prepareToAnswer(true, followUpQuestionObj);
  4320. } catch (error) {
  4321. console.error('音频播放失败:', error);
  4322. // 即使音频播放失败,也继续准备录制回答
  4323. this.prepareToAnswer(true, followUpQuestionObj);
  4324. }
  4325. },
  4326. // 播放追问音频
  4327. async playFollowUpAudio() {
  4328. return new Promise((resolve, reject) => {
  4329. console.log('开始播放追问音频, URL:', this.followUpAudioUrl);
  4330. // 检查音频URL
  4331. if (!this.followUpAudioUrl) {
  4332. console.error('没有音频URL');
  4333. reject(new Error('没有音频URL'));
  4334. return;
  4335. }
  4336. // 显示加载提示
  4337. uni.showLoading({
  4338. title: '思考中...'
  4339. });
  4340. // 停止并销毁之前的音频实例
  4341. this.stopAndDestroyAudio();
  4342. try {
  4343. // 创建新的音频上下文
  4344. const innerAudioContext = uni.createInnerAudioContext();
  4345. this.audioContext = innerAudioContext;
  4346. // 设置音频属性
  4347. innerAudioContext.autoplay = true;
  4348. innerAudioContext.obeyMuteSwitch = false;
  4349. innerAudioContext.volume = 1.0;
  4350. // 监听音频加载状态
  4351. innerAudioContext.onCanplay(() => {
  4352. console.log('音频可以播放');
  4353. uni.hideLoading();
  4354. this.isAudioPlaying = true;
  4355. /* uni.showToast({
  4356. title: '正在播放追问',
  4357. icon: 'none',
  4358. duration: 2000
  4359. }); */
  4360. });
  4361. // 监听音频播放完成
  4362. innerAudioContext.onEnded(() => {
  4363. console.log('追问音频播放完成');
  4364. this.isAudioPlaying = false;
  4365. resolve();
  4366. // 延迟清理资源,确保不会影响播放完成的回调
  4367. setTimeout(() => {
  4368. this.stopAndDestroyAudio();
  4369. // 音频播放完成后,自动准备录制回答
  4370. this.prepareToAnswer(true, this.currentFollowUpQuestion);
  4371. }, 100);
  4372. });
  4373. // 监听音频播放错误
  4374. innerAudioContext.onError((res) => {
  4375. console.error('音频播放错误:', res);
  4376. this.isAudioPlaying = false;
  4377. uni.hideLoading();
  4378. uni.showToast({
  4379. title: '音频播放失败',
  4380. icon: 'none'
  4381. });
  4382. reject(res);
  4383. this.stopAndDestroyAudio();
  4384. });
  4385. // 设置音频源
  4386. console.log('设置音频源:', this.followUpAudioUrl);
  4387. innerAudioContext.src = this.followUpAudioUrl;
  4388. } catch (error) {
  4389. console.error('创建或播放音频失败:', error);
  4390. this.isAudioPlaying = false;
  4391. uni.hideLoading();
  4392. uni.showToast({
  4393. title: '音频播放失败',
  4394. icon: 'none'
  4395. });
  4396. this.stopAndDestroyAudio();
  4397. reject(error);
  4398. }
  4399. });
  4400. },
  4401. // 停止并销毁音频
  4402. stopAndDestroyAudio() {
  4403. if (!this.audioContext) {
  4404. return;
  4405. }
  4406. const ctx = this.audioContext;
  4407. this.audioContext = null; // 先清除引用
  4408. try {
  4409. if (this.isAudioPlaying) {
  4410. ctx.stop();
  4411. }
  4412. } catch (error) {
  4413. console.error('停止音频播放失败:', error);
  4414. }
  4415. try {
  4416. ctx.destroy();
  4417. } catch (error) {
  4418. console.error('销毁音频实例失败:', error);
  4419. }
  4420. this.isAudioPlaying = false;
  4421. },
  4422. // 显示字幕
  4423. showSubtitle(text, isFollowUp = true) {
  4424. console.log('显示字幕:', text);
  4425. this.subtitleText = text;
  4426. this.showSubtitleText = true;
  4427. this.isFollowUpQuestion = isFollowUp;
  4428. // 确保字幕显示在界面上
  4429. this.$nextTick(() => {
  4430. // 如果需要,可以添加字幕动画效果
  4431. setTimeout(() => {
  4432. this.showSubtitleText = false;
  4433. }, 8000); // 8秒后隐藏字幕
  4434. });
  4435. },
  4436. // 显示问题对话框
  4437. showQuestionDialog() {
  4438. if (this.followUpQuestion) {
  4439. uni.showModal({
  4440. title: '追问问题',
  4441. content: this.followUpQuestion,
  4442. showCancel: false,
  4443. success: () => {
  4444. // 准备开始回答
  4445. this.prepareToAnswer(true, this.followUpQuestions[this.currentFollowUpIndex]);
  4446. }
  4447. });
  4448. }
  4449. },
  4450. // 显示面试官思考中loading
  4451. showThinkingLoading() {
  4452. this.isThinking = true;
  4453. uni.showLoading({
  4454. title: '面试官正在思考中',
  4455. mask: false
  4456. });
  4457. },
  4458. // 隐藏面试官思考中loading
  4459. hideThinkingLoading() {
  4460. this.isThinking = false;
  4461. uni.hideLoading();
  4462. if (this.thinkingTimer) {
  4463. clearTimeout(this.thinkingTimer);
  4464. this.thinkingTimer = null;
  4465. }
  4466. },
  4467. // 处理视频完成
  4468. handleVideoCompletion(jobId) {
  4469. this.isVideoSwitching = false; // 重置切换状态锁
  4470. // 延迟执行跳转,确保资源清理完成
  4471. /* setTimeout(() => { */
  4472. // 如果职位ID为9,跳转到interview-question页面
  4473. if (jobId === 9) {
  4474. uni.navigateTo({
  4475. url: '/pages/interview-question/interview-question',
  4476. success: () => {
  4477. console.log('成功跳转到interview-question页面');
  4478. },
  4479. fail: (err) => {
  4480. console.error('跳转到interview-question页面失败:', err);
  4481. // 如果跳转失败,尝试使用redirectTo
  4482. uni.redirectTo({
  4483. url: '/pages/interview-question/interview-question',
  4484. fail: (redirectErr) => {
  4485. console.error('重定向到interview-question页面也失败:', redirectErr);
  4486. // 如果所有跳转方式都失败,尝试返回上一页
  4487. uni.navigateBack({
  4488. delta: 1
  4489. });
  4490. }
  4491. });
  4492. }
  4493. });
  4494. } else {
  4495. // 其他职位ID跳转到camera页面
  4496. uni.navigateTo({
  4497. url: '/pages/camera/camera',
  4498. success: () => {
  4499. console.log('成功跳转到camera页面');
  4500. },
  4501. fail: (err) => {
  4502. console.error('跳转到camera页面失败:', err);
  4503. // 如果跳转失败,尝试使用redirectTo
  4504. uni.redirectTo({
  4505. url: '/pages/camera/camera',
  4506. fail: (redirectErr) => {
  4507. console.error('重定向到camera页面也失败:', redirectErr);
  4508. // 最后尝试使用switchTab(如果camera是tabBar页面)
  4509. uni.switchTab({
  4510. url: '/pages/camera/camera',
  4511. fail: (switchErr) => {
  4512. console.error('所有跳转方式都失败:', switchErr);
  4513. // 如果所有跳转方式都失败,尝试返回上一页
  4514. uni.navigateBack({
  4515. delta: 1
  4516. });
  4517. }
  4518. });
  4519. }
  4520. });
  4521. }
  4522. });
  4523. }
  4524. /* }, 200); */
  4525. },
  4526. },
  4527. computed: {
  4528. // 计算进度比例
  4529. progressRatio() {
  4530. return this.recordingTimerCount / this.maxRecordingTime;
  4531. },
  4532. // 右半圆旋转角度
  4533. half1Turn() {
  4534. // 初始状态为0度,小于50%时,右半圆按比例旋转
  4535. if (this.progressRatio <= 0.5) {
  4536. return this.progressRatio * 2 * 180;
  4537. } else {
  4538. // 大于50%时,右半圆固定在180度
  4539. return 180;
  4540. }
  4541. },
  4542. // 左半圆旋转角度
  4543. half2Turn() {
  4544. // 小于50%时,左半圆固定在0度
  4545. if (this.progressRatio <= 0.5) {
  4546. return 0;
  4547. } else {
  4548. // 大于50%时,左半圆按超出50%的比例旋转
  4549. return (this.progressRatio - 0.5) * 2 * 180;
  4550. }
  4551. },
  4552. // 修改进度百分比的计算方式
  4553. progressPercent() {
  4554. // 将时间进度转换为百分比(0-100)
  4555. return Math.min(Math.round((this.recordingTimerCount / this.maxRecordingTime) * 100), 100);
  4556. },
  4557. // 添加总题数计算属性
  4558. totalQuestions() {
  4559. // 获取问题总数,不包括介绍视频
  4560. return this.questions.length || 5; // 如果没有问题数据,默认显示5
  4561. }
  4562. }
  4563. }
  4564. </script>
  4565. <style scoped>
  4566. .subtitle-container {
  4567. position: fixed;
  4568. bottom: 20%;
  4569. left: 0;
  4570. right: 0;
  4571. display: flex;
  4572. justify-content: center;
  4573. align-items: center;
  4574. z-index: 1000;
  4575. }
  4576. .subtitle-text {
  4577. background-color: rgba(0, 0, 0, 0.7);
  4578. color: white;
  4579. padding: 10px 20px;
  4580. border-radius: 5px;
  4581. font-size: 16px;
  4582. max-width: 80%;
  4583. text-align: center;
  4584. animation: fadeIn 0.5s ease-in-out;
  4585. }
  4586. @keyframes fadeIn {
  4587. from {
  4588. opacity: 0;
  4589. transform: translateY(20px);
  4590. }
  4591. to {
  4592. opacity: 1;
  4593. transform: translateY(0);
  4594. }
  4595. }
  4596. .identity-verify-container {
  4597. padding: 0;
  4598. max-width: 100%;
  4599. margin: 0 auto;
  4600. height: 100vh;
  4601. display: flex;
  4602. flex-direction: column;
  4603. background-color: #f5f5f5;
  4604. transition: all 0.3s ease;
  4605. position: relative;
  4606. }
  4607. .page-warning {
  4608. animation: page-warning-flash 1s ease-in-out infinite;
  4609. }
  4610. @keyframes page-warning-flash {
  4611. 0% {
  4612. background-color: rgba(255, 0, 0, 0.2);
  4613. box-shadow: 0 0 20px rgba(255, 0, 0, 0.3);
  4614. }
  4615. 50% {
  4616. background-color: rgba(255, 0, 0, 0.1);
  4617. box-shadow: 0 0 10px rgba(255, 0, 0, 0.2);
  4618. }
  4619. 100% {
  4620. background-color: rgba(255, 0, 0, 0.2);
  4621. box-shadow: 0 0 20px rgba(255, 0, 0, 0.3);
  4622. }
  4623. }
  4624. .digital-human-container {
  4625. position: relative;
  4626. width: 100%;
  4627. height: 100vh;
  4628. overflow: hidden;
  4629. background-color: #f0f0f0;
  4630. }
  4631. .digital-human-video {
  4632. width: 100%;
  4633. height: 100%;
  4634. margin-top: 32px;
  4635. display: flex;
  4636. justify-content: center;
  4637. align-items: center;
  4638. }
  4639. /* 用户摄像头容器样式 */
  4640. .user-camera-container {
  4641. position: absolute;
  4642. top: 100px;
  4643. right: 5px;
  4644. width: 110px;
  4645. height: 160px;
  4646. border-radius: 4px;
  4647. overflow: hidden;
  4648. box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
  4649. z-index: 20;
  4650. transition: all 0.3s ease;
  4651. }
  4652. .camera-warning {
  4653. animation: camera-warning-flash 1s ease-in-out infinite;
  4654. border: 4px solid #ff0000;
  4655. }
  4656. @keyframes camera-warning-flash {
  4657. 0% {
  4658. border-color: #ff0000;
  4659. box-shadow: 0 0 15px rgba(255, 0, 0, 0.8);
  4660. }
  4661. 50% {
  4662. border-color: rgba(255, 0, 0, 0.3);
  4663. box-shadow: 0 0 5px rgba(255, 0, 0, 0.4);
  4664. }
  4665. 100% {
  4666. border-color: #ff0000;
  4667. box-shadow: 0 0 15px rgba(255, 0, 0, 0.8);
  4668. }
  4669. }
  4670. /* 用户摄像头视频样式 */
  4671. .user-camera-video {
  4672. width: 100%;
  4673. height: 100%;
  4674. object-fit: cover;
  4675. background-color: #333;
  4676. }
  4677. .video-player {
  4678. width: 100%;
  4679. height: 100%;
  4680. object-fit: cover;
  4681. outline: none; /* 移除视频获得焦点时的轮廓 */
  4682. -webkit-tap-highlight-color: transparent; /* 移除移动设备上的点击高亮 */
  4683. }
  4684. /* 隐藏视频控制条 */
  4685. video::-webkit-media-controls {
  4686. display: none !important;
  4687. }
  4688. video::-webkit-media-controls-enclosure {
  4689. display: none !important;
  4690. }
  4691. video::-webkit-media-controls-panel {
  4692. display: none !important;
  4693. }
  4694. video::-webkit-media-controls-play-button {
  4695. display: none !important;
  4696. }
  4697. video::-webkit-media-controls-timeline {
  4698. display: none !important;
  4699. }
  4700. video::-webkit-media-controls-current-time-display {
  4701. display: none !important;
  4702. }
  4703. video::-webkit-media-controls-time-remaining-display {
  4704. display: none !important;
  4705. }
  4706. video::-webkit-media-controls-mute-button {
  4707. display: none !important;
  4708. }
  4709. video::-webkit-media-controls-volume-slider {
  4710. display: none !important;
  4711. }
  4712. video::-webkit-media-controls-fullscreen-button {
  4713. display: none !important;
  4714. }
  4715. /* 修改字幕覆盖层样式,使其与图片中的样式一致 */
  4716. .subtitle-overlay {
  4717. position: absolute;
  4718. bottom: 180px;
  4719. left: 10%;
  4720. width: 80%;
  4721. padding: 0; /* 移除内边距,由内部元素控制 */
  4722. border-radius: 15px;
  4723. background-color: rgba(255, 255, 255, 0.9);
  4724. color: #333;
  4725. text-align: left;
  4726. font-size: 16px;
  4727. line-height: 1.5;
  4728. z-index: 10;
  4729. margin: 0 auto;
  4730. box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  4731. display: flex;
  4732. flex-direction: column;
  4733. overflow: hidden; /* 确保圆角效果 */
  4734. }
  4735. /* 添加题号header样式 */
  4736. .subtitle-header {
  4737. /* background-color: rgba(0, 0, 0, 0.05); */
  4738. padding: 8px 20px;
  4739. /* border-bottom: 1px solid rgba(0, 0, 0, 0.05); */
  4740. }
  4741. .question-tag {
  4742. font-size: 14px;
  4743. color: #666;
  4744. font-weight: 500;
  4745. }
  4746. /* 调整主字幕样式 */
  4747. .subtitle-main {
  4748. padding: 15px 20px ;
  4749. font-weight: 500;
  4750. }
  4751. /* 移除之前的题号显示器 */
  4752. .question-counter {
  4753. display: none;
  4754. }
  4755. .control-panel {
  4756. padding: 15px;
  4757. display: flex;
  4758. justify-content: center;
  4759. }
  4760. .control-button {
  4761. padding: 10px 20px;
  4762. background-color: #4CAF50;
  4763. color: white;
  4764. border: none;
  4765. border-radius: 4px;
  4766. cursor: pointer;
  4767. }
  4768. .loading {
  4769. text-align: center;
  4770. margin: 20px 0;
  4771. font-size: 16px;
  4772. }
  4773. .response-container {
  4774. margin-top: 20px;
  4775. padding: 0 20px;
  4776. display: none; /* 默认隐藏调试信息 */
  4777. }
  4778. /* 当showDebugInfo为true时显示 */
  4779. .showDebugInfo .response-container {
  4780. display: block;
  4781. }
  4782. .response-item {
  4783. padding: 10px;
  4784. border: 1px solid #eee;
  4785. border-radius: 4px;
  4786. margin-bottom: 10px;
  4787. background-color: #f9f9f9;
  4788. }
  4789. .response-content {
  4790. display: flex;
  4791. flex-direction: column;
  4792. }
  4793. .answer-button-container {
  4794. position: absolute;
  4795. bottom: 50px; /* 将按钮放在底部而不是75%的位置 */
  4796. left: 50%;
  4797. transform: translateX(-50%); /* 只在X轴上平移,保持水平居中 */
  4798. z-index: 20;
  4799. }
  4800. /* 修改回答按钮样式 */
  4801. .answer-button {
  4802. width: 120px;
  4803. height: 40px; /* 改为矩形按钮 */
  4804. border-radius: 20px; /* 圆角矩形 */
  4805. background-color: #ffffff; /* 白色背景 */
  4806. color: #333; /* 深色文字 */
  4807. font-size: 16px;
  4808. border: none;
  4809. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  4810. display: flex;
  4811. justify-content: center;
  4812. align-items: center;
  4813. cursor: pointer;
  4814. animation: none; /* 移除脉动动画 */
  4815. }
  4816. .stop-recording-button-container {
  4817. position: absolute;
  4818. bottom: 50px; /* 统一与其他按钮的位置 */
  4819. left: 50%;
  4820. transform: translateX(-50%);
  4821. z-index: 20;
  4822. }
  4823. .stop-recording-button {
  4824. width: 120px;
  4825. height: 40px; /* 改为矩形按钮 */
  4826. border-radius: 20px; /* 圆角矩形 */
  4827. background-color: #0039b3; /* 白色背景 */
  4828. color: #fff;/* 深色文字 */
  4829. font-size: 16px;
  4830. border: none;
  4831. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  4832. display: flex;
  4833. justify-content: center;
  4834. align-items: center;
  4835. cursor: pointer;
  4836. animation: none; /* 移除脉动动画 */
  4837. }
  4838. .recording-indicator {
  4839. position: fixed;
  4840. bottom: 20px;
  4841. left: 17%;
  4842. transform: translateX(-50%);
  4843. display: flex;
  4844. flex-direction: column;
  4845. align-items: center;
  4846. /* background-color: rgba(0, 0, 0, 0.6); */
  4847. padding: 10px 15px;
  4848. border-radius: 10px;
  4849. z-index: 100;
  4850. }
  4851. .timer-text {
  4852. color: #05dc8b;
  4853. font-size: 14px;
  4854. margin-top: 5px;
  4855. }
  4856. .start-recording-button-container {
  4857. position: absolute;
  4858. bottom: 50px; /* 统一与其他按钮的位置 */
  4859. left: 50%;
  4860. transform: translateX(-50%);
  4861. z-index: 101;
  4862. }
  4863. .start-recording-button {
  4864. width: 120px;
  4865. height: 40px; /* 改为矩形按钮 */
  4866. border-radius: 20px; /* 圆角矩形 */
  4867. background-color: #ffffff; /* 白色背景 */
  4868. color: #333; /* 深色文字 */
  4869. font-size: 16px;
  4870. border: none;
  4871. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  4872. display: flex;
  4873. justify-content: center;
  4874. align-items: center;
  4875. cursor: pointer;
  4876. animation: none; /* 移除脉动动画 */
  4877. }
  4878. .retry-button-container {
  4879. position: absolute;
  4880. bottom: 30px; /* 统一与其他按钮的位置 */
  4881. left: 50%;
  4882. transform: translateX(-50%);
  4883. z-index: 20;
  4884. }
  4885. .retry-button {
  4886. padding: 10px 20px;
  4887. background-color: #ffffff; /* 白色背景 */
  4888. color: #333; /* 深色文字 */
  4889. font-size: 16px;
  4890. border: none;
  4891. border-radius: 20px; /* 圆角矩形 */
  4892. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  4893. cursor: pointer;
  4894. }
  4895. .retry-button:hover {
  4896. background-color: #2980b9;
  4897. }
  4898. /* 录制时长显示 */
  4899. .recording-timer {
  4900. position: absolute;
  4901. top: 20px;
  4902. left: 130px; /* 放在录制指示器旁边 */
  4903. background-color: rgba(0, 0, 0, 0.6);
  4904. padding: 5px 10px;
  4905. border-radius: 15px;
  4906. z-index: 20;
  4907. display: flex;
  4908. flex-direction: column;
  4909. }
  4910. .timer-text {
  4911. color: #000;
  4912. font-size: 14px;
  4913. font-family: monospace; /* 使用等宽字体,使时间显示更稳定 */
  4914. }
  4915. .remaining-time {
  4916. color: white;
  4917. font-size: 12px;
  4918. margin-top: 2px;
  4919. }
  4920. .remaining-time.warning {
  4921. color: #ff6b6b; /* 剩余时间少时显示红色 */
  4922. animation: blink 1s infinite; /* 使用闪烁动画提醒用户 */
  4923. }
  4924. /* 添加上传状态指示器 */
  4925. .upload-status-indicator {
  4926. position: absolute;
  4927. top: 20px;
  4928. left: 130px; /* 放在录制指示器旁边 */
  4929. background-color: rgba(0, 0, 0, 0.6);
  4930. padding: 5px 10px;
  4931. border-radius: 15px;
  4932. z-index: 20;
  4933. }
  4934. .upload-status-content {
  4935. display: flex;
  4936. align-items: center;
  4937. }
  4938. .upload-status-icon {
  4939. width: 12px;
  4940. height: 12px;
  4941. border-radius: 50%;
  4942. margin-right: 8px;
  4943. }
  4944. .upload-status-text {
  4945. color: white;
  4946. font-size: 14px;
  4947. }
  4948. .uploading {
  4949. background-color: #e74c3c;
  4950. }
  4951. /* 添加倒计时蒙层样式 */
  4952. .countdown-overlay {
  4953. position: fixed;
  4954. top: 0;
  4955. left: 0;
  4956. width: 100%;
  4957. height: 100%;
  4958. background-color: rgba(0, 0, 0, 0.7);
  4959. z-index: 100;
  4960. display: flex;
  4961. justify-content: center;
  4962. align-items: center;
  4963. }
  4964. .countdown-content {
  4965. display: flex;
  4966. flex-direction: column;
  4967. align-items: center;
  4968. }
  4969. .countdown-number {
  4970. font-size: 80px;
  4971. color: #ffffff;
  4972. font-weight: bold;
  4973. margin-bottom: 20px;
  4974. }
  4975. .countdown-text {
  4976. font-size: 24px;
  4977. color: #ffffff;
  4978. }
  4979. /* 添加GIF播放器样式 */
  4980. .gif-player {
  4981. width: 100%;
  4982. height: 100%;
  4983. object-fit: cover;
  4984. position: absolute;
  4985. top: 0;
  4986. left: 0;
  4987. z-index: 5; /* 确保GIF在视频上方但在字幕和按钮下方 */
  4988. }
  4989. /* 重新录制按钮容器样式 */
  4990. .rerecord-button-container {
  4991. position: absolute;
  4992. bottom: 50px; /* 统一与其他按钮的位置 */
  4993. left: 50%;
  4994. transform: translateX(-50%);
  4995. z-index: 20;
  4996. }
  4997. /* 重新录制按钮样式 */
  4998. .rerecord-button {
  4999. width: 120px;
  5000. height: 40px;
  5001. border-radius: 20px;
  5002. background-color: #ffffff;
  5003. color: #333;
  5004. font-size: 16px;
  5005. border: none;
  5006. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  5007. display: flex;
  5008. justify-content: center;
  5009. align-items: center;
  5010. cursor: pointer;
  5011. }
  5012. .rerecord-button:hover {
  5013. background-color: #f0f0f0;
  5014. }
  5015. /* 添加视频蒙层样式 */
  5016. .video-overlay {
  5017. position: absolute;
  5018. top: 0;
  5019. left: 0;
  5020. width: 100%;
  5021. height: 100%;
  5022. background-color: transparent; /* 完全透明 */
  5023. z-index: 6; /* 确保在视频之上,但在按钮和字幕之下 */
  5024. pointer-events: auto; /* 允许捕获点击事件 */
  5025. }
  5026. /* 调整其他元素的z-index以确保正确的层级关系 */
  5027. .subtitle-overlay {
  5028. /* ... 现有样式 ... */
  5029. z-index: 10; /* 确保字幕在蒙层之上 */
  5030. }
  5031. .answer-button-container,
  5032. .stop-recording-button-container,
  5033. .start-recording-button-container,
  5034. .retry-button-container,
  5035. .rerecord-button-container {
  5036. /* ... 现有样式 ... */
  5037. z-index: 999; /* 确保按钮在蒙层之上 */
  5038. }
  5039. .user-camera-container {
  5040. /* ... 现有样式 ... */
  5041. z-index: 20; /* 确保摄像头窗口在蒙层之上 */
  5042. }
  5043. .recording-indicator {
  5044. /* ... 现有样式 ... */
  5045. z-index: 20; /* 确保录制指示器在蒙层之上 */
  5046. }
  5047. /* 环形进度条样式 */
  5048. .circle-progress-container {
  5049. width: 60px;
  5050. height: 60px;
  5051. position: relative;
  5052. margin: 0 auto 10px;
  5053. }
  5054. .circle-progress {
  5055. width: 100%;
  5056. height: 100%;
  5057. border-radius: 50%;
  5058. display: flex;
  5059. align-items: center;
  5060. justify-content: center;
  5061. position: relative;
  5062. transform: rotate(-90deg); /* 从顶部开始进度 */
  5063. }
  5064. .circle-progress-inner {
  5065. width: 80%;
  5066. height: 80%;
  5067. background-color: rgba(255, 255, 255);
  5068. border-radius: 50%;
  5069. display: flex;
  5070. align-items: center;
  5071. justify-content: center;
  5072. transform: rotate(90deg); /* 修正文本方向 */
  5073. }
  5074. .progress-text {
  5075. font-size: 14px;
  5076. font-weight: bold;
  5077. color: #05dc8b;
  5078. }
  5079. /* 添加题号显示 */
  5080. .question-counter {
  5081. position: absolute;
  5082. top: 20px;
  5083. right: 130px; /* 调整位置,避免与用户摄像头重叠 */
  5084. background-color: rgba(255, 255, 255, 0.9);
  5085. padding: 6px 12px;
  5086. border-radius: 15px;
  5087. z-index: 20;
  5088. box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  5089. display: flex;
  5090. align-items: center;
  5091. }
  5092. .question-number {
  5093. color: #333;
  5094. font-size: 14px;
  5095. font-weight: 500;
  5096. }
  5097. /* 追问问题容器样式 */
  5098. .followup-container {
  5099. width: 100%;
  5100. }
  5101. /* 追问分隔线 */
  5102. .followup-divider {
  5103. height: 1px;
  5104. background-color: rgba(0, 0, 0, 0.05);
  5105. margin: 0;
  5106. }
  5107. /* 追问内容样式 */
  5108. .followup-content {
  5109. padding: 12px 20px;
  5110. display: flex;
  5111. align-items: flex-start;
  5112. gap: 8px;
  5113. }
  5114. /* 追问标签样式 */
  5115. .followup-label {
  5116. color: #fb752f;
  5117. font-size: 14px;
  5118. font-weight: 500;
  5119. }
  5120. /* 追问文本样式 */
  5121. .followup-text {
  5122. color: #333;
  5123. font-size: 14px;
  5124. line-height: 1.5;
  5125. flex: 1;
  5126. }
  5127. /* 调整主字幕样式,确保有足够空间 */
  5128. .subtitle-main {
  5129. padding:15px 20px ;
  5130. font-weight: 500;
  5131. border-bottom: none; /* 移除底部边框,由追问分隔线处理 */
  5132. }
  5133. /* 父问题样式 */
  5134. .parent-question {
  5135. padding: 15px 20px;
  5136. font-weight: 500;
  5137. color: #333;
  5138. }
  5139. /* 追问容器样式调整 */
  5140. .followup-container {
  5141. width: 100%;
  5142. /* background-color: rgba(0, 0, 0, 0.02); *//* 轻微的背景色区分 */
  5143. }
  5144. /* 分隔线样式 */
  5145. .followup-divider {
  5146. height: 1px;
  5147. background-color: rgba(0, 0, 0, 0.05);
  5148. margin: 0;
  5149. }
  5150. /* 追问内容样式 */
  5151. .followup-content {
  5152. padding: 12px 20px;
  5153. display: flex;
  5154. align-items: flex-start;
  5155. gap: 8px;
  5156. }
  5157. /* 追问标签样式 */
  5158. .followup-label {
  5159. color: #fb752f;
  5160. font-size: 14px;
  5161. font-weight: 500;
  5162. }
  5163. /* 追问文本样式 */
  5164. .followup-text {
  5165. color: #333;
  5166. font-size: 14px;
  5167. line-height: 1.5;
  5168. flex: 1;
  5169. }
  5170. .custom-navbar {
  5171. position: fixed;
  5172. top: 0;
  5173. left: 0;
  5174. right: 0;
  5175. height: 44px;
  5176. background-color: #ffffff;
  5177. display: flex;
  5178. align-items: center;
  5179. justify-content: center;
  5180. z-index: 999;
  5181. }
  5182. .navbar-title {
  5183. font-size: 16px;
  5184. font-weight: bold;
  5185. }
  5186. .content {
  5187. margin-top: 44px;
  5188. padding-top: var(--status-bar-height);
  5189. }
  5190. </style>