identity-verify.vue 199 KB

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