123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061 |
- <template>
- <div class="identity-verify-container">
- <div class="digital-human-container">
- <!-- AI数字人视频/图像显示区域 -->
- <div class="digital-human-video">
- <!-- 添加GIF图片显示区域 -->
- <!-- <img v-if="showGif && gifUrl" :src="gifUrl" class="gif-player" alt="面试官GIF" /> -->
- <!-- <video
- v-if="showGif && gifUrl"
- :src="gifUrl"
- id="mpVideo"
- autoplay
- class="video-player"
- :controls="false"
- loop
- muted
- object-fit="contain"
- ></video> v-if="!showGif" -->
-
- <!-- 视频播放区域,当showGif为false时显示 -->
- <video
- :src="videoUrl"
- id="myVideo"
- ref="videoPlayer"
- autoplay
- playsinline
- disablePictureInPicture
- controlsList="nodownload nofullscreen noremoteplayback"
- class="video-player"
- :controls="false"
- @error="handleVideoError"
- @ended="handleVideoEnded"
- @timeupdate="handleTimeUpdate">
- </video>
- <div class="answer-button-container" v-if="showAnswerButton">
- <button class="answer-button" @click="handleAnswerButtonClick">
- 开始提问
- </button>
- </div>
- <!-- 添加字幕覆盖层 :data-time="formatTime(recordingTimerCount) || '03:30'"-->
- <div class="subtitle-overlay" v-if="currentSubtitle" >
- {{ currentSubtitle }}
- </div>
-
- <!-- 添加答题按钮 -->
-
- </div>
-
- <!-- 用户摄像头视频显示区域 -->
- <div class="user-camera-container">
- <!-- 在小程序环境中使用camera组件 -->
- <camera v-if="useMiniProgramCameraComponent"
- device-position="front"
- flash="off"
- class="user-camera-video"
- @error="handleCameraError"
- :record-audio="true"
- frame-size="small"
- resolution="low"
- :disable-zoom="true"
- :enable-camera="true"
- :enable-record="true"
- mode="normal">
- </camera>
- <!-- 在H5/App环境中使用video元素 -->
- <video v-else
- id="userCamera"
- ref="userCameraVideo"
- autoplay
- playsinline
- muted
- class="user-camera-video"
- :controls="false">
- </video>
- </div>
-
- <!-- 字幕/文本覆盖区域 -->
- <!-- <div class="subtitle-overlay" v-if="assistantResponse">
- {{ assistantResponse }}
- </div> -->
- </div>
- <!-- 加载状态 -->
- <div v-if="loading" class="loading">加载中...</div>
-
- <!-- 控制面板(可选,可以隐藏) -->
-
- <!-- 响应数据(可以设为隐藏,仅用于调试) -->
- <div v-if="showDebugInfo" class="response-container">
- <div v-if="assistantResponse" class="response-item">
- <div class="response-content">
- <span>助手回复: {{ assistantResponse }}</span>
- </div>
- </div>
- <div v-if="audioTranscript" class="response-item">
- <div class="response-content">
- <span>音频转写: {{ audioTranscript }}</span>
- </div>
- </div>
- <div v-for="(item, index) in processedResponses" :key="index" class="response-item">
- <div class="response-content">
- <span v-if="item.role">角色: {{ item.role }}</span>
- <span v-if="item.transcript">文本: {{ item.transcript }}</span>
- </div>
- </div>
- </div>
- <!-- 添加停止录制按钮 -->
- <div class="stop-recording-button-container" v-if="showStopRecordingButton">
- <button class="stop-recording-button" @click="stopRecordingAnswer">
- 完成提问
- </button>
- </div>
- <!-- 添加录制指示器 -->
- <div class="recording-indicator" v-if="isRecording">
- <div class="recording-dot"></div>
- <span class="recording-text">正在录制...</span>
- <span class="timer-text">{{ recordingTimeDisplay || '00:00 / 05:00' }}</span>
- </div>
- <!-- 添加开始回答按钮 -->
- <div class="start-recording-button-container" v-if="showStartRecordingButton">
- <button class="start-recording-button" @click="handleStartRecordingClick">
- 开始提问
- </button>
- </div>
- <!-- 添加重试上传按钮 -->
- <div class="retry-button-container" v-if="showRetryButton">
- <button class="retry-button" @click="retryVideoUpload">
- 重新上传
- </button>
- </div>
- <!-- 在模板部分添加录制时长显示 -->
- <!-- <div class="recording-timer" v-if="isRecording">
- <span class="timer-text">{{ recordingTimeDisplay || '00:00' }}</span>
- </div> -->
- <!-- 添加上传状态指示器 -->
- <!-- <div class="upload-status-indicator" v-if="showUploadStatus && uploadStatusText">
- <div class="upload-status-content">
- <div class="upload-status-icon" :class="{'uploading': isUploading}"></div>
- <span class="upload-status-text">{{ uploadStatusText }}</span>
- </div>
- </div> -->
- <!-- 修改录制时长显示 -->
- <!-- <div class="recording-timer" v-if="isRecording">
- <span class="timer-text">{{ recordingTimeDisplay || '00:00 / 05:00' }}</span>
- <span class="remaining-time" :class="{'warning': remainingTime <= 10}">
- 剩余: {{ formatTime(remainingTime) }}
- </span>
- </div> -->
- <!-- 在模板部分添加倒计时蒙层 -->
- <div class="countdown-overlay" v-if="showCountdown">
- <div class="countdown-content">
- <div class="countdown-number">{{ countdownValue }}</div>
- <div class="countdown-text">准备开始回答</div>
- </div>
- </div>
- <!-- 在template中添加蒙层 -->
- <div class="ai-voice-overlay" v-if="isPlayingAiVoice">
- <div class="ai-voice-content">
- <div class="ai-voice-icon"></div>
- <div class="ai-voice-text">面试官正在回复...</div>
- </div>
- </div>
- <!-- 在模板部分添加继续提问和结束面试按钮 -->
- <div class="continue-question-container" v-if="showContinueQuestionButton">
- <button class="continue-question-button" @click="handleContinueQuestionClick">
- 继续提问
- </button>
- </div>
- <!-- <div class="end-interview-container" v-if="showEndInterviewButton">
- <button class="end-interview-button" @click="handleEndInterviewClick">
- 结束提问
- </button>
- </div> -->
- <!-- 添加提问轮次显示 -->
- <!-- <div class="question-round-indicator" v-if="questionRound > 0">
- <span class="round-text">第 {{ questionRound }}/{{ maxQuestionRounds }} 轮提问</span>
- </div> -->
- </div>
- </template>
- <script>
- import { apiBaseUrl } from '@/common/config.js';
- export default {
- name: 'IdentityVerify',
- data() {
- return {
- loading: false,
- responses: [],
- processedResponses: [],
- assistantResponse: '',
- audioTranscript: '',
- videoPlaying: false,
- showDebugInfo: false, // 设置为true可以显示调试信息
- videoUrl: 'https://data.qicai321.com/minlong/1809457d-30c5-40bb-b6d8-a8c2e8e1e9e2.mp4', //'http://121.36.251.245:9000/minlong/tenant_1/general_uploads/abdaa6fda8494e3a8613304743ed0433.mp4', // 用于存储AI数字人视频URL
- showReplayButton: false,
- cameraStream: null, // 存储摄像头流
- cameraError: null, // 存储摄像头错误信息
- useMiniProgramCameraComponent: false, // 添加小程序相机组件标志
- cameraContext: null, // 添加相机上下文
- currentSubtitle: '',
- subtitles: [
- {
- startTime: 0, // 开始时间(秒)
- endTime: 6, // 结束时间(秒)
- text: '您已完成本次面试全部题目,请问您对于这个岗位还有什么想要了解的吗?'
- },
- ],
- // secondVideoSubtitles: [
- // {
- // startTime: 0,
- // endTime: 10,
- // text: '请结合您的基本信息与过往履历进行简单的自我介绍,并讲一讲您有哪些优势胜任本岗位:'
- // }
- // ],
- // thirdVideoSubtitles: [
- // {
- // startTime: 0,
- // endTime: 4,
- // text: '在工作中,你如何确保个人防护装备的正确使用?'
- // }
- // ],
- // fourthVideoSubtitles: [
- // {
- // startTime: 0,
- // endTime: 4,
- // text: '描述一次你与团队合作改善生产流程的经历。'
- // }
- // ],
- // fifthVideoSubtitles: [
- // {
- // startTime: 0,
- // endTime: 6,
- // text: '你在团队合作中曾遇到过哪些挑战?如何解决团队内部的分歧?'
- // }
- // ],
- // sixthVideoSubtitles: [
- // {
- // startTime: 0,
- // endTime: 5,
- // text: '您已完成本次面试全部题目,请问您对于这个岗位还有什么想要了解的吗?'
- // }
- // ],
- showAnswerButton: false, // 控制答题按钮显示
- currentVideoIndex: 0, // 当前播放的视频索引
- videoList: [
- 'https://data.qicai321.com/minlong/1809457d-30c5-40bb-b6d8-a8c2e8e1e9e2.mp4'//结束
- ],
- isRecording: false,
- recordingTimer: null,
- showStopRecordingButton: false,
- mediaRecorder: null,
- recordedChunks: [],
- recorder: null,
- lastUploadedVideoUrl: '',
- showStartRecordingButton: false,
- showRetryButton: false, // 控制重试按钮显示
- lastVideoToRetry: null, // 存储上次失败的视频URL,用于重试
- recordingStartTime: null, // 录制开始时间
- recordingTimerCount: 0, // 录制计时器计数
- recordingTimeDisplay: '00:00', // 格式化的录制时间显示
-
- // 添加上传队列相关数据
- uploadQueue: [], // 存储待上传的视频
- isUploading: false, // 标记是否正在上传
- uploadProgress: {}, // 存储每个视频的上传进度
- uploadStatus: {}, // 存储每个视频的上传状态
- showUploadStatus: false, // 是否显示上传状态指示器
- uploadStatusText: '', // 上传状态文本
- mediaRecorderTimeout: null, // 用于存储MediaRecorder的超时机制
- maxRecordingTime: 300, // 最大录制时间(秒)- 从60秒改为300秒(5分钟)
- remainingTime: 300, // 剩余录制时间(秒)- 从60秒改为300秒
-
- // 修改初始视频索引,添加参数控制
- startFromLastVideo: false, // 是否从最后一个视频开始播放
- countdownValue: 10, // 倒计时数值
- showCountdown: false, // 是否显示倒计时蒙层
- countdownTimer: null,
- showGif: false, // 控制是否显示GIF
- gifUrl: '', // GIF图片的URL
-
- // 添加AI语音交互相关属性
- aiVoiceUrl: '', // AI语音URL
- aiText: '', // AI回复文本
- transcribedText: '', // 转写文本
- isPlayingAiVoice: false, // 是否正在播放AI语音
- aiAudioPlayer: null, // AI语音播放器
-
- // 添加新的状态变量
- showContinueQuestionButton: false, // 控制"继续提问"按钮显示
- showEndInterviewButton: false, // 控制"结束面试"按钮显示
- questionRound: 0, // 当前提问轮次
- maxQuestionRounds: 1, // 最大提问轮次(可配置)
- conversationHistory: [], // 对话历史记录
- pendingAutoNavigation: false, // 标记是否有待处理的自动跳转
- hasTriedFallbackMethod: false, // 标记是否尝试过备选方法播放音频
- hasShownTextFallbackToast: false, // 标记是否已显示文本回退提示
- }
- },
- onLoad(options) {
- // 检查是否有参数指定从最后一个视频开始
- if (options && options.startFromLast === 'true') {
- this.startFromLastVideo = true;
- // 设置为最后一个视频的索引
- this.currentVideoIndex = this.videoList.length - 1;
- }
- },
- mounted() {
- /* this.fetchData() */
-
- // 如果需要从最后一个视频开始,直接设置
- if (this.startFromLastVideo) {
- console.log('从最后一个视频开始播放');
- this.currentVideoIndex = this.videoList.length - 1;
- this.videoUrl = this.videoList[this.currentVideoIndex];
- }
-
- this.playDigitalHumanVideo();
- this.checkAudioPermission();
- this.initCamera();
- this.checkIOSCameraRecordPermission();
-
- // 添加防御性检查,避免渲染错误
- this.checkAndFixRenderingIssues();
-
- // 添加音频测试
- setTimeout(() => {
- if (this.cameraStream && !this.useMiniProgramCameraComponent) {
- this.testAudioInput();
- }
- }, 3000);
-
- uni.setKeepScreenOn({
- keepScreenOn: true
- });
- },
- beforeDestroy() {
- // 组件销毁前停止摄像头
- this.stopUserCamera();
-
- // 销毁AI音频播放器
- if (this.aiAudioPlayer) {
- try {
- this.aiAudioPlayer.destroy();
- } catch (e) {
- console.error('销毁音频播放器失败:', e);
- }
- this.aiAudioPlayer = null;
- }
-
- // 清除所有计时器
- if (this.recordingTimer) {
- clearInterval(this.recordingTimer);
- this.recordingTimer = null;
- }
-
- if (this.countdownTimer) {
- clearInterval(this.countdownTimer);
- this.countdownTimer = null;
- }
-
- if (this.mediaRecorderTimeout) {
- clearTimeout(this.mediaRecorderTimeout);
- this.mediaRecorderTimeout = null;
- }
-
- // 如果有正在进行的录制,停止录制
- if (this.mediaRecorder && this.mediaRecorder.state === 'recording') {
- try {
- this.mediaRecorder.stop();
- } catch (e) {
- console.error('停止MediaRecorder失败:', e);
- }
- }
-
- if (this.recorder) {
- try {
- this.cameraContext.stopRecord();
- } catch (e) {
- console.error('停止小程序录制失败:', e);
- }
- }
-
- // 关闭屏幕常亮
- uni.setKeepScreenOn({
- keepScreenOn: false
- });
- },
- methods: {
- // 初始化相机
- async initCamera() {
- // 检查平台
- const systemInfo = uni.getSystemInfoSync();
-
- // 判断是否在小程序环境中
- const isMiniProgram = systemInfo.uniPlatform === 'mp-weixin' ||
- systemInfo.uniPlatform === 'mp-alipay' ||
- systemInfo.uniPlatform === 'mp-baidu';
-
- if (isMiniProgram) {
- // 小程序环境使用小程序的相机API
- this.useMiniProgramCameraComponent = true;
-
- // 创建相机上下文
- this.cameraContext = uni.createCameraContext();
-
- // 确保已获取录音和相机权限
- uni.getSetting({
- success: (res) => {
- // 检查录音权限
- if (!res.authSetting['scope.record']) {
- uni.authorize({
- scope: 'scope.record',
- success: () => {
- console.log('录音权限已获取');
- },
- fail: (err) => {
- console.error('录音权限获取失败:', err);
- this.showPermissionDialog('录音');
- }
- });
- }
-
- // 检查相机权限
- if (!res.authSetting['scope.camera']) {
- uni.authorize({
- scope: 'scope.camera',
- success: () => {
- console.log('相机权限已获取');
- },
- fail: (err) => {
- console.error('相机权限获取失败:', err);
- this.showPermissionDialog('相机');
- }
- });
- }
-
- // 在iOS上,可能需要额外的权限检查
- const systemInfo = uni.getSystemInfoSync();
- if (systemInfo.platform === 'ios') {
- // 在iOS上,不要使用无效的权限范围
- // 移除以下代码块
- /*
- if (!res.authSetting['scope.camera.record']) {
- uni.authorize({
- scope: 'scope.camera.record',
- success: () => {
- console.log('相机录制权限已获取');
- },
- fail: (err) => {
- console.error('相机录制权限获取失败:', err);
- this.showPermissionDialog('相机录制');
- }
- });
- }
- */
-
- // 确保同时获取了相机和录音权限
- if (!res.authSetting['scope.camera'] || !res.authSetting['scope.record']) {
- console.log('iOS需要同时获取相机和录音权限');
- }
- }
- }
- });
- } else {
- // H5/App环境使用浏览器的API
- try {
- // 请求摄像头和麦克风权限并获取媒体流,添加更多约束
- const constraints = {
- audio: {
- echoCancellation: true,
- noiseSuppression: true,
- autoGainControl: true
- },
- video: {
- width: { ideal: 640, max: 1280 }, // 控制视频宽度
- height: { ideal: 480, max: 720 }, // 控制视频高度
- frameRate: { ideal: 15, max: 24 }, // 控制帧率
- facingMode: 'user'
- }
- };
-
- const stream = await navigator.mediaDevices.getUserMedia(constraints);
-
- // 保存流以便后续使用
- this.cameraStream = stream;
-
- // 检查音频轨道
- const audioTracks = stream.getAudioTracks();
- console.log('音频轨道数量:', audioTracks.length);
- if (audioTracks.length > 0) {
- console.log('音频轨道已获取:', audioTracks[0].label);
- // 确保音频轨道已启用
- audioTracks[0].enabled = true;
- } else {
- console.warn('未检测到音频轨道,尝试单独获取音频');
- this.tryGetAudioOnly();
- }
-
- // 将流设置到视频元素
- const videoElement = this.$refs.userCameraVideo;
- if (videoElement) {
- videoElement.srcObject = stream;
- videoElement.muted = true; // 避免回声,但仍然录制声音
- }
- } catch (error) {
- console.error('获取摄像头失败:', error);
- this.cameraError = error.message || '无法访问摄像头';
-
- // 显示错误提示
- uni.showToast({
- title: '无法访问摄像头,请检查权限设置',
- icon: 'none'
- });
- }
- }
- },
-
- // 停止用户摄像头
- stopUserCamera() {
- if (this.cameraStream) {
- // 停止所有轨道
- this.cameraStream.getTracks().forEach(track => {
- track.stop();
- });
- this.cameraStream = null;
- }
- },
-
- async fetchData() {
- this.loading = true
- this.assistantResponse = ''
- this.audioTranscript = ''
- this.processedResponses = []
- try {
- // 使用uni.request代替fetch
- const requestTask = uni.request({
- url: 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions',
- method: 'POST',
- header: {
- 'Content-Type': 'application/json',
- 'Authorization': 'Bearer sk-9e1ec73a7d97493b8613c63f06b6110c'
- },
- data: {
- "model": "qwen-omni-turbo",
- "messages": [
- {
- "role": "user",
- "content": [
- {
- "type": "input_audio",
- "input_audio": {
- "data": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250211/tixcef/cherry.wav",
- "format": "wav"
- }
- },
- {
- "type": "text",
- "text": "这段音频在说什么"
- }
- ]
- }
- ],
- "stream":true,
- "stream_options":{
- "include_usage":true
- },
- "modalities":["text","audio"],
- "audio":{"voice":"Cherry","format":"wav"}
- },
- success: (res) => {
- console.log('请求成功,响应数据:', res.data);
- // 检查响应数据是否包含多个JSON对象
- if (typeof res.data === 'string' && res.data.includes('data: {')) {
- // 处理包含多个JSON对象的情况
- const chunks = res.data.split('data: ').filter(chunk => chunk.trim() !== '');
- chunks.forEach(chunk => {
- this.handleStreamResponse(chunk);
- });
- } else {
- // 处理单个响应对象的情况
- this.handleStreamResponse(res.data);
- }
-
- // 模拟获取到数字人视频并播放
- this.playDigitalHumanVideo();
- },
- fail: (err) => {
- console.error('请求失败:', err);
- },
- complete: () => {
- this.loading = false;
- }
- });
- } catch (error) {
- console.error('获取数据失败:', error);
- this.loading = false;
- }
- },
-
- handleStreamResponse(data) {
- // 处理流式响应数据
- if (typeof data === 'string') {
- // 处理字符串格式的响应
- if (data === '[DONE]') return;
-
- try {
- // 移除可能存在的换行符和多余空格
- const cleanData = data.trim();
- // 检查是否是有效的JSON字符串
- if (cleanData.startsWith('{') && cleanData.endsWith('}')) {
- const jsonData = JSON.parse(cleanData);
- this.processStreamChunk(jsonData);
- }
- } catch (e) {
- console.error('解析JSON失败:', e, '原始数据:', data);
- }
- } else {
- // 处理对象格式的响应
- this.processStreamChunk(data);
- }
- },
-
- processStreamChunk(chunk) {
- if (chunk.choices && chunk.choices.length > 0) {
- const choice = chunk.choices[0];
-
- // 处理助手回复内容
- if (choice.delta && choice.delta.content) {
- this.assistantResponse += choice.delta.content;
- }
-
- // 处理音频转写内容
- if (choice.delta && choice.delta.audio && choice.delta.audio.transcript) {
- this.audioTranscript += choice.delta.audio.transcript;
- }
-
- // 处理角色和音频转写
- if (choice.delta) {
- const result = {};
-
- if (choice.delta.role) {
- result.role = choice.delta.role;
- }
-
- if (choice.delta.audio && choice.delta.audio.transcript) {
- result.transcript = choice.delta.audio.transcript;
- }
-
- if (Object.keys(result).length > 0) {
- this.processedResponses.push(result);
- }
- }
- }
- },
-
- processResponseData() {
- // 处理返回的数据
- this.processedResponses = this.responses.map(item => {
- const result = {}
-
- // 处理角色信息
- if (item.delta && item.delta.role) {
- result.role = item.delta.role
- }
-
- // 处理音频转写文本
- if (item.delta && item.delta.audio && item.delta.audio.transcript) {
- result.transcript = item.delta.audio.transcript
- }
-
- return result
- }).filter(item => Object.keys(item).length > 0)
- },
-
- // 播放数字人视频
- playDigitalHumanVideo() {
- // 设置当前视频
- this.videoUrl = this.videoList[this.currentVideoIndex];
- this.videoPlaying = true;
-
- console.log(`播放视频 ${this.currentVideoIndex + 1}/${this.videoList.length}: ${this.videoUrl}`);
-
- // 使用 uni.createVideoContext 来控制视频
- this.$nextTick(() => {
- const videoContext = uni.createVideoContext('myVideo', this);
- if (videoContext) {
- videoContext.play();
-
- // 设置超时检查,确认视频是否真的在播放
- setTimeout(() => {
- if (this.videoPlaying && this.$refs.videoPlayer) {
- console.log('视频应该正在播放');
- } else {
- console.log('视频可能未成功播放,尝试替代方案');
- this.tryAlternativeVideoPath();
- }
- }, 1000);
- } else {
- console.error('无法创建视频上下文');
- this.tryAlternativeVideoPath();
- }
- });
- },
-
- // 修改 tryAlternativeVideoPath 方法
- tryAlternativeVideoPath() {
- console.log('尝试使用替代路径');
-
- // 尝试不同的路径格式
- const alternativePaths = [
- './static/demo.mp4',
- '../static/demo.mp4',
- 'static/demo.mp4',
- '/static/demo.mp4',
- // 添加绝对路径
- `${window.location.origin}/static/demo.mp4`
- ];
-
- // 获取当前路径索引
- const currentPathIndex = alternativePaths.indexOf(this.videoUrl);
- const nextPathIndex = (currentPathIndex + 1) % alternativePaths.length;
-
- // 设置下一个路径
- this.videoUrl = alternativePaths[nextPathIndex];
- console.log('尝试新路径:', this.videoUrl);
-
- this.$nextTick(() => {
- const videoContext = uni.createVideoContext('myVideo', this);
- if (videoContext) {
- videoContext.stop();
- videoContext.play();
-
- // 检查是否成功播放
- setTimeout(() => {
- if (nextPathIndex === alternativePaths.length - 1 && !this.videoPlaying) {
- console.log('所有路径均失败,尝试使用uni.getVideoInfo检查视频');
- this.checkVideoWithAPI();
- }
- }, 1000);
- }
- });
- },
-
- // 添加新方法:使用uni API检查视频
- checkVideoWithAPI() {
- // 尝试使用uni.getVideoInfo API检查视频是否可用
- uni.getVideoInfo({
- src: '/static/demo.mp4',
- success: (res) => {
- console.log('视频信息获取成功:', res);
- // 如果能获取到视频信息,再次尝试播放
- this.videoUrl = '/static/demo.mp4';
- this.$nextTick(() => {
- const videoContext = uni.createVideoContext('myVideo', this);
- if (videoContext) {
- videoContext.play();
- }
- });
- },
- fail: (err) => {
- console.error('视频信息获取失败:', err);
- // 最后尝试使用uni.chooseVideo API
- this.fallbackToLocalVideo();
- }
- });
- },
-
- // 添加新方法:回退到本地视频
- fallbackToLocalVideo() {
- console.log('尝试使用本地视频资源');
-
- // 检查平台
- const platform = uni.getSystemInfoSync().platform;
- if (platform === 'android' || platform === 'ios') {
- // 移动端可以尝试使用本地资源
- this.videoUrl = platform === 'android' ? 'android.resource://package_name/raw/demo' : 'file:///assets/demo.mp4';
- this.$nextTick(() => {
- const videoContext = uni.createVideoContext('myVideo', this);
- if (videoContext) {
- videoContext.play();
- }
- });
- } else {
- // 最终回退到静态图片
- this.videoPlaying = false;
- uni.showToast({
- title: '视频加载失败,显示静态图片',
- icon: 'none'
- });
- }
- },
-
- // 修改 handleVideoError 方法
- handleVideoError(e) {
- console.error('视频加载错误:', e);
-
- // 记录更详细的错误信息
- if (e && e.detail) {
- console.error('详细错误信息:', e.detail);
- }
-
- // 检查视频文件是否存在
- uni.getFileInfo({
- filePath: this.videoUrl.startsWith('/') ? this.videoUrl.substring(1) : this.videoUrl,
- success: (res) => {
- console.log('文件存在,大小:', res.size);
- // 文件存在但播放失败,可能是格式问题
- this.tryDifferentFormat();
- },
- fail: (err) => {
- console.error('文件不存在或无法访问:', err);
- // 尝试不同路径
- this.tryAlternativeVideoPath();
- }
- });
-
- // 如果多次尝试后仍然失败,显示错误信息
- uni.showToast({
- title: '视频加载失败,请检查文件是否存在',
- icon: 'none',
- duration: 2000
- });
- },
- // 添加新方法:尝试不同格式
- tryDifferentFormat() {
- console.log('尝试不同的视频格式');
-
- // 尝试不同的视频格式
- const formats = [
- { ext: 'mp4', mime: 'video/mp4' },
- { ext: 'webm', mime: 'video/webm' },
- { ext: 'ogg', mime: 'video/ogg' },
- { ext: 'mov', mime: 'video/quicktime' }
- ];
-
- // 获取当前文件名(不含扩展名)
- const currentPath = this.videoUrl;
- const basePath = currentPath.substring(0, currentPath.lastIndexOf('.')) || '/static/demo';
-
- // 尝试下一个格式
- let nextFormat = formats.find(f => !currentPath.endsWith(f.ext));
- if (nextFormat) {
- this.videoUrl = `${basePath}.${nextFormat.ext}`;
- console.log('尝试新格式:', this.videoUrl);
-
- this.$nextTick(() => {
- const videoContext = uni.createVideoContext('myVideo', this);
- if (videoContext) {
- videoContext.stop();
- videoContext.play();
- }
- });
- } else {
- // 所有格式都尝试过了,使用内置资源
- this.useBuiltInResource();
- }
- },
- // 添加新方法:使用内置资源
- useBuiltInResource() {
- console.log('尝试使用内置资源');
-
- // 检查平台
- const platform = uni.getSystemInfoSync().platform;
-
- // 根据平台选择合适的视频源
- if (platform === 'windows') {
- // Windows平台特定处理
- // 尝试使用相对于应用根目录的路径
- const appRoot = process.env.UNI_INPUT_DIR || '';
- this.videoUrl = `./static/demo.mp4`;
-
- // 或者尝试使用file://协议
- // this.videoUrl = `file:///${appRoot.replace(/\\/g, '/')}/static/demo.mp4`;
-
- console.log('Windows平台尝试路径:', this.videoUrl);
- } else if (platform === 'android' || platform === 'ios') {
- // 移动端
- this.useNativeVideo();
- } else {
- // Web平台
- // 尝试使用完整URL
- const baseUrl = window.location.origin;
- this.videoUrl = `${baseUrl}/static/demo.mp4`;
- console.log('Web平台尝试URL:', this.videoUrl);
- }
-
- this.$nextTick(() => {
- const videoContext = uni.createVideoContext('myVideo', this);
- if (videoContext) {
- videoContext.play();
- }
- });
- },
- // 添加新方法:使用原生视频能力
- useNativeVideo() {
- console.log('尝试使用原生视频能力');
-
- // 在移动端,可以尝试使用原生视频播放器
- uni.chooseVideo({
- sourceType: ['album'],
- success: (res) => {
- this.videoUrl = res.tempFilePath;
- this.$nextTick(() => {
- const videoContext = uni.createVideoContext('myVideo', this);
- if (videoContext) {
- videoContext.play();
- }
- });
- },
- fail: () => {
- // 如果用户取消选择,回退到静态图片
- this.videoPlaying = false;
- uni.showToast({
- title: '无法加载视频,显示静态图片',
- icon: 'none'
- });
- }
- });
- },
- // 处理视频结束事件
- handleVideoEnded() {
- console.log('视频播放结束,当前视频索引:', this.currentVideoIndex);
- this.videoPlaying = false;
- /* // 设置对应问题的GIF图片URL
- // if (this.currentVideoIndex === 0) {
- this.gifUrl = 'http://121.36.251.245:9000/minlong/cae2da8f92ce4af278d3929ab8c5973f.mp4';
- // } else if (this.currentVideoIndex === 1) {
- // this.gifUrl = 'http://121.36.251.245:9000/minlong/tenant_1/general_uploads/5273282d971441249aeadf35a7574f01.gif';
- // } else if (this.currentVideoIndex === 2) {
- // this.gifUrl = 'http://121.36.251.245:9000/minlong/tenant_1/general_uploads/5273282d971441249aeadf35a7574f01.gif';
- // } else if (this.currentVideoIndex === 3) {
- // this.gifUrl = 'http://121.36.251.245:9000/minlong/tenant_1/general_uploads/5273282d971441249aeadf35a7574f01.gif';
- // } else if (this.currentVideoIndex === 4) {
- // this.gifUrl = 'http://121.36.251.245:9000/minlong/tenant_1/general_uploads/5273282d971441249aeadf35a7574f01.gif';
- // } else if (this.currentVideoIndex === 5) {
- // this.gifUrl = 'http://121.36.251.245:9000/minlong/tenant_1/general_uploads/5273282d971441249aeadf35a7574f01.gif';
- // }
-
- // 显示GIF图片
- this.showGif = true; */
-
- // 视频结束后直接显示"开始作答"按钮
- this.showStartRecordingButton = true;
- this.startCountdown();
- this.showAnswerButton = false;
- },
- // 添加新方法:开始倒计时
- startCountdown() {
- // 显示倒计时蒙层
- this.showCountdown = true;
- this.countdownValue = 10;
-
- // 开始倒计时
- this.countdownTimer = setInterval(() => {
- this.countdownValue--;
-
- if (this.countdownValue <= 0) {
- // 倒计时结束,清除定时器
- this.clearCountdown();
-
- // 隐藏"开始回答"按钮
- this.showStartRecordingButton = false;
-
- // 开始录制
- this.startRecordingAnswer();
- }
- }, 1000);
- },
- // 添加新方法:清除倒计时
- clearCountdown() {
- if (this.countdownTimer) {
- clearInterval(this.countdownTimer);
- this.countdownTimer = null;
- }
- this.showCountdown = false;
- },
- // 修改 handleStartRecordingClick 方法,使其可以终止倒计时
- handleStartRecordingClick() {
- // 隐藏"开始回答"按钮
- this.showStartRecordingButton = false;
-
- // 如果倒计时正在进行,清除倒计时
- this.clearCountdown();
-
- // 直接开始录制
- this.startRecordingAnswer();
- },
- // 修复 stopRecordingAnswer 方法,确保录制正确停止并上传
- stopRecordingAnswer() {
- // 如果倒计时正在进行,先清除倒计时
- this.clearCountdown();
-
- // 检查录制时长
- const recordingDuration = this.getRecordingDuration();
- const minimumDuration = 5; // 最小录制时长(秒)
-
- if (recordingDuration < minimumDuration) {
- // 录制时间过短,显示提示
- uni.showToast({
- title: '录制时间过短,请至少录制5秒',
- icon: 'none',
- duration: 2000
- });
- // 不执行停止录制逻辑,继续录制
- return;
- }
-
- // 隐藏停止录制按钮
- this.showStopRecordingButton = false;
-
- // 停止录制计时器
- if (this.recordingTimer) {
- clearInterval(this.recordingTimer);
- this.recordingTimer = null;
- }
-
- // 根据平台选择不同的停止录制方法
- const systemInfo = uni.getSystemInfoSync();
- const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
-
- if (isMiniProgram) {
- // 小程序环境使用小程序的停止录制API
- this.stopMiniProgramRecording();
- } else {
- // H5/App环境使用MediaRecorder API
- this.stopBrowserRecording();
- }
-
- // 标记录制已停止
- this.isRecording = false;
- },
-
- // 添加新方法:开始录制用户回答
- startRecordingAnswer() {
- console.log('开始录制用户回答');
- this.isRecording = true;
-
- // 记录录制开始时间
- this.recordingStartTime = Date.now();
- this.recordingTimerCount = 0;
- this.remainingTime = this.maxRecordingTime;
-
- // 启动计时器,每秒更新计时
- this.recordingTimer = setInterval(() => {
- this.recordingTimerCount++;
- this.remainingTime = Math.max(0, this.maxRecordingTime - this.recordingTimerCount);
-
- // 更新UI显示录制时长和剩余时间
- this.recordingTimeDisplay = this.formatTime(this.recordingTimerCount) +
- ' / ' + this.formatTime(this.maxRecordingTime);
-
- // 检查是否达到最大录制时间
- if (this.recordingTimerCount >= this.maxRecordingTime) {
- console.log('已达到最大录制时间(60秒),自动停止录制');
- this.stopRecordingAnswer();
- }
- }, 1000);
-
- // 显示录制中的提示
- // uni.showLoading({
- // title: '正在录制...',
- // mask: true
- // });
-
- // 根据平台选择不同的录制方法
- const systemInfo = uni.getSystemInfoSync();
- const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
-
- if (isMiniProgram) {
- // 小程序环境使用小程序的录制API
- this.startMiniProgramRecording();
- } else {
- // H5/App环境使用MediaRecorder API
- this.startBrowserRecording();
- }
-
- // 显示停止录制按钮
- this.showStopRecordingButton = true;
- },
- // 添加一个新方法:重置相机组件
- resetCamera() {
- console.log('重置相机组件');
-
- // 先完全移除相机组件
- this.useMiniProgramCameraComponent = false;
-
- // 释放相机上下文
- if (this.cameraContext) {
- this.cameraContext = null;
- }
-
- // 延迟后重新创建相机组件
- setTimeout(() => {
- this.useMiniProgramCameraComponent = true;
-
- // 再次延迟创建相机上下文,确保组件已完全渲染
- setTimeout(() => {
- this.cameraContext = uni.createCameraContext();
- console.log('相机组件已重置');
- }, 500);
- }, 500);
- },
- // 修改 startMiniProgramRecording 方法
- startMiniProgramRecording() {
- console.log('开始小程序录制方法');
-
- // 获取平台信息
- const systemInfo = uni.getSystemInfoSync();
- const isIOS = systemInfo.platform === 'ios';
-
- // 在iOS上,先重置相机
- if (isIOS) {
- // 先重置相机组件
- this.resetCamera();
-
- // 延迟执行录制,给相机组件足够的初始化时间
- setTimeout(() => {
- this.actualStartRecording(isIOS);
- }, 1000);
- } else {
- // Android直接开始
- this.actualStartRecording(isIOS);
- }
- },
- // 添加新方法:实际开始录制
- actualStartRecording(isIOS) {
- if (!this.cameraContext) {
- this.cameraContext = uni.createCameraContext();
- console.log('创建新的相机上下文');
- }
-
- // 确保有录音权限
- uni.getSetting({
- success: (res) => {
- const hasRecordAuth = res.authSetting['scope.record'];
- const hasCameraAuth = res.authSetting['scope.camera'];
-
- if (!hasRecordAuth || !hasCameraAuth) {
- console.warn('缺少必要权限,请求权限');
- this.requestMiniProgramPermissions();
- return;
- }
-
- // 在iOS上,先检查相机状态
- if (isIOS) {
- console.log('iOS: 检查相机状态');
-
- // 使用最简单的选项,设置最大录制时间为5分钟
- const options = {
- timeout: 300000, // 300秒超时 (5分钟)
- quality: 'low', // 降低质量
- compressed: true,
- success: () => {
- console.log('iOS录制开始成功');
- },
- fail: (err) => {
- console.error('iOS录制失败:', err);
-
- // 如果失败,尝试使用不同的方法
- this.useAlternativeRecordingMethod();
- }
- };
-
- try {
- console.log('尝试开始录制');
- this.recorder = this.cameraContext.startRecord(options);
- } catch (e) {
- console.error('开始录制异常:', e);
- this.useAlternativeRecordingMethod();
- }
- } else {
- // Android使用标准选项,设置最大录制时间为5分钟
- const options = {
- timeout: 300000, // 300秒超时 (5分钟)
- quality: 'medium',
- compressed: true,
- success: () => {
- console.log('Android录制开始成功');
- },
- fail: (err) => {
- console.error('Android录制失败:', err);
- uni.showToast({
- title: '录制失败,请检查相机权限',
- icon: 'none'
- });
- this.proceedToNextQuestion();
- }
- };
-
- this.recorder = this.cameraContext.startRecord(options);
- }
- }
- });
- },
- // 添加新方法:使用替代录制方法
- useAlternativeRecordingMethod() {
- console.log('使用替代录制方法');
-
- // 在iOS上,可以尝试使用chooseVideo API作为备选
- uni.showActionSheet({
- itemList: ['使用相册中的视频', '跳过此问题'],
- success: (res) => {
- if (res.tapIndex === 0) {
- // 选择相册中的视频
- uni.chooseVideo({
- sourceType: ['album'],
- maxDuration: 300, // 从60秒改为300秒
- camera: 'front',
- success: (res) => {
- console.log('选择视频成功:', res.tempFilePath);
- // 停止录制状态
- this.isRecording = false;
- this.showStopRecordingButton = false;
-
- // 上传选择的视频
- this.uploadRecordedVideo(res.tempFilePath);
- },
- fail: () => {
- console.log('用户取消选择视频');
- this.proceedToNextQuestion();
- }
- });
- } else {
- // 跳过此问题
- console.log('用户选择跳过问题');
- this.proceedToNextQuestion();
- }
- },
- fail: () => {
- console.log('操作取消');
- this.proceedToNextQuestion();
- }
- });
- },
- // 添加新方法:请求小程序权限
- requestMiniProgramPermissions() {
- // 请求录音权限
- uni.authorize({
- scope: 'scope.record',
- success: () => {
- console.log('录音权限已获取');
-
- // 请求相机权限
- uni.authorize({
- scope: 'scope.camera',
- success: () => {
- console.log('相机权限已获取');
- // 权限都获取到后,开始录制
- this.startMiniProgramRecording();
- },
- fail: (err) => {
- console.error('相机权限获取失败:', err);
- this.showPermissionDialog('相机');
- }
- });
- },
- fail: (err) => {
- console.error('录音权限获取失败:', err);
- this.showPermissionDialog('录音');
- }
- });
- },
- // 修改浏览器环境下的录制方法
- startBrowserRecording() {
- if (!this.cameraStream) {
- console.error('没有可用的摄像头流');
- uni.showToast({
- title: '录制失败,摄像头未就绪',
- icon: 'none'
- });
- this.proceedToNextQuestion();
- return;
- }
-
- try {
- // 检查流中是否包含音频轨道
- const hasAudio = this.cameraStream.getAudioTracks().length > 0;
- if (!hasAudio) {
- console.warn('警告:媒体流中没有音频轨道,尝试重新获取带音频的媒体流');
-
- // 尝试重新获取带音频的媒体流
- navigator.mediaDevices.getUserMedia({
- audio: {
- echoCancellation: true,
- noiseSuppression: true,
- autoGainControl: true
- },
- video: true
- })
- .then(newStream => {
- // 检查新流是否包含音频轨道
- const audioTracks = newStream.getAudioTracks();
- if (audioTracks.length > 0) {
- console.log('成功获取音频轨道:', audioTracks[0].label);
-
- // 合并视频和音频轨道
- const videoTrack = this.cameraStream.getVideoTracks()[0];
- const audioTrack = newStream.getAudioTracks()[0];
-
- // 创建新的媒体流,包含视频和音频轨道
- const combinedStream = new MediaStream();
- if (videoTrack) combinedStream.addTrack(videoTrack);
- if (audioTrack) combinedStream.addTrack(audioTrack);
-
- this.cameraStream = combinedStream;
-
- // 更新视频元素的源
- const videoElement = this.$refs.userCameraVideo;
- if (videoElement) {
- videoElement.srcObject = combinedStream;
- videoElement.muted = true; // 避免回声,但仍然录制声音
- }
-
- // 继续录制过程
- this.setupMediaRecorder(combinedStream);
- } else {
- console.warn('仍然无法获取音频轨道');
- // 使用现有流继续
- this.setupMediaRecorder(this.cameraStream);
- }
- })
- .catch(err => {
- console.error('获取音频失败:', err);
- // 使用现有流继续
- this.setupMediaRecorder(this.cameraStream);
- });
- } else {
- console.log('检测到音频轨道,直接使用');
- // 已有音频轨道,直接使用
- this.setupMediaRecorder(this.cameraStream);
- }
- } catch (error) {
- console.error('浏览器录制失败:', error);
- uni.showToast({
- title: '录制失败,浏览器可能不支持此功能',
- icon: 'none'
- });
- this.proceedToNextQuestion();
- }
- },
- // 修改 setupMediaRecorder 方法
- setupMediaRecorder(stream) {
- // 检查流中的轨道
- const videoTracks = stream.getVideoTracks();
- const audioTracks = stream.getAudioTracks();
-
- console.log('设置MediaRecorder - 视频轨道:', videoTracks.length, '音频轨道:', audioTracks.length);
-
- // 尝试使用支持度更广的编码格式
- let mimeType = '';
- const supportedTypes = [
- 'video/webm;codecs=vp9,opus',
- 'video/webm;codecs=vp8,opus',
- 'video/webm;codecs=h264,opus',
- 'video/mp4;codecs=h264,aac',
- 'video/webm',
- 'video/mp4'
- ];
-
- for (const type of supportedTypes) {
- if (MediaRecorder.isTypeSupported(type)) {
- mimeType = type;
- console.log('使用支持的MIME类型:', mimeType);
- break;
- }
- }
-
- // 创建MediaRecorder实例,设置较低的比特率以减小文件大小
- const options = {
- mimeType: mimeType || '',
- audioBitsPerSecond: 64000, // 降低音频比特率
- videoBitsPerSecond: 1000000, // 降低视频比特率到1Mbps
- };
-
- try {
- this.mediaRecorder = new MediaRecorder(stream, options);
- console.log('MediaRecorder创建成功,使用选项:', options);
- } catch (e) {
- console.warn('使用指定选项创建MediaRecorder失败,尝试使用默认选项');
- this.mediaRecorder = new MediaRecorder(stream);
- }
-
- // 存储录制的数据块
- this.recordedChunks = [];
-
- // 监听数据可用事件
- this.mediaRecorder.ondataavailable = (event) => {
- if (event.data && event.data.size > 0) {
- this.recordedChunks.push(event.data);
- console.log(`收到数据块: ${event.data.size} 字节`);
- }
- };
-
- // 监听录制停止事件
- this.mediaRecorder.onstop = async () => {
- console.log('MediaRecorder停止,数据块数量:', this.recordedChunks.length);
-
- if (this.recordedChunks.length === 0) {
- console.error('没有录制到数据');
- uni.showToast({
- title: '录制失败,未捕获到数据',
- icon: 'none'
- });
- this.proceedToNextQuestion();
- return;
- }
-
- // 创建Blob对象
- const mimeType = this.mediaRecorder.mimeType || 'video/webm';
- const blob = new Blob(this.recordedChunks, { type: mimeType });
- console.log('创建Blob,原始大小:', blob.size, '类型:', mimeType);
-
- // 显示压缩中提示
- uni.showLoading({
- title: '正在处理视频...',
- mask: true
- });
-
- try {
- // 压缩视频
- const compressedBlob = await this.compressVideo(blob);
-
- // 将Blob转换为File对象
- const fileName = `answer_${this.currentVideoIndex}_${Date.now()}.webm`;
- const file = new File([compressedBlob], fileName, { type: mimeType });
-
- // 隐藏压缩提示
- uni.hideLoading();
-
- // 上传文件
- this.uploadRecordedVideo(file);
- } catch (error) {
- console.error('视频处理失败:', error);
- uni.hideLoading();
-
- // 如果压缩失败,使用原始视频
- const fileName = `answer_${this.currentVideoIndex}_${Date.now()}.webm`;
- const file = new File([blob], fileName, { type: mimeType });
- this.uploadRecordedVideo(file);
- }
- };
-
- // 监听错误
- this.mediaRecorder.onerror = (event) => {
- console.error('MediaRecorder错误:', event.error);
- };
-
- // 开始录制
- try {
- this.mediaRecorder.start(1000); // 每秒触发一次dataavailable事件
- console.log('MediaRecorder开始录制');
-
- // 设置最大录制时间为60秒
- // 注意:我们已经在startRecordingAnswer方法中设置了全局计时器
- // 这里作为备份机制,确保即使全局计时器失效,也能停止录制
- this.mediaRecorderTimeout = setTimeout(() => {
- if (this.mediaRecorder && this.mediaRecorder.state === 'recording') {
- console.log('MediaRecorder备份超时机制触发,停止录制');
- this.mediaRecorder.stop();
- }
- }, 300000); // 300秒 (5分钟)
- } catch (e) {
- console.error('开始录制失败:', e);
- }
- },
- // 添加新方法:停止录制用户回答
- stopRecordingAnswer() {
- console.log('停止录制用户回答');
- if (this.countdownTimer) {
- clearInterval(this.countdownTimer);
- this.countdownTimer = null;
- this.showCountdown = false;
- }
-
- // 检查录制时长
- const recordingDuration = this.getRecordingDuration();
- const minimumDuration = 5; // 最小录制时长(秒),从3秒改为5秒
-
- if (recordingDuration < minimumDuration) {
- // 录制时间过短,显示提示
- uni.showToast({
- title: '录制时间过短,请至少录制5秒',
- icon: 'none',
- duration: 2000
- });
- // 不执行停止录制逻辑,继续录制
- return;
- }
-
- // 隐藏停止录制按钮
- this.showStopRecordingButton = false;
-
- // 停止录制计时器
- if (this.recordingTimer) {
- clearInterval(this.recordingTimer);
- this.recordingTimer = null;
- }
-
- // 根据平台选择不同的停止录制方法
- const systemInfo = uni.getSystemInfoSync();
- const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
-
- if (isMiniProgram) {
- // 小程序环境使用小程序的停止录制API
- this.stopMiniProgramRecording();
- } else {
- // H5/App环境使用MediaRecorder API
- this.stopBrowserRecording();
- }
-
- // 标记录制已停止
- this.isRecording = false;
- },
- // 添加新方法:获取录制时长
- getRecordingDuration() {
- // 如果有明确的录制开始时间,计算实际录制时长
- if (this.recordingStartTime) {
- return (Date.now() - this.recordingStartTime) / 1000;
- }
-
- // 如果没有明确记录开始时间,尝试从视频元素获取
- if (this.mediaRecorder && this.$refs.userCameraVideo) {
- return this.$refs.userCameraVideo.currentTime || 0;
- }
-
- // 如果无法获取准确时长,返回估计值(如果有计时器)
- if (this.recordingTimerCount) {
- return this.recordingTimerCount;
- }
-
- // 默认返回0
- return 0;
- },
- // 添加新方法:重置录制
- resetRecording() {
- // 保持录制状态,但重置计时器
- if (this.recordingTimer) {
- clearTimeout(this.recordingTimer);
- }
-
- // 重置录制开始时间
- this.recordingStartTime = Date.now();
- this.recordingTimerCount = 0;
-
- // 如果是浏览器环境,需要重置MediaRecorder
- if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
- // 停止当前录制
- this.mediaRecorder.stop();
-
- // 清空已录制的数据块
- this.recordedChunks = [];
-
- // 短暂延迟后重新开始录制
- setTimeout(() => {
- this.startBrowserRecording();
- }, 500);
- }
- // 如果是小程序环境,需要重置相机录制
- else if (this.cameraContext) {
- // 停止当前录制
- this.cameraContext.stopRecord({
- success: () => {
- console.log('重置录制:停止当前录制成功');
- // 短暂延迟后重新开始录制
- setTimeout(() => {
- this.startMiniProgramRecording();
- }, 500);
- },
- fail: (err) => {
- console.error('重置录制:停止当前录制失败', err);
- // 尝试直接重新开始录制
- this.startMiniProgramRecording();
- }
- });
- }
-
- // 显示提示
- uni.showToast({
- title: '请重新开始回答',
- icon: 'none',
- duration: 2000
- });
- },
- // 修复 completeRecordingStop 方法,确保视频正确上传和处理
- completeRecordingStop() {
- console.log('完成录制停止');
-
- // 隐藏停止录制按钮
- this.showStopRecordingButton = false;
-
- // 停止录制计时器
- if (this.recordingTimer) {
- clearInterval(this.recordingTimer);
- this.recordingTimer = null;
- }
-
- // 标记录制已停止
- this.isRecording = false;
-
- // 显示上传中状态
- this.showUploadStatus = true;
- this.uploadStatusText = '正在处理视频...';
- this.isUploading = true;
-
- // 根据平台选择不同的停止录制方法
- const systemInfo = uni.getSystemInfoSync();
- const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
-
- if (isMiniProgram) {
- // 小程序环境使用小程序的停止录制API
- this.stopMiniProgramRecording();
- } else {
- // H5/App环境使用MediaRecorder API
- this.stopBrowserRecording();
- }
- },
- // 修复 stopMiniProgramRecording 方法,确保小程序环境下正确停止录制
- stopMiniProgramRecording() {
- console.log('停止小程序录制');
-
- if (!this.cameraContext) {
- console.error('相机上下文不存在');
- this.handleRecordingError(new Error('相机上下文不存在'));
- return;
- }
-
- try {
- // 显示加载提示
- uni.showLoading({
- title: '正在处理视频...',
- mask: true
- });
-
- // 停止录制
- this.cameraContext.stopRecord({
- success: (res) => {
- console.log('停止录制成功:', res);
-
- // 隐藏加载提示
- uni.hideLoading();
-
- // 获取视频临时路径
- const tempVideoPath = res.tempVideoPath || res.tempFilePath;
-
- if (tempVideoPath) {
- console.log('获取到视频临时路径:', tempVideoPath);
-
- // 上传视频
- this.uploadRecordedVideo(tempVideoPath);
- } else {
- console.error('未获取到视频临时路径');
- this.handleRecordingError(new Error('未获取到视频临时路径'));
- }
- },
- fail: (err) => {
- console.error('停止录制失败:', err);
- uni.hideLoading();
- this.handleRecordingError(err);
- }
- });
- } catch (e) {
- console.error('停止录制异常:', e);
- uni.hideLoading();
- this.handleRecordingError(e);
- }
- },
- // 添加新方法:停止浏览器录制
- stopBrowserRecording() {
- if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
- this.mediaRecorder.stop();
- console.log('浏览器录制停止成功');
- } else {
- console.error('MediaRecorder不存在或已经停止');
- this.proceedToNextQuestion();
- }
- },
- // 修复 uploadRecordedVideo 方法,确保视频正确上传到服务器
- uploadRecordedVideo(videoPath) {
- console.log('开始上传录制的视频:', videoPath);
-
- // 保存最后上传的视频路径,用于可能的重试
- this.lastVideoToRetry = videoPath;
-
- // 显示上传状态
- this.showUploadStatus = true;
- this.uploadStatusText = '正在上传视频...';
- this.isUploading = true;
-
- // 保存上传状态到本地存储
- this.saveUploadStatus();
-
- // 获取用户信息和租户ID
- const tenant_id = uni.getStorageSync('tenant_id') || '1';
- const openid = uni.getStorageSync('userInfo') ? JSON.parse(uni.getStorageSync('userInfo')).openid : '';
- const application_id = uni.getStorageSync('appId') || '';
-
- // 使用uni.uploadFile上传视频
- const uploadTask = uni.uploadFile({
- url: `${apiBaseUrl}/api/upload/`,
- filePath: videoPath,
- name: 'file',
- formData: {
- tenant_id: tenant_id,
- openid: openid,
- application_id: application_id,
- biz_type: 'interview_video',
- video_duration: this.recordingTimerCount || 0,
- has_audio: 'true' // 明确标记包含音频
- },
- success: (uploadRes) => {
- console.log('视频上传成功:', uploadRes);
-
- try {
- // 解析响应数据
- const result = typeof uploadRes.data === 'string' ? JSON.parse(uploadRes.data) : uploadRes.data;
-
- if ((result.success || result.code === 2000) && (result.data?.url || result.data?.permanent_link)) {
- // 上传成功,获取视频URL
- const videoUrl = result.data.url || result.data.permanent_link || '';
- console.log('视频URL:', videoUrl);
-
- // 更新上传状态
- this.uploadStatusText = '视频处理完成,正在分析...';
-
- // 保存上传状态
- this.saveUploadStatus();
-
- // 提交视频到AI语音交互接口
- this.submitToAiVoiceInteraction(videoUrl);
- } else {
- console.error('上传响应格式错误:', result);
- const errorMsg = result.msg || result.message || '上传响应格式错误';
- this.handleUploadError(new Error(errorMsg));
- }
- } catch (e) {
- console.error('解析上传响应失败:', e);
- this.handleUploadError(e);
- }
- },
- fail: (err) => {
- console.error('视频上传失败:', err);
-
- // 提供更友好的错误信息
- let errorMessage = '网络错误,请检查网络连接';
- if (err.errMsg) {
- if (err.errMsg.includes('timeout')) {
- errorMessage = '上传超时,请检查网络连接';
- } else if (err.errMsg.includes('fail')) {
- errorMessage = '上传失败: ' + err.errMsg;
- }
- }
-
- this.handleUploadError(new Error(errorMessage));
- },
- complete: () => {
- // 隐藏上传状态
- this.showUploadStatus = false;
- this.isUploading = false;
-
- // 更新上传状态
- this.saveUploadStatus();
- }
- });
-
- // 监听上传进度
- uploadTask.onProgressUpdate((res) => {
- console.log('上传进度:', res.progress);
- this.uploadStatusText = `正在上传视频... ${res.progress}%`;
-
- // 如果上传速度过慢,提供提示
- if (res.progress < 10 && res.totalTimeMs > 10000) {
- this.uploadStatusText = `上传速度较慢,请耐心等待... ${res.progress}%`;
- }
- });
- },
-
- // 修改 processUploadQueue 方法,添加后台上传支持
- processUploadQueue() {
- // 如果队列为空,结束处理
- if (this.uploadQueue.length === 0) {
- this.isUploading = false;
- this.showUploadStatus = false;
-
- // 清除上传状态
- try {
- uni.removeStorageSync('videoUploadStatus');
- } catch (e) {
- console.error('清除上传状态失败:', e);
- }
-
- // 发送上传完成通知
- this.notifyUploadComplete();
- return;
- }
-
- // 标记为正在上传
- this.isUploading = true;
- this.showUploadStatus = true;
-
- // 获取队列中的第一个任务
- const task = this.uploadQueue[0];
-
- // 更新任务状态
- this.uploadStatus[task.id] = 'uploading';
- this.updateUploadStatusText();
-
- // 增加尝试次数
- task.attempts++;
-
- // 根据文件类型选择上传方法
- if (typeof task.file !== 'string') {
- // 浏览器环境,使用XMLHttpRequest上传
- this.uploadFileWithXHR(task);
- } else {
- // 小程序环境,使用uni.uploadFile上传
- this.uploadFileWithUni(task);
- }
-
- // 更新上传状态到本地存储
- this.saveUploadStatus();
- },
-
- // 添加新方法:发送上传完成通知
- notifyUploadComplete() {
- // 使用uni.postMessage在页面间通信(小程序环境)
- try {
- uni.$emit('videoUploadComplete', {
- timestamp: Date.now()
- });
-
- console.log('发送上传完成通知');
- } catch (e) {
- console.error('发送上传完成通知失败:', e);
- }
-
- // 如果在App环境,可以使用本地通知
- const systemInfo = uni.getSystemInfoSync();
- if (systemInfo.platform === 'android' || systemInfo.platform === 'ios') {
- // 检查是否支持本地通知
- if (plus && plus.push) {
- plus.push.createMessage('视频上传完成', '您的面试视频已成功上传', {});
- }
- }
- },
-
- // 添加新方法:使用XMLHttpRequest上传文件
- uploadFileWithXHR(task) {
- // 获取用户信息
- const userInfo = uni.getStorageSync('userInfo');
- const openid = userInfo ? (JSON.parse(userInfo).openid || '') : '';
- const tenant_id = uni.getStorageSync('tenant_id') || '1';
-
- // 创建FormData
- const formData = new FormData();
- formData.append('file', task.file);
- formData.append('openid', openid);
- formData.append('tenant_id', tenant_id);
- formData.append('application_id', uni.getStorageSync('appId'));
- formData.append('question_id', task.questionId);
- formData.append('video_duration', this.recordingTimerCount || 0);
- formData.append('has_audio', 'true'); // 明确标记包含音频
-
- // 创建XMLHttpRequest
- const xhr = new XMLHttpRequest();
- xhr.open('POST', `${apiBaseUrl}/api/upload/`, true);
- xhr.timeout = 120000; // 2分钟超时
-
- // 监听上传进度
- xhr.upload.onprogress = (event) => {
- if (event.lengthComputable) {
- const percentComplete = Math.round((event.loaded / event.total) * 100);
- this.uploadProgress[task.id] = percentComplete;
- this.updateUploadStatusText();
- }
- };
-
- // 监听请求完成
- xhr.onload = () => {
- if (xhr.status === 200) {
- try {
- const res = JSON.parse(xhr.responseText);
- console.log('上传响应:', res);
- if (res.code === 2000) {
- // 获取上传后的视频URL
- const videoUrl = res.data.url || res.data.photoUrl || '';
- if (videoUrl) {
- // 上传成功,更新状态
- this.uploadStatus[task.id] = 'success';
- this.updateUploadStatusText();
-
- // 提交到面试接口
- this.submitVideoToInterview(videoUrl, task);
- } else {
- this.handleUploadFailure(task, '视频URL获取失败');
- }
- } else {
- this.handleUploadFailure(task, res.msg || '上传失败');
- }
- } catch (e) {
- this.handleUploadFailure(task, '解析响应失败');
- }
- } else {
- this.handleUploadFailure(task, 'HTTP状态: ' + xhr.status);
- }
- };
-
- // 监听错误
- xhr.onerror = () => {
- this.handleUploadFailure(task, '网络错误');
- };
-
- // 监听超时
- xhr.ontimeout = () => {
- this.handleUploadFailure(task, '上传超时');
- };
-
- // 发送请求
- xhr.send(formData);
- },
-
- // 添加新方法:使用uni.uploadFile上传文件
- uploadFileWithUni(task) {
- // 获取用户信息
- const userInfo = uni.getStorageSync('userInfo');
- const openid = userInfo ? (JSON.parse(userInfo).openid || '') : '';
- const tenant_id = uni.getStorageSync('tenant_id') || '1';
-
- // 创建上传任务
- const uploadTask = uni.uploadFile({
- url: `${apiBaseUrl}/api/upload/`,
- filePath: task.file,
- name: 'file',
- formData: {
- openid: openid,
- tenant_id: tenant_id,
- application_id: uni.getStorageSync('appId'),
- question_id: task.questionId,
- video_duration: this.recordingTimerCount || 0,
- has_audio: 'true' // 明确标记包含音频
- },
- success: (uploadRes) => {
- try {
- const res = JSON.parse(uploadRes.data);
- console.log('上传响应:', res);
- if (res.code === 2000) {
- // 获取上传后的视频URL
- const videoUrl = res.data.permanent_link || res.data.url || '';
- if (videoUrl) {
- // 上传成功,更新状态
- this.uploadStatus[task.id] = 'success';
- this.updateUploadStatusText();
-
- // 提交到面试接口
- this.submitVideoToInterview(videoUrl, task);
- } else {
- this.handleUploadFailure(task, '视频URL获取失败');
- }
- } else {
- this.handleUploadFailure(task, res.msg || '上传失败');
- }
- } catch (e) {
- this.handleUploadFailure(task, '解析响应失败');
- }
- },
- fail: (err) => {
- this.handleUploadFailure(task, err.errMsg || '上传失败');
- }
- });
-
- // 监听上传进度
- uploadTask.onProgressUpdate((res) => {
- this.uploadProgress[task.id] = res.progress;
- this.updateUploadStatusText();
- });
- },
-
- // 添加新方法:处理上传失败
- handleUploadFailure(task, errorMsg) {
- console.error('上传失败:', errorMsg);
-
- // 更新任务状态
- this.uploadStatus[task.id] = 'failed';
- this.updateUploadStatusText();
-
- // 检查是否还有重试机会
- if (task.attempts < task.maxAttempts) {
- console.log(`将在5秒后重试上传,当前尝试次数: ${task.attempts}/${task.maxAttempts}`);
-
- // 5秒后重试
- setTimeout(() => {
- // 重置进度
- this.uploadProgress[task.id] = 0;
-
- // 重新开始上传
- if (typeof task.file !== 'string') {
- this.uploadFileWithXHR(task);
- } else {
- this.uploadFileWithUni(task);
- }
- }, 5000);
- } else {
- // 超过最大重试次数,移除任务并继续处理队列
- console.log('超过最大重试次数,放弃上传');
-
- // 显示错误提示
- uni.showToast({
- title: '视频上传失败,请稍后重试',
- icon: 'none',
- duration: 2000
- });
-
- // 从队列中移除当前任务
- this.uploadQueue.shift();
-
- // 继续处理队列中的下一个任务
- this.processUploadQueue();
- }
- },
-
- // 修改 submitVideoToInterview 方法
- submitVideoToInterview(videoUrl, task = null) {
- console.log('提交视频URL到面试接口:', videoUrl);
-
- // 确定问题ID
- let questionId;
- if (task) {
- questionId = task.questionId;
- } else {
- // 根据当前视频索引映射到正确的问题ID(兼容旧代码)
- switch(this.currentVideoIndex) {
- case 1:
- questionId = 36;
- break;
- case 2:
- questionId = 11;
- break;
- case 3:
- questionId = 12;
- break;
- case 4:
- questionId = 13;
- break;
- default:
- questionId = 10;
- }
- }
-
- // 准备请求参数
- const requestData = {
- application_id: uni.getStorageSync('appId'),
- question_id: questionId,
- video_url: videoUrl,
- tenant_id: uni.getStorageSync('tenant_id') || '1',
- has_audio: true // 明确标记包含音频
- };
-
- // 首先提交到面试接口
- /* uni.request({
- url: `${apiBaseUrl}/api/job/upload_video`,
- method: 'POST',
- data: requestData,
- header: {
- 'content-type': 'application/x-www-form-urlencoded'
- },
- success: (res) => {
- console.log('面试接口提交成功:', res);
-
- if (res.data.code === 0 || res.data.code === 2000) {
- // 提交成功
- if (task) {
- // 从队列中移除当前任务
- this.uploadQueue.shift();
-
- // 继续处理队列中的下一个任务
- this.processUploadQueue();
- } else {
- // 兼容旧代码的处理逻辑
- uni.showToast({
- title: '回答已提交',
- icon: 'success'
- });
-
- // 保存最后上传的视频URL
- this.lastUploadedVideoUrl = videoUrl;
-
- // 隐藏重试按钮(如果之前显示了)
- this.showRetryButton = false;
- this.lastVideoToRetry = null;
- }
-
- // 提交到AI语音交互接口
-
- } else {
- // 提交失败
- if (task) {
- this.handleSubmitFailure(task, res.data.msg || '提交失败');
- } else {
- // 兼容旧代码的处理逻辑
- uni.showToast({
- title: res.data.msg || '提交失败,请重试',
- icon: 'none'
- });
-
- // 保存失败的视频URL,用于重试
- this.lastVideoToRetry = videoUrl;
-
- // 显示重试按钮
- this.showRetryButton = true;
- }
- }
- },
- fail: (err) => {
- console.error('面试接口提交失败:', err);
-
- if (task) {
- this.handleSubmitFailure(task, err.errMsg || '网络错误');
- } else {
- // 兼容旧代码的处理逻辑
- uni.hideLoading();
- uni.showToast({
- title: '网络错误,请重试',
- icon: 'none'
- });
-
- // 保存失败的视频URL,用于重试
- this.lastVideoToRetry = videoUrl;
-
- // 显示重试按钮
- this.showRetryButton = true;
- }
- }
- }); */
- this.submitToAiVoiceInteraction(videoUrl);
- },
-
- // 添加新方法:处理提交失败
- handleSubmitFailure(task, errorMsg) {
- console.error('提交失败:', errorMsg);
-
- // 更新任务状态
- this.uploadStatus[task.id] = 'failed';
- this.updateUploadStatusText();
-
- // 检查是否还有重试机会
- if (task.attempts < task.maxAttempts) {
- console.log(`将在5秒后重试提交,当前尝试次数: ${task.attempts}/${task.maxAttempts}`);
-
- // 5秒后重试
- setTimeout(() => {
- // 重新提交
- this.submitVideoToInterview(task.videoUrl, task);
- }, 5000);
- } else {
- // 超过最大重试次数,移除任务并继续处理队列
- console.log('超过最大重试次数,放弃提交');
-
- // 显示错误提示
- uni.showToast({
- title: '视频提交失败,请稍后重试',
- icon: 'none',
- duration: 2000
- });
-
- // 从队列中移除当前任务
- this.uploadQueue.shift();
-
- // 继续处理队列中的下一个任务
- this.processUploadQueue();
- }
- },
-
- // 添加新方法:更新上传状态文本
- updateUploadStatusText() {
- if (this.uploadQueue.length === 0) {
- this.uploadStatusText = '';
- return;
- }
-
- const currentTask = this.uploadQueue[0];
- const progress = this.uploadProgress[currentTask.id] || 0;
- const status = this.uploadStatus[currentTask.id] || 'pending';
-
- let statusText = '';
- switch (status) {
- case 'pending':
- statusText = '等待上传';
- break;
- case 'uploading':
- statusText = `上传中 ${progress}%`;
- break;
- case 'success':
- statusText = '上传成功,提交中...';
- break;
- case 'failed':
- statusText = `上传失败,${currentTask.attempts < currentTask.maxAttempts ? '即将重试' : '已放弃'}`;
- break;
- }
-
- this.uploadStatusText = `问题${currentTask.questionId - 9}:${statusText}`;
-
- // 如果队列中有多个任务,显示总数
- if (this.uploadQueue.length > 1) {
- this.uploadStatusText += ` (${this.uploadQueue.length}个视频待处理)`;
- }
- },
-
- // 修改 proceedToNextQuestion 方法
- proceedToNextQuestion() {
- console.log('准备跳转到下一页面');
-
- // 如果正在播放AI语音,不立即跳转
- if (this.isPlayingAiVoice) {
- console.log('AI语音正在播放,等待播放完成后再跳转');
- return;
- }
-
- // 不再等待上传队列完成,直接跳转
- // this.navigateToNextPage();
-
- // 如果有未完成的上传任务,在后台继续处理
- if (this.uploadQueue.length > 0) {
- console.log('上传队列将在后台继续处理...');
-
- // 保存上传状态到本地存储,以便在其他页面可以查看
- this.saveUploadStatus();
- }
- },
-
- // 修改 navigateToNextPage 方法
- navigateToNextPage() {
- console.log('准备导航到下一个页面');
-
- // 如果正在播放AI语音,不立即跳转
- if (this.isPlayingAiVoice) {
- console.log('AI语音正在播放,等待播放完成后再跳转');
- return;
- }
-
- console.log('导航到下一个页面');
- // 检查 selectedJob 的 id
- try {
- const currentJobDetail = uni.getStorageSync('selectedJob');
- const jobId = currentJobDetail ? JSON.parse(currentJobDetail).id : null;
-
- // 如果 id 为 9 或 10,直接跳转到 success 页面
- if (jobId === 9 || jobId === 10) {
- uni.navigateTo({
- url: '/pages/success/success',
- success: () => {
- console.log('成功跳转到成功页面');
- },
- fail: (err) => {
- console.error('跳转失败:', err);
- // 如果跳转失败,尝试其他页面
- this.handleNavigationFailure();
- }
- });
- return; // 提前返回,不执行后续代码
- }
- } catch (e) {
- console.error('解析 selectedJob 失败:', e);
- // 解析失败时继续默认跳转逻辑
- }
-
- // 原有的跳转逻辑
- uni.navigateTo({
- url: '/pages/posture-guide/posture-guide?uploading=' + (this.uploadQueue.length > 0 ? 'true' : 'false'),
- success: () => {
- console.log('成功跳转到结果页面');
- },
- fail: (err) => {
- console.error('跳转失败:', err);
- this.handleNavigationFailure();
- }
- });
- },
- // 添加处理导航失败的方法
- handleNavigationFailure() {
- // 尝试跳转到其他页面
- uni.navigateTo({
- url: '/pages/posture-guide/posture-guide',
- fail: (err2) => {
- console.error('备用跳转也失败:', err2);
-
- // 最后尝试返回上一页
- uni.navigateBack({
- delta: 1
- });
- }
- });
- },
- // 修改 handleAnswerButtonClick 方法
- handleAnswerButtonClick() {
- // 隐藏答题按钮
- this.showAnswerButton = false;
-
- // 显示简短提示
- uni.showToast({
- title: '面试完成',
- icon: 'success',
- duration: 500 // 只显示0.5秒
- });
-
- // 如果有最后上传的视频URL,提交到AI语音交互接口
- if (this.lastUploadedVideoUrl) {
- this.submitToAiVoiceInteraction(this.lastUploadedVideoUrl);
- } else {
- // 没有视频URL,直接跳转
- this.navigateToNextPage();
- }
- },
- // 处理相机错误
- handleCameraError(e) {
- console.error('相机错误:', e);
-
- // 获取平台信息
- const systemInfo = uni.getSystemInfoSync();
- const isIOS = systemInfo.platform === 'ios';
-
- if (isIOS) {
- console.log('iOS相机错误,尝试重新初始化');
-
- // 显示提示
- uni.showToast({
- title: '相机初始化中...',
- icon: 'loading',
- duration: 2000
- });
-
- // 重置相机
- this.resetCamera();
-
- // 如果正在录制,停止录制
- if (this.isRecording) {
- this.isRecording = false;
- this.showStopRecordingButton = false;
-
- // 提供替代选项
- setTimeout(() => {
- this.useAlternativeRecordingMethod();
- }, 1000);
- }
- } else {
- // 显示错误提示
- uni.showToast({
- title: '相机初始化失败,请检查权限设置',
- icon: 'none'
- });
-
- // 尝试备用选项
- this.tryFallbackOptions();
- }
- },
- // 添加新方法:尝试备用选项
- tryFallbackOptions() {
- // 检查环境
- const systemInfo = uni.getSystemInfoSync();
-
- // 在小程序环境中使用小程序API
- if (systemInfo.uniPlatform === 'mp-weixin' || systemInfo.uniPlatform === 'mp-alipay') {
- this.useMiniProgramCamera();
- }
- // 在H5环境中显示静态图像
- else {
- this.showStaticCameraPlaceholder();
- }
- },
- // 添加新方法:使用小程序相机API
- useMiniProgramCamera() {
- console.log('尝试使用小程序相机组件');
- // 这里需要在模板中添加小程序相机组件
- // 并设置一个标志来控制显示
- this.useMiniProgramCameraComponent = true;
- },
- // 添加新方法:显示静态图像
- showStaticCameraPlaceholder() {
- console.log('显示静态摄像头占位图');
- // 创建一个图像元素
- const img = document.createElement('img');
- img.src = '/static/images/camera-placeholder.png'; // 确保有这个图片资源
- img.className = 'static-camera-image';
- img.style.width = '100%';
- img.style.height = '100%';
- img.style.objectFit = 'cover';
-
- // 获取容器并添加图像
- const container = this.$refs.userCameraVideo.parentNode;
- container.appendChild(img);
- },
- // 处理视频时间更新事件
- handleTimeUpdate(e) {
- // 获取当前视频播放时间
- const currentTime = e.target.currentTime;
-
- // 如果正在录制,更新录制时间显示
- if (this.isRecording && this.recordingTimerCount) {
- this.recordingTimeDisplay = this.formatTime(this.recordingTimerCount);
- }
-
- // 根据当前播放的视频索引选择对应的字幕数组
- let currentSubtitles;
- if (this.currentVideoIndex === 0) {
- currentSubtitles = this.subtitles;
- } else if (this.currentVideoIndex === 1) {
- currentSubtitles = this.secondVideoSubtitles;
- } else if (this.currentVideoIndex === 2) {
- currentSubtitles = this.thirdVideoSubtitles;
- } else if (this.currentVideoIndex === 3) {
- currentSubtitles = this.fourthVideoSubtitles;
- } else if (this.currentVideoIndex === 4) {
- currentSubtitles = this.fifthVideoSubtitles;
- } else if (this.currentVideoIndex === 5) {
- currentSubtitles = this.sixthVideoSubtitles;
- } else {
- // 如果有更多视频,可以继续添加条件
- currentSubtitles = [];
- }
-
- // 查找当前时间应该显示的字幕
- const subtitle = currentSubtitles.find(
- sub => currentTime >= sub.startTime && currentTime < sub.endTime
- );
-
- // 更新当前字幕
- this.currentSubtitle = subtitle ? subtitle.text : '';
- },
- // Add a new method to handle the "Start Recording" button click
- handleStartRecordingClick() {
- // 隐藏"开始回答"按钮
- this.showStartRecordingButton = false;
- // 如果倒计时正在进行,清除倒计时
- this.clearCountdown();
-
- // 开始录制
- this.startRecordingAnswer();
- },
- // 修改 checkAudioPermission 方法,确保在录制前获取音频权限
- checkAudioPermission() {
- // 在小程序环境中
- const systemInfo = uni.getSystemInfoSync();
- const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
-
- if (isMiniProgram) {
- // 小程序环境下的权限请求
- uni.getSetting({
- success: (res) => {
- if (!res.authSetting['scope.record']) {
- uni.authorize({
- scope: 'scope.record',
- success: () => {
- console.log('录音权限已获取');
- },
- fail: (err) => {
- console.error('录音权限获取失败:', err);
- this.showPermissionDialog('录音');
- }
- });
- }
-
- if (!res.authSetting['scope.camera']) {
- uni.authorize({
- scope: 'scope.camera',
- success: () => {
- console.log('相机权限已获取');
- },
- fail: (err) => {
- console.error('相机权限获取失败:', err);
- this.showPermissionDialog('相机');
- }
- });
- }
- }
- });
- } else {
- // 浏览器环境下的权限请求
- // ... 保持原有代码不变
- }
- },
- // 添加新方法:测试音频输入
- testAudioInput() {
- if (!this.cameraStream) {
- console.warn('没有可用的媒体流,无法测试音频');
- return;
- }
-
- const audioTracks = this.cameraStream.getAudioTracks();
- if (audioTracks.length === 0) {
- console.warn('没有检测到音频轨道,尝试重新获取');
- this.tryGetAudioOnly();
- return;
- }
-
- console.log('音频轨道信息:', audioTracks[0].getSettings());
-
- // 创建音频上下文和分析器
- try {
- const AudioContext = window.AudioContext || window.webkitAudioContext;
- if (!AudioContext) {
- console.warn('浏览器不支持AudioContext');
- return;
- }
-
- const audioContext = new AudioContext();
- const analyser = audioContext.createAnalyser();
- const microphone = audioContext.createMediaStreamSource(this.cameraStream);
- microphone.connect(analyser);
-
- // 设置分析器
- analyser.fftSize = 256;
- const bufferLength = analyser.frequencyBinCount;
- const dataArray = new Uint8Array(bufferLength);
-
- // 检测音频输入
- let silenceCounter = 0;
- const checkAudio = () => {
- if (this.isRecording) return; // 如果正在录制,停止检测
-
- analyser.getByteFrequencyData(dataArray);
-
- // 计算平均音量
- let sum = 0;
- for (let i = 0; i < bufferLength; i++) {
- sum += dataArray[i];
- }
- const average = sum / bufferLength;
-
- if (average > 10) {
- console.log('检测到音频输入,音量:', average);
- silenceCounter = 0;
- } else {
- silenceCounter++;
- if (silenceCounter > 10) {
- console.warn('持续检测不到音频输入,可能麦克风未正常工作');
- silenceCounter = 0;
- }
- }
-
- // 继续检测
- requestAnimationFrame(checkAudio);
- };
-
- // 开始检测
- checkAudio();
- } catch (e) {
- console.error('音频测试失败:', e);
- }
- },
- // 添加新方法:尝试单独获取音频
- tryGetAudioOnly() {
- navigator.mediaDevices.getUserMedia({ audio: true })
- .then(audioStream => {
- // 如果已有视频流,合并音频和视频轨道
- if (this.cameraStream) {
- const videoTrack = this.cameraStream.getVideoTracks()[0];
- const audioTrack = audioStream.getAudioTracks()[0];
-
- // 创建新的媒体流,包含视频和音频轨道
- const combinedStream = new MediaStream();
- if (videoTrack) combinedStream.addTrack(videoTrack);
- if (audioTrack) combinedStream.addTrack(audioTrack);
-
- // 更新摄像头流
- this.cameraStream = combinedStream;
-
- // 更新视频元素的源
- const videoElement = this.$refs.userCameraVideo;
- if (videoElement) {
- videoElement.srcObject = combinedStream;
- videoElement.muted = true; // 避免回声,但仍然录制声音
- }
-
- console.log('成功合并音频和视频轨道');
- } else {
- console.warn('没有视频流可合并');
- }
- })
- .catch(err => {
- console.error('单独获取音频失败:', err);
- });
- },
- // 添加新方法:显示权限对话框
- showPermissionDialog(permissionType) {
- uni.showModal({
- title: '需要权限',
- content: `请允许使用${permissionType}权限,否则可能影响面试功能`,
- confirmText: '去设置',
- success: (res) => {
- if (res.confirm) {
- uni.openSetting({
- success: (settingRes) => {
- console.log('设置页面打开成功', settingRes);
- }
- });
- }
- }
- });
- },
- // 添加重试上传方法
- retryVideoUpload() {
- if (this.lastVideoToRetry) {
- // 隐藏重试按钮
- this.showRetryButton = false;
-
- // 显示加载提示
- uni.showLoading({
- title: '正在重新提交...',
- mask: true
- });
-
- // 重新提交视频
- this.submitVideoToInterview(this.lastVideoToRetry);
- } else {
- uni.showToast({
- title: '没有可重试的视频',
- icon: 'none'
- });
- }
- },
- // 添加一个新方法用于压缩视频
- async compressVideo(videoBlob) {
- // 如果视频大小小于某个阈值,直接返回原视频
- if (videoBlob.size < 5 * 1024 * 1024) { // 小于5MB
- return videoBlob;
- }
-
- console.log('开始压缩视频,原始大小:', videoBlob.size);
-
- // 创建一个视频元素来加载视频
- const videoElement = document.createElement('video');
- videoElement.muted = true;
- videoElement.autoplay = false;
-
- // 创建一个canvas元素用于绘制视频帧
- const canvas = document.createElement('canvas');
- const ctx = canvas.getContext('2d');
-
- // 设置视频源
- videoElement.src = URL.createObjectURL(videoBlob);
-
- return new Promise((resolve) => {
- videoElement.onloadedmetadata = () => {
- // 设置canvas尺寸为视频的一半
- const width = Math.floor(videoElement.videoWidth / 2);
- const height = Math.floor(videoElement.videoHeight / 2);
- canvas.width = width;
- canvas.height = height;
-
- // 创建MediaRecorder来录制canvas
- const stream = canvas.captureStream(15); // 15fps
-
- // 如果原视频有音轨,添加到新流中
- if (videoElement.captureStream) {
- const originalStream = videoElement.captureStream();
- const audioTracks = originalStream.getAudioTracks();
- if (audioTracks.length > 0) {
- stream.addTrack(audioTracks[0]);
- }
- }
-
- // 设置较低的比特率
- const options = {
- mimeType: 'video/webm;codecs=vp8,opus',
- audioBitsPerSecond: 64000,
- videoBitsPerSecond: 800000 // 800kbps
- };
-
- const mediaRecorder = new MediaRecorder(stream, options);
- const chunks = [];
-
- mediaRecorder.ondataavailable = (e) => {
- if (e.data.size > 0) {
- chunks.push(e.data);
- }
- };
-
- mediaRecorder.onstop = () => {
- const compressedBlob = new Blob(chunks, { type: 'video/webm' });
- console.log('视频压缩完成,压缩后大小:', compressedBlob.size);
- resolve(compressedBlob);
- };
-
- // 开始播放视频并录制
- videoElement.onplay = () => {
- mediaRecorder.start(100);
-
- // 绘制视频帧到canvas
- const drawFrame = () => {
- if (videoElement.paused || videoElement.ended) {
- mediaRecorder.stop();
- return;
- }
-
- ctx.drawImage(videoElement, 0, 0, width, height);
- requestAnimationFrame(drawFrame);
- };
-
- drawFrame();
- };
-
- videoElement.play();
- };
- });
- },
- // 修改 checkIOSCameraRecordPermission 方法
- checkIOSCameraRecordPermission() {
- const systemInfo = uni.getSystemInfoSync();
- if (systemInfo.platform !== 'ios') return;
-
- // 在iOS上,需要同时请求相机和录音权限
- uni.getSetting({
- success: (res) => {
- // 检查相机权限
- if (!res.authSetting['scope.camera']) {
- uni.authorize({
- scope: 'scope.camera',
- success: () => {
- console.log('iOS相机权限已获取');
- },
- fail: (err) => {
- console.error('iOS相机权限获取失败:', err);
- this.showPermissionDialog('相机');
- }
- });
- }
-
- // 检查录音权限
- if (!res.authSetting['scope.record']) {
- uni.authorize({
- scope: 'scope.record',
- success: () => {
- console.log('iOS录音权限已获取');
- },
- fail: (err) => {
- console.error('iOS录音权限获取失败:', err);
- this.showPermissionDialog('录音');
- }
- });
- }
- }
- });
- },
- // 添加新方法:检查并修复渲染问题
- checkAndFixRenderingIssues() {
- // 检查全局对象,防止渲染错误
- try {
- // 检查是否有全局变量u
- if (typeof u !== 'undefined' && u) {
- // 检查currentQuestion属性
- if (!u.currentQuestion) {
- console.log('修复: 创建缺失的currentQuestion对象');
- u.currentQuestion = {};
- }
- // 确保isImportant属性存在
- if (u.currentQuestion && typeof u.currentQuestion.isImportant === 'undefined') {
- console.log('修复: 设置缺失的isImportant属性');
- u.currentQuestion.isImportant = false;
- }
- }
- } catch (e) {
- console.log('防御性检查异常:', e);
- }
- },
- // 添加格式化时间的辅助方法
- formatTime(seconds) {
- if (!seconds && seconds !== 0) return '03:30'; // 默认显示03:30
- const minutes = Math.floor(seconds / 60);
- const remainingSeconds = seconds % 60;
- return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
- },
- // 添加新方法:保存上传状态到本地存储
- saveUploadStatus() {
- const uploadStatus = {
- isUploading: this.isUploading,
- uploadQueue: this.uploadQueue.length,
- timestamp: Date.now()
- };
-
- try {
- uni.setStorageSync('videoUploadStatus', JSON.stringify(uploadStatus));
- } catch (e) {
- console.error('保存上传状态失败:', e);
- }
- },
- // 修改 submitToAiVoiceInteraction 方法
- submitToAiVoiceInteraction(videoUrl) {
- console.log('提交视频到AI语音交互接口:', videoUrl);
-
- // 显示加载提示
- uni.showLoading({
- title: '面试官正在思考...',
- mask: true
- });
-
- // 获取用户信息和租户ID
- const tenant_id = uni.getStorageSync('tenant_id') || '1';
- const application_id = uni.getStorageSync('appId') || '98'; // 默认为98(报告)
-
- // 准备请求数据
- const requestData = {
- voice_url: videoUrl,
- tenant_id: tenant_id,
- application_id: application_id,
- scene_type: 'interview', // 场景类型:面试
- voice_type: 'longxiaoxia', // 角色:龙小侠
- conversation_history: this.conversationHistory // 添加对话历史
- };
-
- // 检查环境
- const systemInfo = uni.getSystemInfoSync();
- const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
-
- if (isMiniProgram) {
- // 小程序环境使用 uni.request
- uni.request({
- url: `${apiBaseUrl}/api/system/voice/mcp/interaction`, // 使用新的接口地址
- method: 'POST',
- data: requestData,
- header: {
- 'content-type': 'application/json' // 修改为JSON格式
- },
- success: (res) => {
- if (res.statusCode === 200) {
- this.handleAiInteractionResponse(res.data);
- } else {
- this.handleAiInteractionError(res.data);
- }
- },
- fail: (err) => {
- this.handleAiInteractionError(err);
- }
- });
- } else {
- // H5/App环境使用 XMLHttpRequest
- const xhr = new XMLHttpRequest();
- xhr.open('POST', `${apiBaseUrl}/api/system/voice/mcp/interaction`, true);
- xhr.timeout = 60000; // 60秒超时
- xhr.setRequestHeader('Content-Type', 'application/json');
-
- xhr.onload = () => {
- if (xhr.status === 200) {
- try {
- const response = JSON.parse(xhr.responseText);
- this.handleAiInteractionResponse(response);
- } catch (e) {
- console.error('解析AI响应失败:', e);
- this.handleAiInteractionError({ errMsg: '解析响应失败' });
- }
- } else {
- this.handleAiInteractionError({ errMsg: 'HTTP状态: ' + xhr.status });
- }
- };
-
- xhr.onerror = () => {
- this.handleAiInteractionError({ errMsg: '网络错误' });
- };
-
- xhr.ontimeout = () => {
- this.handleAiInteractionError({ errMsg: '请求超时' });
- };
-
- // 发送JSON格式的数据
- xhr.send(JSON.stringify(requestData));
- }
- },
- // 添加处理AI交互响应的方法
- handleAiInteractionResponse(data) {
- console.log('AI语音交互接口响应:', data);
- // 获取系统信息
- const systemInfo = uni.getSystemInfoSync();
- const isIOS = systemInfo.platform === 'ios';
- // 标记正在播放AI语音
- this.isPlayingAiVoice = true;
- // 隐藏加载提示
- uni.hideLoading();
-
- // 重置备选方法尝试标志
- this.hasTriedFallbackMethod = false;
-
- if (data && data.success) {
- // 保存AI回复数据
- this.aiText = data.ai_text || '';
- this.transcribedText = data.transcribed_text ? data.transcribed_text.text : '';
-
- // 记录对话历史
- this.conversationHistory.push({
- role: 'user',
- content: this.transcribedText
- });
- this.conversationHistory.push({
- role: 'assistant',
- content: this.aiText
- });
-
- // 获取AI语音URL
- const aiVoiceUrl = data.ai_voice_url || '';
- if (aiVoiceUrl) {
- // 构建完整的URL
- this.aiVoiceUrl = aiVoiceUrl.startsWith('http')
- ? aiVoiceUrl
- : `${apiBaseUrl}${aiVoiceUrl}`;
-
- console.log('AI语音URL:', this.aiVoiceUrl);
-
- // 显示AI回复文本作为字幕
- this.currentSubtitle = this.aiText;
-
- // 检查平台
- const systemInfo = uni.getSystemInfoSync();
- const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
-
- // 检查音频URL是否包含不支持的格式
- const isUnsupportedFormat = this.checkUnsupportedAudioFormat(this.aiVoiceUrl);
-
- if (isUnsupportedFormat && isMiniProgram) {
- console.warn('检测到小程序不支持的音频格式,直接使用文本显示');
- this.displayTextResponse();
- return;
- }
-
- // 根据平台选择不同的播放方法
- if (isMiniProgram) {
- // 小程序环境使用原生API
- if (isIOS) {
- this.playIOSMiniProgramAudio();
- } else {
- this.playMiniProgramAudio();
- }
- /* this.playMiniProgramAudio(); */
- } else {
- // H5/App环境使用通用方法
- this.playAiVoice();
- }
-
- // 重要:确保在AI语音播放期间不显示继续提问按钮
- this.showContinueQuestionButton = false;
- this.showEndInterviewButton = false;
- } else {
- console.warn('未获取到AI语音URL,使用文本显示');
- // 如果没有语音URL,显示文本回复
- this.displayTextResponse();
- }
- } else {
- console.error('AI语音交互失败:', data);
- // AI交互失败,显示继续提问按钮
- this.showContinueQuestionOptions();
-
- // 检查是否需要自动跳转
- this.checkPendingNavigation();
- }
- },
- // 修改 handleAiInteractionError 方法,不要直接跳转,而是显示继续提问选项
- handleAiInteractionError(err) {
- console.error('AI语音交互请求失败:', err);
- uni.hideLoading();
-
- // 显示错误提示
- uni.showToast({
- title: 'AI处理失败,请重试',
- icon: 'none',
- duration: 2000
- });
-
- // 请求失败,显示继续提问选项,而不是直接跳转
- this.showContinueQuestionOptions();
- },
- // 添加新方法:播放AI语音
- playAiVoice() {
- console.log('开始播放AI语音:', this.aiVoiceUrl);
-
- // 重置错误提示标记
- this.hasShownTextFallbackToast = false;
-
- // 标记正在播放AI语音
- this.isPlayingAiVoice = true;
-
- // 隐藏所有按钮
- this.showContinueQuestionButton = false;
- this.showEndInterviewButton = false;
-
- // 显示AI回复文本作为字幕
- this.currentSubtitle = this.aiText;
-
- // 检查音频URL是否有效
- if (!this.aiVoiceUrl || this.aiVoiceUrl.trim() === '') {
- console.error('无效的音频URL,直接显示文本');
- this.useTextFallbackAndNavigate();
- return;
- }
-
- // 获取系统信息
- const systemInfo = uni.getSystemInfoSync();
- const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
- const isIOS = systemInfo.platform === 'ios';
-
- // 根据平台选择播放方式
- if (isMiniProgram) {
- if (isIOS) {
- this.playIOSMiniProgramAudio();
- } else {
- this.playMiniProgramAudio();
- }
- } else if (isIOS) {
- this.playAiVoiceForIOS();
- } else {
- this.playAiVoiceForAndroid();
- }
- },
- // 新增方法:文本回退并导航
- useTextFallbackAndNavigate() {
- console.log('使用文本回退并准备导航');
-
- // 标记播放结束
- this.isPlayingAiVoice = false;
-
- // 显示友好提示
- if (!this.hasShownTextFallbackToast) {
- this.hasShownTextFallbackToast = true;
- uni.showToast({
- title: '为您显示文字回复',
- icon: 'none',
- duration: 2000
- });
- }
-
- // 显示完整文本
- this.currentSubtitle = this.aiText || '抱歉,AI回复内容加载失败';
-
- // 给用户一定时间阅读文本后自动跳转
- setTimeout(() => {
- this.navigateToNextPage();
- }, 5000); // 5秒后跳转
- },
- // 修改 handleIOSAudioPlaybackComplete 方法
- handleIOSAudioPlaybackComplete() {
- // 标记播放结束
- this.isPlayingAiVoice = false;
-
- // 延迟清空字幕
- setTimeout(() => {
- this.currentSubtitle = '';
- }, 1000);
-
- // 销毁音频播放器
- if (this.aiAudioPlayer) {
- try {
- this.aiAudioPlayer.destroy();
- } catch (e) {
- console.error('销毁iOS音频播放器失败:', e);
- }
- this.aiAudioPlayer = null;
- }
-
- // 直接导航到下一页
- this.navigateToNextPage();
- },
- // 修改 playMiniProgramAudio 方法
- playMiniProgramAudio() {
- console.log('使用小程序原生音频API播放:', this.aiVoiceUrl);
-
- try {
- const audioContext = wx.createInnerAudioContext();
-
- audioContext.autoplay = true;
- audioContext.src = this.aiVoiceUrl;
-
- audioContext.onPlay(() => {
- console.log('AI语音开始播放');
- this.currentSubtitle = this.aiText;
- });
-
- audioContext.onEnded(() => {
- console.log('AI语音播放结束');
- this.isPlayingAiVoice = false;
- this.currentSubtitle = '';
- audioContext.destroy();
-
- // 播放结束后直接导航
- this.navigateToNextPage();
- });
-
- audioContext.onError((err) => {
- console.error('AI语音播放错误:', err);
- audioContext.destroy();
- this.useTextFallbackAndNavigate();
- });
-
- // 设置超时处理
- setTimeout(() => {
- if (this.isPlayingAiVoice) {
- console.warn('音频播放超时,使用文本回退');
- this.useTextFallbackAndNavigate();
- }
- }, 5000);
-
- } catch (e) {
- console.error('小程序播放AI语音失败:', e);
- this.useTextFallbackAndNavigate();
- }
- },
- // 新增方法:导航到下一页
- navigateToNextPage() {
- // 这里添加导航逻辑
- console.log('准备导航到下一页');
-
- // 根据实际需求设置导航目标
- uni.navigateTo({
- url: '/pages/posture-guide/posture-guide',
- fail: (err) => {
- console.error('导航失败:', err);
- // 导航失败时的处理
- uni.showToast({
- title: '页面跳转失败',
- icon: 'none',
- duration: 2000
- });
- }
- });
- },
- // 新增方法:专门处理iOS小程序音频播放
- playIOSMiniProgramAudio() {
- console.log('iOS小程序环境:使用增强的音频处理方法');
-
- // 重置错误标记
- this.hasShownTextFallbackToast = false;
-
- try {
- // 创建音频上下文,使用wx API确保兼容性
- const audioContext = wx.createInnerAudioContext();
-
- // iOS小程序优化配置
- audioContext.autoplay = false;
- audioContext.obeyMuteSwitch = true; // iOS遵循静音开关
- audioContext.volume = 1.0;
-
- // 设置播放成功事件
- audioContext.onPlay(() => {
- console.log('iOS小程序音频开始播放');
- this.currentSubtitle = this.aiText;
-
- uni.showToast({
- title: '正在播放AI回复',
- icon: 'none',
- duration: 1500
- });
- });
-
- // 设置播放结束事件
- audioContext.onEnded(() => {
- console.log('iOS小程序音频播放结束');
- this.handleIOSAudioComplete(audioContext);
- });
-
- // 设置播放停止事件
- audioContext.onStop(() => {
- console.log('iOS小程序音频播放停止');
- this.handleIOSAudioComplete(audioContext);
- });
-
- // 重点:增强的iOS错误处理
- audioContext.onError((err) => {
- console.error('iOS小程序音频播放错误:', err);
- this.handleIOSMiniProgramError(audioContext, err);
- });
-
- // 先尝试预下载音频文件(iOS小程序推荐做法)
- this.preloadIOSMiniProgramAudio(this.aiVoiceUrl)
- .then((localPath) => {
- console.log('iOS小程序音频预下载成功:', localPath);
- audioContext.src = localPath;
-
- /* // 设置播放超时
- const playTimeout = setTimeout(() => {
- if (this.isPlayingAiVoice) {
- console.log('iOS小程序音频播放超时,使用文本回退');
- clearTimeout(playTimeout);
- this.handleIOSPlaybackTimeout(audioContext);
- }
- }, 5000);
- */
- // 尝试播放
- audioContext.play();
- })
- .catch((error) => {
- console.error('iOS小程序音频预下载失败:', error);
- // 预下载失败,尝试直接播放
- this.fallbackIOSMiniProgramPlay(audioContext);
- });
-
- } catch (e) {
- console.error('iOS小程序音频初始化失败:', e);
- this.useIOSTextFallback();
- }
- },
- // 新增方法:iOS小程序音频预下载
- preloadIOSMiniProgramAudio(audioUrl) {
- return new Promise((resolve, reject) => {
- console.log('开始预下载iOS小程序音频:', audioUrl);
-
- uni.downloadFile({
- url: audioUrl,
- timeout: 15000, // 15秒超时
- success: (res) => {
- if (res.statusCode === 200) {
- console.log('iOS小程序音频下载成功:', res.tempFilePath);
- resolve(res.tempFilePath);
- } else {
- console.error('iOS小程序音频下载失败,状态码:', res.statusCode);
- reject(new Error(`下载失败,状态码: ${res.statusCode}`));
- }
- },
- fail: (err) => {
- console.error('iOS小程序音频下载请求失败:', err);
- reject(err);
- }
- });
- });
- },
- // 新增方法:iOS小程序错误处理
- handleIOSMiniProgramError(audioContext, error) {
- console.error('处理iOS小程序音频错误:', error);
-
- // 销毁音频播放器
- if (audioContext) {
- try {
- audioContext.destroy();
- } catch (e) {
- console.error('销毁音频播放器失败:', e);
- }
- }
-
- // 根据错误类型显示不同的提示信息
- let errorMessage = '音频播放异常,显示文字';
-
- if (error.errMsg && error.errMsg.includes('-11850')) {
- console.log('iOS小程序检测到系统音频错误(-11850)');
- errorMessage = '系统音频服务暂停,显示文字';
- } else if (error.errCode === 10002) {
- console.log('iOS小程序检测到errCode:10002,网络或资源问题');
- errorMessage = '音频加载中断,显示文字';
- } else if (error.errCode === 10001) {
- console.log('iOS小程序检测到errCode:10001,系统错误');
- errorMessage = '系统音频错误,显示文字';
- } else if (error.errCode === 10003) {
- console.log('iOS小程序检测到errCode:10003,文件错误');
- errorMessage = '音频文件错误,显示文字';
- } else if (error.errCode === 10004) {
- console.log('iOS小程序检测到errCode:10004,格式不支持');
- errorMessage = '音频格式不支持,显示文字';
- }
-
- // 显示用户友好的错误提示
- uni.showToast({
- title: errorMessage,
- icon: 'none',
- duration: 2000
- });
-
- // 使用文本回退
- this.useIOSTextFallback();
- },
- // 新增方法:iOS小程序播放超时处理
- handleIOSPlaybackTimeout(audioContext) {
- console.log('iOS小程序音频播放超时处理');
-
- // 销毁音频播放器
- if (audioContext) {
- try {
- audioContext.destroy();
- } catch (e) {
- console.error('销毁超时音频播放器失败:', e);
- }
- }
-
- // 显示超时提示
- uni.showToast({
- title: '音频加载超时,显示文字',
- icon: 'none',
- duration: 2000
- });
-
- // 使用文本回退
- this.useIOSTextFallback();
- },
- // 新增方法:iOS小程序备选播放方法
- fallbackIOSMiniProgramPlay(audioContext) {
- console.log('iOS小程序使用备选播放方法');
-
- try {
- // 直接设置原始URL
- audioContext.src = this.aiVoiceUrl;
-
- // 设置较短的超时时间
- const fallbackTimeout = setTimeout(() => {
- if (this.isPlayingAiVoice) {
- console.log('iOS小程序备选方法也超时');
- clearTimeout(fallbackTimeout);
- this.handleIOSPlaybackTimeout(audioContext);
- }
- }, 3000);
-
- // 尝试播放
- audioContext.play();
-
- } catch (e) {
- console.error('iOS小程序备选播放方法失败:', e);
- this.handleIOSPlaybackTimeout(audioContext);
- }
- },
- // 新增方法:统一的iOS音频完成处理
- handleIOSAudioComplete(audioContext) {
- console.log('iOS音频播放完成');
-
- // 标记播放结束
- this.isPlayingAiVoice = false;
-
- // 延迟清空字幕,让用户有时间阅读
- setTimeout(() => {
- this.currentSubtitle = '';
- }, 2000);
-
- // 销毁音频播放器
- if (audioContext) {
- try {
- audioContext.destroy();
- } catch (e) {
- console.error('销毁iOS音频播放器失败:', e);
- }
- }
-
- // 显示继续提问选项
- this.showContinueQuestionOptions();
-
- // 检查是否需要自动跳转
- this.checkPendingNavigation();
- },
- // 移除原来的 playMiniProgramAudioForIOS 方法,因为已经被新的 playIOSMiniProgramAudio 替代
- // playMiniProgramAudioForIOS() 方法可以删除或注释掉
- // 保留原有的 useIOSTextFallback 方法,但确保它能正确处理所有iOS场景
- useIOSTextFallback() {
- console.log('iOS使用文本回退方案');
-
- // 确保播放状态正确
- this.isPlayingAiVoice = false;
-
- // 显示友好提示(如果还没有显示过)
- if (!this.hasShownTextFallbackToast) {
- this.hasShownTextFallbackToast = true;
- uni.showToast({
- title: '为您显示文字回复',
- icon: 'none',
- duration: 2000
- });
- }
-
- // 显示完整文本
- this.currentSubtitle = this.aiText || '抱歉,AI回复内容加载失败';
-
- // 根据文本长度计算合适的阅读时间
- const textLength = this.aiText ? this.aiText.length : 20;
- const readingTime = Math.max(5000, Math.min(textLength * 100, 15000)); // 最少5秒,最多15秒
-
- console.log(`文本长度: ${textLength}, 预计阅读时间: ${readingTime}ms`);
-
- setTimeout(() => {
- this.handleIOSAudioComplete(null);
- }, readingTime);
- },
- // 添加新方法:iOS音频播放完成处理
- handleIOSAudioPlaybackComplete() {
- // 标记播放结束
- this.isPlayingAiVoice = false;
-
- // 延迟清空字幕,让用户有时间阅读
- setTimeout(() => {
- this.currentSubtitle = '';
- }, 2000);
-
- // 销毁音频播放器
- if (this.aiAudioPlayer) {
- try {
- this.aiAudioPlayer.destroy();
- } catch (e) {
- console.error('销毁iOS音频播放器失败:', e);
- }
- this.aiAudioPlayer = null;
- }
-
- // 显示继续提问选项
- this.showContinueQuestionOptions();
-
- // 检查是否需要自动跳转
- this.checkPendingNavigation();
- },
- // 添加新方法:iOS音频错误处理
- handleIOSAudioError(error) {
- console.error('iOS音频播放错误:', error);
-
- // 根据错误码进行不同处理
- switch (error.errCode) {
- case 10001:
- console.log('iOS音频系统错误,尝试重新播放');
- this.retryIOSAudioPlay();
- break;
- case 10002:
- console.log('iOS音频网络错误,使用备选方案');
- this.handleIOS10002Error();
- break;
- case 10003:
- console.log('iOS音频文件错误,使用文本回退');
- this.useIOSTextFallback();
- break;
- case 10004:
- console.log('iOS音频格式不支持,使用文本回退');
- this.useIOSTextFallback();
- break;
- default:
- console.log('iOS音频未知错误,使用文本回退');
- this.useIOSTextFallback();
- break;
- }
- },
- // 添加新方法:重试iOS音频播放
- retryIOSAudioPlay() {
- console.log('重试iOS音频播放');
-
- // 销毁当前播放器
- if (this.aiAudioPlayer) {
- try {
- this.aiAudioPlayer.destroy();
- } catch (e) {
- console.error('销毁播放器失败:', e);
- }
- this.aiAudioPlayer = null;
- }
-
- // 延迟后重试
- setTimeout(() => {
- this.fallbackIOSAudioPlay();
- }, 1000);
- },
- // 添加新方法:iOS备选音频播放
- fallbackIOSAudioPlay() {
- console.log('iOS备选音频播放方案');
-
- try {
- // 创建新的音频播放器
- this.aiAudioPlayer = uni.createInnerAudioContext();
-
- // 使用更保守的设置
- this.aiAudioPlayer.autoplay = true;
- this.aiAudioPlayer.obeyMuteSwitch = true; // 遵循静音开关
- this.aiAudioPlayer.volume = 0.8;
-
- // 直接使用原URL
- this.aiAudioPlayer.src = this.aiVoiceUrl;
-
- // 设置简化的事件监听
- this.aiAudioPlayer.onPlay(() => {
- console.log('iOS备选方案:音频开始播放');
- this.currentSubtitle = this.aiText;
- });
-
- this.aiAudioPlayer.onEnded(() => {
- console.log('iOS备选方案:音频播放结束');
- this.handleIOSAudioPlaybackComplete();
- });
-
- this.aiAudioPlayer.onError((err) => {
- console.error('iOS备选方案:音频播放错误:', err);
- this.useIOSTextFallback();
- });
-
- // 设置超时,如果5秒内没有开始播放,使用文本回退
- setTimeout(() => {
- if (this.isPlayingAiVoice && this.aiAudioPlayer) {
- console.log('iOS音频播放超时,使用文本回退');
- this.useIOSTextFallback();
- }
- }, 5000);
-
- } catch (e) {
- console.error('iOS备选音频播放失败:', e);
- this.useIOSTextFallback();
- }
- },
- // 修改 playMiniProgramAudio 方法,添加iOS特殊处理
- playMiniProgramAudio() {
- console.log('使用小程序原生音频API播放:', this.aiVoiceUrl);
-
- // 标记正在播放AI语音
- this.isPlayingAiVoice = true;
-
- // 确保在播放期间不显示继续提问按钮
- this.showContinueQuestionButton = false;
- this.showEndInterviewButton = false;
-
- // 检查音频URL是否有效
- if (!this.aiVoiceUrl || this.aiVoiceUrl.trim() === '') {
- console.error('无效的音频URL');
- this.handleAudioPlaybackFailure();
- return;
- }
-
- // 检查平台
- const systemInfo = uni.getSystemInfoSync();
- const isIOS = systemInfo.platform === 'ios';
-
- // iOS小程序特殊处理
- if (isIOS) {
- this.playMiniProgramAudioForIOS();
- return;
- }
-
- // 非iOS平台的原有逻辑
- try {
- // 使用wx.createInnerAudioContext API (微信小程序)
- const audioContext = wx.createInnerAudioContext();
-
- // 设置音频属性
- audioContext.autoplay = false;
- audioContext.obeyMuteSwitch = false; // 忽略静音开关
-
- // 监听播放开始事件
- audioContext.onPlay(() => {
- console.log('AI语音开始播放');
-
- // 显示正在播放提示
- uni.showToast({
- title: '正在播放AI回复',
- icon: 'none',
- duration: 2000
- });
- });
-
- // 监听播放结束事件
- audioContext.onEnded(() => {
- console.log('AI语音播放结束');
-
- // 标记播放结束
- this.isPlayingAiVoice = false;
-
- // 清空字幕
- this.currentSubtitle = '';
-
- // 销毁音频播放器
- audioContext.destroy();
-
- // 播放结束后显示继续提问选项,而不是直接跳转
- this.showContinueQuestionOptions();
- });
-
- // 监听播放错误事件
- audioContext.onError((err) => {
- console.error('AI语音播放错误:', err);
-
- // 标记播放结束
- this.isPlayingAiVoice = false;
-
- // 清空字幕
- this.currentSubtitle = '';
-
- // 销毁音频播放器
- audioContext.destroy();
-
- // 播放错误时也显示继续提问选项
- this.showContinueQuestionOptions();
- });
-
- // 设置音频源
- audioContext.src = this.aiVoiceUrl;
-
- // 添加超时处理,如果5秒内没有开始播放,则认为出错
- const playTimeout = setTimeout(() => {
- if (this.isPlayingAiVoice) {
- console.warn('小程序音频播放超时,尝试备选方法');
- this.tryMiniProgramFallbackAudioPlay();
- }
- }, 5000);
-
- // 延迟一小段时间再播放,确保src已经设置完成
- setTimeout(() => {
- audioContext.play();
- // 播放开始后清除超时
- clearTimeout(playTimeout);
- }, 300);
- } catch (e) {
- console.error('小程序播放AI语音时发生错误:', e);
-
- // 标记播放结束
- this.isPlayingAiVoice = false;
-
- // 显示错误提示
- uni.showToast({
- title: '音频播放失败,请查看文字回复',
- icon: 'none',
- duration: 2000
- });
-
- // 使用文本显示方式作为备选方案
- this.handleAudioPlaybackFailure();
- }
- },
- // 添加新方法:iOS小程序音频播放
- playMiniProgramAudioForIOS() {
- console.log('iOS小程序环境:开始播放AI语音');
-
- // 重置错误标记
- this.hasShownTextFallbackToast = false;
-
- try {
- // 创建音频上下文
- const audioContext = wx.createInnerAudioContext();
-
- // iOS小程序特殊配置
- audioContext.autoplay = false;
- audioContext.obeyMuteSwitch = true; // iOS上遵循静音开关
- audioContext.volume = 1.0;
-
- // 设置错误处理
- audioContext.onError((err) => {
- console.error('iOS小程序音频播放错误:', err);
-
- // 检查具体错误类型
- if (err.errMsg && err.errMsg.includes('-11850')) {
- console.log('iOS小程序检测到系统音频错误(-11850)');
- uni.showToast({
- title: '系统音频暂停,显示文字',
- icon: 'none',
- duration: 2000
- });
- } else if (err.errCode === 10002) {
- console.log('iOS小程序检测到errCode:10002,网络或资源问题');
- uni.showToast({
- title: '音频加载中断,显示文字',
- icon: 'none',
- duration: 2000
- });
- } else {
- console.log('iOS小程序其他音频错误:', err.errCode);
- uni.showToast({
- title: '音频播放异常,显示文字',
- icon: 'none',
- duration: 2000
- });
- }
-
- this.useIOSMiniProgramTextFallback(audioContext);
- });
-
- // 先尝试直接播放,如果失败再下载
- audioContext.src = this.aiVoiceUrl;
-
- // 设置成功事件监听
- audioContext.onPlay(() => {
- console.log('iOS小程序音频开始播放');
- this.currentSubtitle = this.aiText;
-
- uni.showToast({
- title: '正在播放AI回复',
- icon: 'none',
- duration: 1500
- });
- });
-
- audioContext.onEnded(() => {
- console.log('iOS小程序音频播放结束');
- this.handleIOSMiniProgramAudioComplete(audioContext);
- });
-
- // 设置较短的播放超时时间
- const playTimeout = setTimeout(() => {
- if (this.isPlayingAiVoice) {
- console.log('iOS小程序音频播放超时,切换到文本显示');
- clearTimeout(playTimeout);
- this.useIOSMiniProgramTextFallback(audioContext);
- }
- }, 3000); // 缩短到3秒
-
- // 尝试播放
- audioContext.play();
-
- } catch (e) {
- console.error('iOS小程序音频播放初始化失败:', e);
- this.handleAudioPlaybackFailure();
- }
- },
- // 添加新方法:iOS小程序音频播放完成
- handleIOSMiniProgramAudioComplete(audioContext) {
- this.isPlayingAiVoice = false;
-
- setTimeout(() => {
- this.currentSubtitle = '';
- }, 2000);
-
- if (audioContext) {
- try {
- audioContext.destroy();
- } catch (e) {
- console.error('销毁iOS小程序音频播放器失败:', e);
- }
- }
-
- this.showContinueQuestionOptions();
- this.checkPendingNavigation();
- },
- // 添加新方法:iOS小程序音频错误处理
- handleIOSMiniProgramAudioError(audioContext, error) {
- console.error('iOS小程序音频错误:', error);
-
- // 根据错误码处理
- if (error.errCode === 10002) {
- this.useIOSMiniProgramTextFallback(audioContext);
- } else {
- // 其他错误也使用文本回退
- this.useIOSMiniProgramTextFallback(audioContext);
- }
- },
- // 添加新方法:iOS小程序文本回退
- useIOSMiniProgramTextFallback(audioContext) {
- console.log('iOS小程序使用文本回退方案');
-
- // 销毁音频播放器
- if (audioContext) {
- try {
- audioContext.destroy();
- } catch (e) {
- console.error('销毁音频播放器失败:', e);
- }
- }
-
- // 确保播放状态正确
- this.isPlayingAiVoice = false;
-
- // 显示完整文本
- this.currentSubtitle = this.aiText || '抱歉,AI回复内容加载失败';
-
- // 根据文本长度计算阅读时间
- const textLength = this.aiText ? this.aiText.length : 20;
- const readingTime = Math.max(6000, Math.min(textLength * 120, 18000)); // 最少6秒,最多18秒
-
- setTimeout(() => {
- this.handleIOSMiniProgramAudioComplete(null);
- }, readingTime);
- },
- // 添加新方法:处理音频播放错误
- handleAudioPlaybackError(error) {
- console.error('音频播放错误:', error);
-
- // 尝试使用备选方法
- if (!this.hasTriedFallbackMethod) {
- this.hasTriedFallbackMethod = true;
- this.tryFallbackAudioPlay();
- return;
- }
-
- // 如果备选方法也失败,回退到文本显示
- this.handleAudioPlaybackFailure();
- },
- // 添加新方法:尝试备选音频播放方法
- tryFallbackAudioPlay() {
- console.log('使用备选方法播放音频:', this.aiVoiceUrl);
-
- // 如果当前播放器存在,先销毁
- if (this.aiAudioPlayer) {
- try {
- this.aiAudioPlayer.destroy();
- } catch (e) {
- console.error('销毁音频播放器失败:', e);
- }
- this.aiAudioPlayer = null;
- }
-
- // 使用uni.downloadFile先下载音频文件
- uni.downloadFile({
- url: this.aiVoiceUrl,
- success: (res) => {
- if (res.statusCode === 200) {
- console.log('音频文件下载成功:', res.tempFilePath);
-
- // 使用新的音频上下文播放本地文件
- const newAudioPlayer = uni.createInnerAudioContext();
- this.aiAudioPlayer = newAudioPlayer;
-
- newAudioPlayer.autoplay = true;
- newAudioPlayer.src = res.tempFilePath;
-
- // 设置事件监听
- newAudioPlayer.onPlay(() => {
- console.log('备选方法:音频开始播放');
- });
-
- newAudioPlayer.onEnded(() => {
- console.log('备选方法:音频播放结束');
- this.isPlayingAiVoice = false;
- this.currentSubtitle = '';
- newAudioPlayer.destroy();
- this.aiAudioPlayer = null;
- this.showContinueQuestionOptions();
- this.checkPendingNavigation();
- });
-
- newAudioPlayer.onError((err) => {
- console.error('备选方法:音频播放错误:', err);
- this.isPlayingAiVoice = false;
- this.currentSubtitle = '';
- newAudioPlayer.destroy();
- this.aiAudioPlayer = null;
-
- // 显示错误提示
- uni.showToast({
- title: '无法播放音频,请查看文字回复',
- icon: 'none',
- duration: 2000
- });
-
- this.showContinueQuestionOptions();
- this.checkPendingNavigation();
- });
- } else {
- console.error('音频文件下载失败:', res);
- this.handleAudioPlaybackFailure();
- }
- },
- fail: (err) => {
- console.error('音频文件下载请求失败:', err);
- this.handleAudioPlaybackFailure();
- }
- });
- },
- // 添加新方法:处理音频播放失败的情况
- handleAudioPlaybackFailure() {
- // 标记播放结束
- this.isPlayingAiVoice = false;
-
- // 显示错误提示
- uni.showToast({
- title: '无法播放音频,将直接显示文字回复',
- icon: 'none',
- duration: 2000
- });
-
- // 确保字幕显示足够长的时间(10秒)让用户阅读
- this.currentSubtitle = this.aiText;
-
- // 设置定时器,10秒后清除字幕并显示继续提问选项
- setTimeout(() => {
- this.currentSubtitle = '';
- this.showContinueQuestionOptions();
- this.checkPendingNavigation();
- }, 10000);
- },
- // 添加新方法:从视频中提取音频
- async extractAudioFromVideo(videoBlob) {
- console.log('开始从视频中提取音频');
-
- return new Promise((resolve, reject) => {
- try {
- // 创建一个视频元素来加载视频
- const videoElement = document.createElement('video');
- videoElement.muted = false;
- videoElement.autoplay = false;
-
- // 创建音频上下文
- const audioContext = new (window.AudioContext || window.webkitAudioContext)();
- let audioDestination = null;
- let mediaRecorder = null;
- const audioChunks = [];
-
- // 设置视频源
- videoElement.src = URL.createObjectURL(videoBlob);
-
- videoElement.onloadedmetadata = () => {
- console.log('视频元数据已加载,视频时长:', videoElement.duration);
-
- // 创建媒体源和目标节点
- const source = audioContext.createMediaElementSource(videoElement);
- audioDestination = audioContext.createMediaStreamDestination();
- source.connect(audioDestination);
-
- // 创建MediaRecorder来录制音频
- mediaRecorder = new MediaRecorder(audioDestination.stream);
-
- mediaRecorder.ondataavailable = (event) => {
- if (event.data.size > 0) {
- audioChunks.push(event.data);
- }
- };
-
- mediaRecorder.onstop = () => {
- const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
- console.log('音频提取完成,大小:', audioBlob.size);
- resolve(audioBlob);
- };
-
- // 开始播放视频并录制音频
- videoElement.onplay = () => {
- mediaRecorder.start(100);
- };
-
- videoElement.onended = () => {
- mediaRecorder.stop();
- audioContext.close();
- };
-
- // 开始播放
- videoElement.play();
- };
-
- videoElement.onerror = (err) => {
- console.error('视频加载失败:', err);
- reject(new Error('视频加载失败'));
- };
- } catch (err) {
- console.error('提取音频失败:', err);
- reject(err);
- }
- });
- },
- // 添加新方法:上传音频文件
- async uploadAudioFile(audioBlob, videoUrl) {
- console.log('准备上传音频文件');
-
- // 创建FormData
- const formData = new FormData();
-
- // 将Blob转换为File对象
- const fileName = `audio_${Date.now()}.wav`;
- const audioFile = new File([audioBlob], fileName, { type: 'audio/wav' });
-
- // 添加文件和其他参数
- formData.append('audio_file', audioFile);
- formData.append('video_url', videoUrl);
- formData.append('tenant_id', uni.getStorageSync('tenant_id') || '1');
- formData.append('openid', uni.getStorageSync('userInfo') ? JSON.parse(uni.getStorageSync('userInfo')).openid : '');
- formData.append('application_id', uni.getStorageSync('appId') || '');
-
- return new Promise((resolve, reject) => {
- // 创建XMLHttpRequest
- const xhr = new XMLHttpRequest();
- xhr.open('POST', `${apiBaseUrl}/api/voice_ai_interaction`, true);
- xhr.timeout = 60000; // 60秒超时
-
- xhr.onload = () => {
- if (xhr.status === 200) {
- try {
- const response = JSON.parse(xhr.responseText);
- resolve(response);
- } catch (e) {
- reject(new Error('解析响应失败'));
- }
- } else {
- reject(new Error('HTTP状态: ' + xhr.status));
- }
- };
-
- xhr.onerror = () => {
- reject(new Error('网络错误'));
- };
-
- xhr.ontimeout = () => {
- reject(new Error('请求超时'));
- };
-
- xhr.send(formData);
- });
- },
- // 添加一个新方法:使用小程序原生音频API
- playMiniProgramAudio() {
- console.log('使用小程序原生音频API播放:', this.aiVoiceUrl);
-
- // 标记正在播放AI语音
- this.isPlayingAiVoice = true;
-
- // 确保在播放期间不显示继续提问按钮
- this.showContinueQuestionButton = false;
- this.showEndInterviewButton = false;
-
- // 检查音频URL是否有效
- if (!this.aiVoiceUrl || this.aiVoiceUrl.trim() === '') {
- console.error('无效的音频URL');
- // 显示错误提示
- uni.showToast({
- title: '音频加载失败',
- icon: 'none',
- duration: 2000
- });
-
- // 标记播放结束
- this.isPlayingAiVoice = false;
-
- // 显示继续提问选项
- this.showContinueQuestionOptions();
- return;
- }
-
- try {
- // 使用wx.createInnerAudioContext API (微信小程序)
- const audioContext = wx.createInnerAudioContext();
-
- // 设置音频属性
- audioContext.autoplay = false;
- audioContext.obeyMuteSwitch = false; // 忽略静音开关
-
- // 监听播放开始事件
- audioContext.onPlay(() => {
- console.log('AI语音开始播放');
-
- // 显示正在播放提示
- uni.showToast({
- title: '正在播放AI回复',
- icon: 'none',
- duration: 2000
- });
- });
-
- // 监听播放结束事件
- audioContext.onEnded(() => {
- console.log('AI语音播放结束');
-
- // 标记播放结束
- this.isPlayingAiVoice = false;
-
- // 清空字幕
- this.currentSubtitle = '';
-
- // 销毁音频播放器
- audioContext.destroy();
-
- // 播放结束后显示继续提问选项,而不是直接跳转
- this.showContinueQuestionOptions();
- });
-
- // 监听播放错误事件
- audioContext.onError((err) => {
- console.error('AI语音播放错误:', err);
-
- // 标记播放结束
- this.isPlayingAiVoice = false;
-
- // 清空字幕
- this.currentSubtitle = '';
-
- // 销毁音频播放器
- audioContext.destroy();
-
- // 播放错误时也显示继续提问选项
- this.showContinueQuestionOptions();
- });
-
- // 设置音频源
- audioContext.src = this.aiVoiceUrl;
-
- // 添加超时处理,如果5秒内没有开始播放,则认为出错
- const playTimeout = setTimeout(() => {
- if (this.isPlayingAiVoice) {
- console.warn('小程序音频播放超时,尝试备选方法');
- this.tryMiniProgramFallbackAudioPlay();
- }
- }, 5000);
-
- // 延迟一小段时间再播放,确保src已经设置完成
- setTimeout(() => {
- audioContext.play();
- // 播放开始后清除超时
- clearTimeout(playTimeout);
- }, 300);
- } catch (e) {
- console.error('小程序播放AI语音时发生错误:', e);
-
- // 标记播放结束
- this.isPlayingAiVoice = false;
-
- // 显示错误提示
- uni.showToast({
- title: '音频播放失败,请查看文字回复',
- icon: 'none',
- duration: 2000
- });
-
- // 使用文本显示方式作为备选方案
- this.handleAudioPlaybackFailure();
- }
- },
- // 添加新方法:小程序环境的备选音频播放方法
- tryMiniProgramFallbackAudioPlay() {
- console.log('使用小程序备选方法播放音频:', this.aiVoiceUrl);
-
- // 先下载音频文件到本地
- uni.downloadFile({
- url: this.aiVoiceUrl,
- success: (res) => {
- if (res.statusCode === 200) {
- console.log('小程序音频文件下载成功:', res.tempFilePath);
-
- // 使用新的音频上下文播放本地文件
- const newAudioContext = wx.createInnerAudioContext();
-
- newAudioContext.autoplay = true;
- newAudioContext.src = res.tempFilePath;
-
- // 设置事件监听
- newAudioContext.onPlay(() => {
- console.log('小程序备选方法:音频开始播放');
- });
-
- newAudioContext.onEnded(() => {
- console.log('小程序备选方法:音频播放结束');
- this.isPlayingAiVoice = false;
- this.currentSubtitle = '';
- newAudioContext.destroy();
- this.showContinueQuestionOptions();
- this.checkPendingNavigation();
- });
-
- newAudioContext.onError((err) => {
- console.error('小程序备选方法:音频播放错误:', err);
- this.isPlayingAiVoice = false;
- this.currentSubtitle = '';
- newAudioContext.destroy();
-
- // 尝试使用系统播放器作为最后的备选方案
- this.trySystemAudioPlayer();
- });
- } else {
- console.error('小程序音频文件下载失败:', res);
- this.handleAudioPlaybackFailure();
- }
- },
- fail: (err) => {
- console.error('小程序音频文件下载请求失败:', err);
- this.handleAudioPlaybackFailure();
- }
- });
- },
- // 添加新方法:尝试使用系统播放器
- trySystemAudioPlayer() {
- console.log('尝试使用系统播放器播放音频');
-
- // 检查平台
- const systemInfo = uni.getSystemInfoSync();
-
- if (systemInfo.platform === 'android' || systemInfo.platform === 'ios') {
- // 在移动端尝试使用系统播放器
- uni.showToast({
- title: '正在使用系统播放器',
- icon: 'none',
- duration: 2000
- });
-
- // 使用uni.playVoice API (如果可用)
- if (typeof uni.playVoice === 'function') {
- uni.playVoice({
- filePath: this.aiVoiceUrl,
- success: () => {
- console.log('系统播放器播放成功');
- setTimeout(() => {
- this.isPlayingAiVoice = false;
- this.currentSubtitle = '';
- this.showContinueQuestionOptions();
- }, 5000); // 假设音频长度约为5秒
- },
- fail: (err) => {
- console.error('系统播放器播放失败:', err);
- this.handleAudioPlaybackFailure();
- }
- });
- } else {
- // 如果uni.playVoice不可用,尝试使用uni.openDocument
- uni.openDocument({
- filePath: this.aiVoiceUrl,
- fileType: 'audio',
- success: () => {
- console.log('使用系统应用打开音频文件');
- // 由于控制权交给了系统,我们需要手动处理后续流程
- setTimeout(() => {
- this.isPlayingAiVoice = false;
- this.currentSubtitle = '';
- this.showContinueQuestionOptions();
- }, 8000); // 给用户足够的时间听完音频
- },
- fail: (err) => {
- console.error('无法使用系统应用打开音频:', err);
- this.handleAudioPlaybackFailure();
- }
- });
- }
- } else {
- // 在其他平台上直接使用文本显示
- this.handleAudioPlaybackFailure();
- }
- },
- // 修改 showContinueQuestionOptions 方法,确保状态正确设置
- showContinueQuestionOptions() {
- // 如果正在播放AI语音,不执行此方法
- if (this.isPlayingAiVoice) {
- console.log('AI语音正在播放,暂不显示继续提问选项');
- return;
- }
-
- // 增加提问轮次计数
- this.questionRound++;
-
- // 清空字幕
- this.currentSubtitle = '';
-
- // 直接跳转到下一页,不再显示继续提问按钮
- console.log('准备跳转到下一页面');
-
- // 延迟3秒后跳转,给用户一些时间查看状态
- setTimeout(() => {
- this.navigateToNextPage();
- }, 3000);
-
- // 确保所有录制状态被重置
- this.isRecording = false;
- if (this.recordingTimer) {
- clearInterval(this.recordingTimer);
- this.recordingTimer = null;
- }
-
- // 重置录制相关数据
- this.recordedChunks = [];
- this.recordingTimerCount = 0;
- this.remainingTime = this.maxRecordingTime;
- },
- // 修复 handleContinueQuestionClick 方法,确保状态正确重置
- handleContinueQuestionClick() {
- // 如果AI语音仍在播放,不允许继续提问
- if (this.isPlayingAiVoice) {
- uni.showToast({
- title: '请等待面试官回复完成',
- icon: 'none',
- duration: 2000
- });
- return;
- }
-
- // 隐藏继续提问和结束面试按钮
- this.showContinueQuestionButton = false;
- this.showEndInterviewButton = false;
-
- // 重置录制相关状态
- this.isRecording = false;
- this.recordingTimerCount = 0;
- this.remainingTime = this.maxRecordingTime;
- this.recordingTimeDisplay = '00:00 / ' + this.formatTime(this.maxRecordingTime);
-
- // 清空已录制的数据
- this.recordedChunks = [];
-
- // 如果有正在进行的录制,先停止
- if (this.mediaRecorder && this.mediaRecorder.state === 'recording') {
- this.mediaRecorder.stop();
- }
-
- if (this.recorder) {
- try {
- this.cameraContext.stopRecord();
- } catch (e) {
- console.error('停止录制失败:', e);
- }
- this.recorder = null;
- }
-
- // 延迟一小段时间再开始新的录制,确保之前的录制已完全停止
- setTimeout(() => {
- // 开始新一轮录制
- this.startRecordingAnswer();
- }, 500);
- },
- // 添加新方法:处理结束面试按钮点击
- handleEndInterviewClick() {
- // 隐藏继续提问和结束面试按钮
- this.showContinueQuestionButton = false;
- this.showEndInterviewButton = false;
-
- // 显示结束提示
- /* uni.showToast({
- title: '面试已结束',
- icon: 'success',
- duration: 1500
- }); */
-
- // 执行现有的跳转逻辑
- this.navigateToNextPage();
- },
- // 添加新方法:处理录制错误
- handleRecordingError(error) {
- console.error('录制错误:', error);
-
- // 显示错误提示
- uni.showToast({
- title: '录制失败,请重试',
- icon: 'none',
- duration: 2000
- });
-
- // 重置录制状态
- this.isRecording = false;
- this.showStopRecordingButton = false;
-
- // 显示重试按钮
- this.showStartRecordingButton = true;
- },
- // 添加新方法:处理上传错误
- handleUploadError(error) {
- console.error('上传错误:', error);
-
- // 显示错误提示
- uni.showToast({
- title: '上传失败,请重试',
- icon: 'none',
- duration: 2000
- });
-
- // 显示重试按钮
- this.showRetryButton = true;
-
- // 隐藏上传状态
- this.showUploadStatus = false;
- this.isUploading = false;
- },
- // 添加新方法:检查是否有待处理的自动跳转
- checkPendingNavigation() {
- // 确保所有处理都已完成
- if (this.pendingAutoNavigation &&
- !this.isPlayingAiVoice &&
- !this.isUploading &&
- !this.currentSubtitle) { // 确保字幕也已经清空
-
- console.log('所有处理已完成,准备跳转');
-
- // 重置标志
- this.pendingAutoNavigation = false;
-
- // 延迟跳转,给用户一点时间看到最终状态
- setTimeout(() => {
- this.navigateToNextPage();
- }, 1000);
- }
- },
- // 添加新方法:显示文本回复
- displayTextResponse() {
- // 标记为正在"播放"
- this.isPlayingAiVoice = true;
-
- // 显示AI回复文本
- this.currentSubtitle = '';
-
- // 计算每个字的显示时间(假设每个字需要200毫秒)
- const charDisplayTime = 200;
- let currentIndex = 0;
-
- // 使用定时器逐字显示文本
- const textInterval = setInterval(() => {
- if (currentIndex <= this.aiText.length) {
- this.currentSubtitle = this.aiText.substring(0, currentIndex);
- currentIndex++;
- } else {
- // 文本显示完成
- clearInterval(textInterval);
-
- // 等待用户阅读完整文本
- setTimeout(() => {
- // 标记播放结束
- this.isPlayingAiVoice = false;
-
- // 清空字幕
- this.currentSubtitle = '';
-
- // 显示继续提问选项
- this.showContinueQuestionOptions();
-
- // 检查是否需要自动跳转
- this.checkPendingNavigation();
- }, 3000); // 给用户3秒时间阅读完整文本
- }
- }, charDisplayTime);
- },
- // 添加新方法:检查不支持的音频格式
- checkUnsupportedAudioFormat(url) {
- if (!url) return false;
-
- // 获取URL的文件扩展名
- const extension = url.split('.').pop().toLowerCase();
-
- // 检查平台
- const systemInfo = uni.getSystemInfoSync();
- const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
-
- if (isMiniProgram) {
- // 微信小程序支持的音频格式有限,主要是mp3和wav
- // 检查是否是不支持的格式
- const unsupportedFormats = ['ogg', 'flac', 'aac', 'm4a', 'opus'];
- return unsupportedFormats.includes(extension);
- }
-
- return false;
- },
- // 修改文本回退方法
- useIOSTextFallback() {
- console.log('切换到文本显示模式');
-
- this.isPlayingAiVoice = false;
-
- if (!this.hasShownTextFallbackToast) {
- this.hasShownTextFallbackToast = true;
- uni.showToast({
- title: '已切换为文字显示',
- icon: 'none',
- duration: 2000
- });
- }
-
- // 显示AI回复文本
- this.currentSubtitle = this.aiText || '抱歉,无法获取AI回复内容';
-
- // 根据文本长度计算阅读时间
- const textLength = this.aiText ? this.aiText.length : 20;
- const readingTime = Math.max(8000, Math.min(textLength * 150, 20000)); // 最少8秒,最多20秒
-
- console.log(`文本长度: ${textLength}字,预计阅读时间: ${readingTime/1000}秒`);
-
- // 等待用户阅读完成后再跳转
- setTimeout(() => {
- this.navigateToNextPage();
- }, readingTime);
- }
- }
- }
- </script>
- <style scoped>
- .identity-verify-container {
- padding: 0;
- max-width: 100%;
- margin: 0 auto;
- height: 100vh;
- display: flex;
- flex-direction: column;
- background-color: #f5f5f5;
- }
- .digital-human-container {
- position: relative;
- width: 100%;
- height: 100vh;
- overflow: hidden;
- background-color: #f0f0f0;
- }
- .digital-human-video {
- width: 100%;
- height: 100%;
- display: flex;
- justify-content: center;
- align-items: center;
- }
- /* 用户摄像头容器样式 */
- .user-camera-container {
- position: absolute;
- top: 50px;
- right: 5px;
- width: 110px; /* 稍微增加宽度 */
- height: 160px; /* 稍微增加高度 */
- border-radius: 4px; /* 减小圆角 */
- overflow: hidden;
- box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
- z-index: 20;
-
- }
- /* 用户摄像头视频样式 */
- .user-camera-video {
- width: 100%;
- height: 100%;
- object-fit: cover;
- background-color: #333;
- }
- .video-player {
- width: 100%;
- height: 100%;
- object-fit: cover;
- outline: none; /* 移除视频获得焦点时的轮廓 */
- -webkit-tap-highlight-color: transparent; /* 移除移动设备上的点击高亮 */
- }
- /* 隐藏视频控制条 */
- video::-webkit-media-controls {
- display: none !important;
- }
- video::-webkit-media-controls-enclosure {
- display: none !important;
- }
- video::-webkit-media-controls-panel {
- display: none !important;
- }
- video::-webkit-media-controls-play-button {
- display: none !important;
- }
- video::-webkit-media-controls-timeline {
- display: none !important;
- }
- video::-webkit-media-controls-current-time-display {
- display: none !important;
- }
- video::-webkit-media-controls-time-remaining-display {
- display: none !important;
- }
- video::-webkit-media-controls-mute-button {
- display: none !important;
- }
- video::-webkit-media-controls-volume-slider {
- display: none !important;
- }
- video::-webkit-media-controls-fullscreen-button {
- display: none !important;
- }
- /* 修改字幕覆盖层样式,使其与图片中的样式一致 */
- .subtitle-overlay {
- position: absolute;
- bottom: 180px; /* 调整位置,使其更靠近底部 */
- left: 5%; /* 从左侧留出5%的空间 */
- width: 80%; /* 宽度设为90%,两侧各留5%实现居中 */
- padding: 15px 20px; /* 增加左右内边距 */
- border-radius: 15px;
- background-color: rgba(255, 255, 255, 0.9); /* 白色半透明背景 */
- color: #333; /* 文字颜色为深色 */
- text-align: left; /* 文字左对齐 */
- font-size: 16px;
- line-height: 1.5;
- z-index: 10;
- margin: 0 auto; /* 添加自动边距实现居中 */
- box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 添加轻微阴影 */
- }
- /* 添加计时器样式,右侧显示橙色圆点和时间 */
- .subtitle-overlay::after {
- content: attr(data-time);
- position: absolute;
- right: 20px;
- bottom: 15px;
- color: #333;
- font-size: 14px;
- }
- .control-panel {
- padding: 15px;
- display: flex;
- justify-content: center;
- }
- .control-button {
- padding: 10px 20px;
- background-color: #4CAF50;
- color: white;
- border: none;
- border-radius: 4px;
- cursor: pointer;
- }
- .loading {
- text-align: center;
- margin: 20px 0;
- font-size: 16px;
- }
- .response-container {
- margin-top: 20px;
- padding: 0 20px;
- display: none; /* 默认隐藏调试信息 */
- }
- /* 当showDebugInfo为true时显示 */
- .showDebugInfo .response-container {
- display: block;
- }
- .response-item {
- padding: 10px;
- border: 1px solid #eee;
- border-radius: 4px;
- margin-bottom: 10px;
- background-color: #f9f9f9;
- }
- .response-content {
- display: flex;
- flex-direction: column;
- }
- .answer-button-container {
- position: absolute;
- bottom: 50px; /* 将按钮放在底部而不是75%的位置 */
- left: 50%;
- transform: translateX(-50%); /* 只在X轴上平移,保持水平居中 */
- z-index: 20;
- }
- /* 修改回答按钮样式 */
- .answer-button {
- width: 120px;
- height: 40px; /* 改为矩形按钮 */
- border-radius: 20px; /* 圆角矩形 */
- background-color: #ffffff; /* 白色背景 */
- color: #333; /* 深色文字 */
- font-size: 16px;
- border: none;
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
- display: flex;
- justify-content: center;
- align-items: center;
- cursor: pointer;
- animation: none; /* 移除脉动动画 */
- }
- .stop-recording-button-container {
- position: absolute;
- bottom: 50px; /* 统一与其他按钮的位置 */
- left: 50%;
- transform: translateX(-50%);
- z-index: 20;
- }
- .stop-recording-button {
- width: 120px;
- height: 40px; /* 改为矩形按钮 */
- border-radius: 20px; /* 圆角矩形 */
- background-color: #0039b3; /* 白色背景 */
- color: #fff; /* 深色文字 */
- font-size: 16px;
- border: none;
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
- display: flex;
- justify-content: center;
- align-items: center;
- cursor: pointer;
- animation: none; /* 移除脉动动画 */
- }
- .recording-indicator {
- position: absolute;
- top: 20px;
- left: 20px;
- display: flex;
- align-items: center;
- background-color: rgba(255, 255, 255, 0.9); /* 改为白色半透明背景 */
- padding: 5px 10px;
- border-radius: 15px;
- z-index: 20;
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
- }
- .recording-dot {
- width: 12px;
- height: 12px;
- background-color: #ff6b00; /* 改为橙色,与图片中的颜色一致 */
- border-radius: 50%;
- margin-right: 8px;
- animation: blink 1s infinite;
- }
- .recording-text {
- color: #333; /* 改为深色文字 */
- font-size: 14px;
- }
- .timer-text {
- color: #333; /* 改为深色文字 */
- font-size: 14px;
- margin-left: 8px;
- }
- .start-recording-button-container {
- position: absolute;
- bottom: 50px; /* 统一与其他按钮的位置 */
- left: 50%;
- transform: translateX(-50%);
- z-index: 101;
- }
- .start-recording-button {
- width: 120px;
- height: 40px; /* 改为矩形按钮 */
- border-radius: 20px; /* 圆角矩形 */
- background-color: #ffffff; /* 白色背景 */
- color: #333; /* 深色文字 */
- font-size: 16px;
- border: none;
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
- display: flex;
- justify-content: center;
- align-items: center;
- cursor: pointer;
- animation: none; /* 移除脉动动画 */
- }
- .retry-button-container {
- position: absolute;
- bottom: 30px; /* 统一与其他按钮的位置 */
- left: 50%;
- transform: translateX(-50%);
- z-index: 20;
- }
- .retry-button {
- padding: 10px 20px;
- background-color: #ffffff; /* 白色背景 */
- color: #333; /* 深色文字 */
- font-size: 16px;
- border: none;
- border-radius: 20px; /* 圆角矩形 */
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
- cursor: pointer;
- }
- .retry-button:hover {
- background-color: #2980b9;
- }
- /* 录制时长显示 */
- .recording-timer {
- position: absolute;
- top: 20px;
- left: 130px; /* 放在录制指示器旁边 */
- background-color: rgba(0, 0, 0, 0.6);
- padding: 5px 10px;
- border-radius: 15px;
- z-index: 20;
- display: flex;
- flex-direction: column;
- }
- .timer-text {
- color: #000;
- font-size: 14px;
- font-family: monospace; /* 使用等宽字体,使时间显示更稳定 */
- }
- .remaining-time {
- color: white;
- font-size: 12px;
- margin-top: 2px;
- }
- .remaining-time.warning {
- color: #ff6b6b; /* 剩余时间少时显示红色 */
- animation: blink 1s infinite; /* 使用闪烁动画提醒用户 */
- }
- /* 添加上传状态指示器 */
- .upload-status-indicator {
- position: absolute;
- top: 20px;
- left: 130px; /* 放在录制指示器旁边 */
- background-color: rgba(0, 0, 0, 0.6);
- padding: 5px 10px;
- border-radius: 15px;
- z-index: 20;
- }
- .upload-status-content {
- display: flex;
- align-items: center;
- }
- .upload-status-icon {
- width: 12px;
- height: 12px;
- border-radius: 50%;
- margin-right: 8px;
- }
- .upload-status-text {
- color: white;
- font-size: 14px;
- }
- .uploading {
- background-color: #e74c3c;
- }
- /* 添加倒计时蒙层样式 */
- .countdown-overlay {
- position: fixed;
- top: 0;
- left: 0;
- width: 100%;
- height: 100%;
- background-color: rgba(0, 0, 0, 0.7);
- z-index: 100;
- display: flex;
- justify-content: center;
- align-items: center;
- }
- .countdown-content {
- display: flex;
- flex-direction: column;
- align-items: center;
- }
- .countdown-number {
- font-size: 80px;
- color: #ffffff;
- font-weight: bold;
- margin-bottom: 20px;
- }
- .countdown-text {
- font-size: 24px;
- color: #ffffff;
- }
- /* 添加GIF播放器样式 */
- .gif-player {
- width: 100%;
- height: 100%;
- object-fit: cover;
- position: absolute;
- top: 0;
- left: 0;
- z-index: 5; /* 确保GIF在视频上方但在字幕和按钮下方 */
- }
- /* AI语音播放蒙层样式 */
- .ai-voice-overlay {
- position: fixed;
- top: 0;
- left: 0;
- width: 100%;
- height: 100%;
- background-color: rgba(0, 0, 0, 0.8); /* 0.8的透明度 */
- z-index: 99; /* 确保在其他元素之上,但在倒计时蒙层之下 */
- display: flex;
- justify-content: center;
- align-items: center;
- }
- .ai-voice-content {
- display: flex;
- flex-direction: column;
- align-items: center;
- color: #ffffff;
- }
- .ai-voice-icon {
- width: 40px;
- height: 40px;
- border-radius: 50%;
- background-color: #ffffff;
- margin-bottom: 15px;
- position: relative;
- animation: pulse 1.5s infinite;
- }
- .ai-voice-icon::before {
- content: '';
- position: absolute;
- top: 50%;
- left: 50%;
- transform: translate(-50%, -50%);
- width: 20px;
- height: 20px;
- background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23333"><path d="M12 15c1.66 0 3-1.34 3-3V6c0-1.66-1.34-3-3-3S9 4.34 9 6v6c0 1.66 1.34 3 3 3zm-1-9c0-.55.45-1 1-1s1 .45 1 1v6c0 .55-.45 1-1 1s-1-.45-1-1V6z"/><path d="M17 11c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z"/></svg>');
- background-repeat: no-repeat;
- background-position: center;
- }
- .ai-voice-text {
- font-size: 18px;
- color: #ffffff;
- }
- @keyframes pulse {
- 0% {
- transform: scale(1);
- opacity: 1;
- }
- 50% {
- transform: scale(1.1);
- opacity: 0.8;
- }
- 100% {
- transform: scale(1);
- opacity: 1;
- }
- }
- /* 继续提问按钮样式 */
- .continue-question-container {
- position: absolute;
- bottom: 100px; /* 位置高于结束面试按钮 */
- left: 50%;
- transform: translateX(-50%);
- z-index: 20;
- }
- .continue-question-button {
- width: 120px;
- height: 40px;
- border-radius: 20px;
- background-color: #ffffff;
- color: #333;
- font-size: 16px;
- border: none;
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
- display: flex;
- justify-content: center;
- align-items: center;
- cursor: pointer;
- }
- /* 结束面试按钮样式 */
- .end-interview-container {
- position: absolute;
- bottom: 50px;
- left: 50%;
- transform: translateX(-50%);
- z-index: 20;
- }
- .end-interview-button {
- width: 120px;
- height: 40px;
- border-radius: 20px;
- background-color: #e74c3c; /* 红色背景 */
- color: #ffffff; /* 白色文字 */
- font-size: 16px;
- border: none;
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
- display: flex;
- justify-content: center;
- align-items: center;
- cursor: pointer;
- }
- /* 提问轮次指示器样式 */
- .question-round-indicator {
- position: absolute;
- top: 20px;
- right: 120px; /* 位置在用户摄像头左侧 */
- background-color: rgba(255, 255, 255, 0.9);
- padding: 5px 10px;
- border-radius: 15px;
- z-index: 20;
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
- }
- .round-text {
- color: #333;
- font-size: 14px;
- }
- </style>
|