interview-question.vue 159 KB

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