identity-verify.vue 209 KB

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