identity-verify.vue 167 KB

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