identity-verify.vue 165 KB

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