interview-question.vue 136 KB

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