identity-verify.vue 199 KB

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