interview-question.vue 137 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360
  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. // 移除延迟,直接跳转
  1982. uni.navigateTo({
  1983. url: '/pages/interview-result/interview-result?uploading=' + (this.uploadQueue.length > 0 ? 'true' : 'false'),
  1984. success: () => {
  1985. console.log('成功跳转到结果页面');
  1986. },
  1987. fail: (err) => {
  1988. console.error('跳转失败:', err);
  1989. // 如果跳转失败,尝试跳转到其他页面
  1990. uni.navigateTo({
  1991. url: '/pages/posture-guide/posture-guide',
  1992. fail: (err2) => {
  1993. console.error('备用跳转也失败:', err2);
  1994. // 最后尝试返回上一页
  1995. uni.navigateBack({
  1996. delta: 1
  1997. });
  1998. }
  1999. });
  2000. }
  2001. });
  2002. },
  2003. // 修改 handleAnswerButtonClick 方法
  2004. handleAnswerButtonClick() {
  2005. // 隐藏答题按钮
  2006. this.showAnswerButton = false;
  2007. // 显示简短提示
  2008. uni.showToast({
  2009. title: '面试完成',
  2010. icon: 'success',
  2011. duration: 500 // 只显示0.5秒
  2012. });
  2013. // 如果有最后上传的视频URL,提交到AI语音交互接口
  2014. if (this.lastUploadedVideoUrl) {
  2015. this.submitToAiVoiceInteraction(this.lastUploadedVideoUrl);
  2016. } else {
  2017. // 没有视频URL,直接跳转
  2018. this.navigateToNextPage();
  2019. }
  2020. },
  2021. // 处理相机错误
  2022. handleCameraError(e) {
  2023. console.error('相机错误:', e);
  2024. // 获取平台信息
  2025. const systemInfo = uni.getSystemInfoSync();
  2026. const isIOS = systemInfo.platform === 'ios';
  2027. if (isIOS) {
  2028. console.log('iOS相机错误,尝试重新初始化');
  2029. // 显示提示
  2030. uni.showToast({
  2031. title: '相机初始化中...',
  2032. icon: 'loading',
  2033. duration: 2000
  2034. });
  2035. // 重置相机
  2036. this.resetCamera();
  2037. // 如果正在录制,停止录制
  2038. if (this.isRecording) {
  2039. this.isRecording = false;
  2040. this.showStopRecordingButton = false;
  2041. // 提供替代选项
  2042. setTimeout(() => {
  2043. this.useAlternativeRecordingMethod();
  2044. }, 1000);
  2045. }
  2046. } else {
  2047. // 显示错误提示
  2048. uni.showToast({
  2049. title: '相机初始化失败,请检查权限设置',
  2050. icon: 'none'
  2051. });
  2052. // 尝试备用选项
  2053. this.tryFallbackOptions();
  2054. }
  2055. },
  2056. // 添加新方法:尝试备用选项
  2057. tryFallbackOptions() {
  2058. // 检查环境
  2059. const systemInfo = uni.getSystemInfoSync();
  2060. // 在小程序环境中使用小程序API
  2061. if (systemInfo.uniPlatform === 'mp-weixin' || systemInfo.uniPlatform === 'mp-alipay') {
  2062. this.useMiniProgramCamera();
  2063. }
  2064. // 在H5环境中显示静态图像
  2065. else {
  2066. this.showStaticCameraPlaceholder();
  2067. }
  2068. },
  2069. // 添加新方法:使用小程序相机API
  2070. useMiniProgramCamera() {
  2071. console.log('尝试使用小程序相机组件');
  2072. // 这里需要在模板中添加小程序相机组件
  2073. // 并设置一个标志来控制显示
  2074. this.useMiniProgramCameraComponent = true;
  2075. },
  2076. // 添加新方法:显示静态图像
  2077. showStaticCameraPlaceholder() {
  2078. console.log('显示静态摄像头占位图');
  2079. // 创建一个图像元素
  2080. const img = document.createElement('img');
  2081. img.src = '/static/images/camera-placeholder.png'; // 确保有这个图片资源
  2082. img.className = 'static-camera-image';
  2083. img.style.width = '100%';
  2084. img.style.height = '100%';
  2085. img.style.objectFit = 'cover';
  2086. // 获取容器并添加图像
  2087. const container = this.$refs.userCameraVideo.parentNode;
  2088. container.appendChild(img);
  2089. },
  2090. // 处理视频时间更新事件
  2091. handleTimeUpdate(e) {
  2092. // 获取当前视频播放时间
  2093. const currentTime = e.target.currentTime;
  2094. // 如果正在录制,更新录制时间显示
  2095. if (this.isRecording && this.recordingTimerCount) {
  2096. this.recordingTimeDisplay = this.formatTime(this.recordingTimerCount);
  2097. }
  2098. // 根据当前播放的视频索引选择对应的字幕数组
  2099. let currentSubtitles;
  2100. if (this.currentVideoIndex === 0) {
  2101. currentSubtitles = this.subtitles;
  2102. } else if (this.currentVideoIndex === 1) {
  2103. currentSubtitles = this.secondVideoSubtitles;
  2104. } else if (this.currentVideoIndex === 2) {
  2105. currentSubtitles = this.thirdVideoSubtitles;
  2106. } else if (this.currentVideoIndex === 3) {
  2107. currentSubtitles = this.fourthVideoSubtitles;
  2108. } else if (this.currentVideoIndex === 4) {
  2109. currentSubtitles = this.fifthVideoSubtitles;
  2110. } else if (this.currentVideoIndex === 5) {
  2111. currentSubtitles = this.sixthVideoSubtitles;
  2112. } else {
  2113. // 如果有更多视频,可以继续添加条件
  2114. currentSubtitles = [];
  2115. }
  2116. // 查找当前时间应该显示的字幕
  2117. const subtitle = currentSubtitles.find(
  2118. sub => currentTime >= sub.startTime && currentTime < sub.endTime
  2119. );
  2120. // 更新当前字幕
  2121. this.currentSubtitle = subtitle ? subtitle.text : '';
  2122. },
  2123. // Add a new method to handle the "Start Recording" button click
  2124. handleStartRecordingClick() {
  2125. // 隐藏"开始回答"按钮
  2126. this.showStartRecordingButton = false;
  2127. // 如果倒计时正在进行,清除倒计时
  2128. this.clearCountdown();
  2129. // 开始录制
  2130. this.startRecordingAnswer();
  2131. },
  2132. // 修改 checkAudioPermission 方法,确保在录制前获取音频权限
  2133. checkAudioPermission() {
  2134. // 在小程序环境中
  2135. const systemInfo = uni.getSystemInfoSync();
  2136. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
  2137. if (isMiniProgram) {
  2138. // 小程序环境下的权限请求
  2139. uni.getSetting({
  2140. success: (res) => {
  2141. if (!res.authSetting['scope.record']) {
  2142. uni.authorize({
  2143. scope: 'scope.record',
  2144. success: () => {
  2145. console.log('录音权限已获取');
  2146. },
  2147. fail: (err) => {
  2148. console.error('录音权限获取失败:', err);
  2149. this.showPermissionDialog('录音');
  2150. }
  2151. });
  2152. }
  2153. if (!res.authSetting['scope.camera']) {
  2154. uni.authorize({
  2155. scope: 'scope.camera',
  2156. success: () => {
  2157. console.log('相机权限已获取');
  2158. },
  2159. fail: (err) => {
  2160. console.error('相机权限获取失败:', err);
  2161. this.showPermissionDialog('相机');
  2162. }
  2163. });
  2164. }
  2165. }
  2166. });
  2167. } else {
  2168. // 浏览器环境下的权限请求
  2169. // ... 保持原有代码不变
  2170. }
  2171. },
  2172. // 添加新方法:测试音频输入
  2173. testAudioInput() {
  2174. if (!this.cameraStream) {
  2175. console.warn('没有可用的媒体流,无法测试音频');
  2176. return;
  2177. }
  2178. const audioTracks = this.cameraStream.getAudioTracks();
  2179. if (audioTracks.length === 0) {
  2180. console.warn('没有检测到音频轨道,尝试重新获取');
  2181. this.tryGetAudioOnly();
  2182. return;
  2183. }
  2184. console.log('音频轨道信息:', audioTracks[0].getSettings());
  2185. // 创建音频上下文和分析器
  2186. try {
  2187. const AudioContext = window.AudioContext || window.webkitAudioContext;
  2188. if (!AudioContext) {
  2189. console.warn('浏览器不支持AudioContext');
  2190. return;
  2191. }
  2192. const audioContext = new AudioContext();
  2193. const analyser = audioContext.createAnalyser();
  2194. const microphone = audioContext.createMediaStreamSource(this.cameraStream);
  2195. microphone.connect(analyser);
  2196. // 设置分析器
  2197. analyser.fftSize = 256;
  2198. const bufferLength = analyser.frequencyBinCount;
  2199. const dataArray = new Uint8Array(bufferLength);
  2200. // 检测音频输入
  2201. let silenceCounter = 0;
  2202. const checkAudio = () => {
  2203. if (this.isRecording) return; // 如果正在录制,停止检测
  2204. analyser.getByteFrequencyData(dataArray);
  2205. // 计算平均音量
  2206. let sum = 0;
  2207. for (let i = 0; i < bufferLength; i++) {
  2208. sum += dataArray[i];
  2209. }
  2210. const average = sum / bufferLength;
  2211. if (average > 10) {
  2212. console.log('检测到音频输入,音量:', average);
  2213. silenceCounter = 0;
  2214. } else {
  2215. silenceCounter++;
  2216. if (silenceCounter > 10) {
  2217. console.warn('持续检测不到音频输入,可能麦克风未正常工作');
  2218. silenceCounter = 0;
  2219. }
  2220. }
  2221. // 继续检测
  2222. requestAnimationFrame(checkAudio);
  2223. };
  2224. // 开始检测
  2225. checkAudio();
  2226. } catch (e) {
  2227. console.error('音频测试失败:', e);
  2228. }
  2229. },
  2230. // 添加新方法:尝试单独获取音频
  2231. tryGetAudioOnly() {
  2232. navigator.mediaDevices.getUserMedia({ audio: true })
  2233. .then(audioStream => {
  2234. // 如果已有视频流,合并音频和视频轨道
  2235. if (this.cameraStream) {
  2236. const videoTrack = this.cameraStream.getVideoTracks()[0];
  2237. const audioTrack = audioStream.getAudioTracks()[0];
  2238. // 创建新的媒体流,包含视频和音频轨道
  2239. const combinedStream = new MediaStream();
  2240. if (videoTrack) combinedStream.addTrack(videoTrack);
  2241. if (audioTrack) combinedStream.addTrack(audioTrack);
  2242. // 更新摄像头流
  2243. this.cameraStream = combinedStream;
  2244. // 更新视频元素的源
  2245. const videoElement = this.$refs.userCameraVideo;
  2246. if (videoElement) {
  2247. videoElement.srcObject = combinedStream;
  2248. videoElement.muted = true; // 避免回声,但仍然录制声音
  2249. }
  2250. console.log('成功合并音频和视频轨道');
  2251. } else {
  2252. console.warn('没有视频流可合并');
  2253. }
  2254. })
  2255. .catch(err => {
  2256. console.error('单独获取音频失败:', err);
  2257. });
  2258. },
  2259. // 添加新方法:显示权限对话框
  2260. showPermissionDialog(permissionType) {
  2261. uni.showModal({
  2262. title: '需要权限',
  2263. content: `请允许使用${permissionType}权限,否则可能影响面试功能`,
  2264. confirmText: '去设置',
  2265. success: (res) => {
  2266. if (res.confirm) {
  2267. uni.openSetting({
  2268. success: (settingRes) => {
  2269. console.log('设置页面打开成功', settingRes);
  2270. }
  2271. });
  2272. }
  2273. }
  2274. });
  2275. },
  2276. // 添加重试上传方法
  2277. retryVideoUpload() {
  2278. if (this.lastVideoToRetry) {
  2279. // 隐藏重试按钮
  2280. this.showRetryButton = false;
  2281. // 显示加载提示
  2282. uni.showLoading({
  2283. title: '正在重新提交...',
  2284. mask: true
  2285. });
  2286. // 重新提交视频
  2287. this.submitVideoToInterview(this.lastVideoToRetry);
  2288. } else {
  2289. uni.showToast({
  2290. title: '没有可重试的视频',
  2291. icon: 'none'
  2292. });
  2293. }
  2294. },
  2295. // 添加一个新方法用于压缩视频
  2296. async compressVideo(videoBlob) {
  2297. // 如果视频大小小于某个阈值,直接返回原视频
  2298. if (videoBlob.size < 5 * 1024 * 1024) { // 小于5MB
  2299. return videoBlob;
  2300. }
  2301. console.log('开始压缩视频,原始大小:', videoBlob.size);
  2302. // 创建一个视频元素来加载视频
  2303. const videoElement = document.createElement('video');
  2304. videoElement.muted = true;
  2305. videoElement.autoplay = false;
  2306. // 创建一个canvas元素用于绘制视频帧
  2307. const canvas = document.createElement('canvas');
  2308. const ctx = canvas.getContext('2d');
  2309. // 设置视频源
  2310. videoElement.src = URL.createObjectURL(videoBlob);
  2311. return new Promise((resolve) => {
  2312. videoElement.onloadedmetadata = () => {
  2313. // 设置canvas尺寸为视频的一半
  2314. const width = Math.floor(videoElement.videoWidth / 2);
  2315. const height = Math.floor(videoElement.videoHeight / 2);
  2316. canvas.width = width;
  2317. canvas.height = height;
  2318. // 创建MediaRecorder来录制canvas
  2319. const stream = canvas.captureStream(15); // 15fps
  2320. // 如果原视频有音轨,添加到新流中
  2321. if (videoElement.captureStream) {
  2322. const originalStream = videoElement.captureStream();
  2323. const audioTracks = originalStream.getAudioTracks();
  2324. if (audioTracks.length > 0) {
  2325. stream.addTrack(audioTracks[0]);
  2326. }
  2327. }
  2328. // 设置较低的比特率
  2329. const options = {
  2330. mimeType: 'video/webm;codecs=vp8,opus',
  2331. audioBitsPerSecond: 64000,
  2332. videoBitsPerSecond: 800000 // 800kbps
  2333. };
  2334. const mediaRecorder = new MediaRecorder(stream, options);
  2335. const chunks = [];
  2336. mediaRecorder.ondataavailable = (e) => {
  2337. if (e.data.size > 0) {
  2338. chunks.push(e.data);
  2339. }
  2340. };
  2341. mediaRecorder.onstop = () => {
  2342. const compressedBlob = new Blob(chunks, { type: 'video/webm' });
  2343. console.log('视频压缩完成,压缩后大小:', compressedBlob.size);
  2344. resolve(compressedBlob);
  2345. };
  2346. // 开始播放视频并录制
  2347. videoElement.onplay = () => {
  2348. mediaRecorder.start(100);
  2349. // 绘制视频帧到canvas
  2350. const drawFrame = () => {
  2351. if (videoElement.paused || videoElement.ended) {
  2352. mediaRecorder.stop();
  2353. return;
  2354. }
  2355. ctx.drawImage(videoElement, 0, 0, width, height);
  2356. requestAnimationFrame(drawFrame);
  2357. };
  2358. drawFrame();
  2359. };
  2360. videoElement.play();
  2361. };
  2362. });
  2363. },
  2364. // 修改 checkIOSCameraRecordPermission 方法
  2365. checkIOSCameraRecordPermission() {
  2366. const systemInfo = uni.getSystemInfoSync();
  2367. if (systemInfo.platform !== 'ios') return;
  2368. // 在iOS上,需要同时请求相机和录音权限
  2369. uni.getSetting({
  2370. success: (res) => {
  2371. // 检查相机权限
  2372. if (!res.authSetting['scope.camera']) {
  2373. uni.authorize({
  2374. scope: 'scope.camera',
  2375. success: () => {
  2376. console.log('iOS相机权限已获取');
  2377. },
  2378. fail: (err) => {
  2379. console.error('iOS相机权限获取失败:', err);
  2380. this.showPermissionDialog('相机');
  2381. }
  2382. });
  2383. }
  2384. // 检查录音权限
  2385. if (!res.authSetting['scope.record']) {
  2386. uni.authorize({
  2387. scope: 'scope.record',
  2388. success: () => {
  2389. console.log('iOS录音权限已获取');
  2390. },
  2391. fail: (err) => {
  2392. console.error('iOS录音权限获取失败:', err);
  2393. this.showPermissionDialog('录音');
  2394. }
  2395. });
  2396. }
  2397. }
  2398. });
  2399. },
  2400. // 添加新方法:检查并修复渲染问题
  2401. checkAndFixRenderingIssues() {
  2402. // 检查全局对象,防止渲染错误
  2403. try {
  2404. // 检查是否有全局变量u
  2405. if (typeof u !== 'undefined' && u) {
  2406. // 检查currentQuestion属性
  2407. if (!u.currentQuestion) {
  2408. console.log('修复: 创建缺失的currentQuestion对象');
  2409. u.currentQuestion = {};
  2410. }
  2411. // 确保isImportant属性存在
  2412. if (u.currentQuestion && typeof u.currentQuestion.isImportant === 'undefined') {
  2413. console.log('修复: 设置缺失的isImportant属性');
  2414. u.currentQuestion.isImportant = false;
  2415. }
  2416. }
  2417. } catch (e) {
  2418. console.log('防御性检查异常:', e);
  2419. }
  2420. },
  2421. // 添加格式化时间的辅助方法
  2422. formatTime(seconds) {
  2423. if (!seconds && seconds !== 0) return '03:30'; // 默认显示03:30
  2424. const minutes = Math.floor(seconds / 60);
  2425. const remainingSeconds = seconds % 60;
  2426. return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
  2427. },
  2428. // 添加新方法:保存上传状态到本地存储
  2429. saveUploadStatus() {
  2430. const uploadStatus = {
  2431. isUploading: this.isUploading,
  2432. uploadQueue: this.uploadQueue.length,
  2433. timestamp: Date.now()
  2434. };
  2435. try {
  2436. uni.setStorageSync('videoUploadStatus', JSON.stringify(uploadStatus));
  2437. } catch (e) {
  2438. console.error('保存上传状态失败:', e);
  2439. }
  2440. },
  2441. // 修改 submitToAiVoiceInteraction 方法
  2442. submitToAiVoiceInteraction(videoUrl) {
  2443. console.log('提交视频到AI语音交互接口:', videoUrl);
  2444. // 显示加载提示
  2445. uni.showLoading({
  2446. title: '面试官正在思考...',
  2447. mask: true
  2448. });
  2449. // 获取用户信息和租户ID
  2450. const tenant_id = uni.getStorageSync('tenant_id') || '1';
  2451. const application_id = uni.getStorageSync('appId') || '98'; // 默认为98(报告)
  2452. // 准备请求数据
  2453. const requestData = {
  2454. voice_url: videoUrl,
  2455. tenant_id: tenant_id,
  2456. application_id: application_id,
  2457. scene_type: 'interview', // 场景类型:面试
  2458. voice_type: 'longxiaoxia', // 角色:龙小侠
  2459. conversation_history: this.conversationHistory // 添加对话历史
  2460. };
  2461. // 检查环境
  2462. const systemInfo = uni.getSystemInfoSync();
  2463. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
  2464. if (isMiniProgram) {
  2465. // 小程序环境使用 uni.request
  2466. uni.request({
  2467. url: `${apiBaseUrl}/api/system/voice/mcp/interaction`, // 使用新的接口地址
  2468. method: 'POST',
  2469. data: requestData,
  2470. header: {
  2471. 'content-type': 'application/json' // 修改为JSON格式
  2472. },
  2473. success: (res) => {
  2474. this.handleAiInteractionResponse(res.data);
  2475. },
  2476. fail: (err) => {
  2477. this.handleAiInteractionError(err);
  2478. }
  2479. });
  2480. } else {
  2481. // H5/App环境使用 XMLHttpRequest
  2482. const xhr = new XMLHttpRequest();
  2483. xhr.open('POST', `${apiBaseUrl}/api/system/voice/mcp/interaction`, true);
  2484. xhr.timeout = 60000; // 60秒超时
  2485. xhr.setRequestHeader('Content-Type', 'application/json');
  2486. xhr.onload = () => {
  2487. if (xhr.status === 200) {
  2488. try {
  2489. const response = JSON.parse(xhr.responseText);
  2490. this.handleAiInteractionResponse(response);
  2491. } catch (e) {
  2492. console.error('解析AI响应失败:', e);
  2493. this.handleAiInteractionError({ errMsg: '解析响应失败' });
  2494. }
  2495. } else {
  2496. this.handleAiInteractionError({ errMsg: 'HTTP状态: ' + xhr.status });
  2497. }
  2498. };
  2499. xhr.onerror = () => {
  2500. this.handleAiInteractionError({ errMsg: '网络错误' });
  2501. };
  2502. xhr.ontimeout = () => {
  2503. this.handleAiInteractionError({ errMsg: '请求超时' });
  2504. };
  2505. // 发送JSON格式的数据
  2506. xhr.send(JSON.stringify(requestData));
  2507. }
  2508. },
  2509. // 添加处理AI交互响应的方法
  2510. handleAiInteractionResponse(data) {
  2511. console.log('AI语音交互接口响应:', data);
  2512. // 隐藏加载提示
  2513. uni.hideLoading();
  2514. // 重置备选方法尝试标志
  2515. this.hasTriedFallbackMethod = false;
  2516. if (data && data.success) {
  2517. // 保存AI回复数据
  2518. this.aiText = data.ai_text || '';
  2519. this.transcribedText = data.transcribed_text ? data.transcribed_text.text : '';
  2520. // 记录对话历史
  2521. this.conversationHistory.push({
  2522. role: 'user',
  2523. content: this.transcribedText
  2524. });
  2525. this.conversationHistory.push({
  2526. role: 'assistant',
  2527. content: this.aiText
  2528. });
  2529. // 获取AI语音URL
  2530. const aiVoiceUrl = data.ai_voice_url || '';
  2531. if (aiVoiceUrl) {
  2532. // 构建完整的URL
  2533. this.aiVoiceUrl = aiVoiceUrl.startsWith('http')
  2534. ? aiVoiceUrl
  2535. : `${apiBaseUrl}${aiVoiceUrl}`;
  2536. console.log('AI语音URL:', this.aiVoiceUrl);
  2537. // 显示AI回复文本作为字幕
  2538. this.currentSubtitle = this.aiText;
  2539. // 检查平台
  2540. const systemInfo = uni.getSystemInfoSync();
  2541. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
  2542. // 检查音频URL是否包含不支持的格式
  2543. const isUnsupportedFormat = this.checkUnsupportedAudioFormat(this.aiVoiceUrl);
  2544. if (isUnsupportedFormat && isMiniProgram) {
  2545. console.warn('检测到小程序不支持的音频格式,直接使用文本显示');
  2546. this.displayTextResponse();
  2547. return;
  2548. }
  2549. // 根据平台选择不同的播放方法
  2550. if (isMiniProgram) {
  2551. // 小程序环境使用原生API
  2552. this.playMiniProgramAudio();
  2553. } else {
  2554. // H5/App环境使用通用方法
  2555. this.playAiVoice();
  2556. }
  2557. // 重要:确保在AI语音播放期间不显示继续提问按钮
  2558. this.showContinueQuestionButton = false;
  2559. this.showEndInterviewButton = false;
  2560. } else {
  2561. console.warn('未获取到AI语音URL,使用文本显示');
  2562. // 如果没有语音URL,显示文本回复
  2563. this.displayTextResponse();
  2564. }
  2565. } else {
  2566. console.error('AI语音交互失败:', data);
  2567. // AI交互失败,显示继续提问按钮
  2568. this.showContinueQuestionOptions();
  2569. // 检查是否需要自动跳转
  2570. this.checkPendingNavigation();
  2571. }
  2572. },
  2573. // 修改 handleAiInteractionError 方法,不要直接跳转,而是显示继续提问选项
  2574. handleAiInteractionError(err) {
  2575. console.error('AI语音交互请求失败:', err);
  2576. uni.hideLoading();
  2577. // 显示错误提示
  2578. uni.showToast({
  2579. title: 'AI处理失败,请重试',
  2580. icon: 'none',
  2581. duration: 2000
  2582. });
  2583. // 请求失败,显示继续提问选项,而不是直接跳转
  2584. this.showContinueQuestionOptions();
  2585. },
  2586. // 添加新方法:播放AI语音
  2587. playAiVoice() {
  2588. console.log('开始播放AI语音:', this.aiVoiceUrl);
  2589. // 标记正在播放AI语音
  2590. this.isPlayingAiVoice = true;
  2591. // 确保在播放期间不显示继续提问按钮
  2592. this.showContinueQuestionButton = false;
  2593. this.showEndInterviewButton = false;
  2594. // 检查音频URL是否有效
  2595. if (!this.aiVoiceUrl || this.aiVoiceUrl.trim() === '') {
  2596. console.error('无效的音频URL');
  2597. // 显示错误提示
  2598. uni.showToast({
  2599. title: '音频加载失败',
  2600. icon: 'none',
  2601. duration: 2000
  2602. });
  2603. // 标记播放结束
  2604. this.isPlayingAiVoice = false;
  2605. // 显示继续提问选项
  2606. this.showContinueQuestionOptions();
  2607. return;
  2608. }
  2609. try {
  2610. // 创建音频播放器 - 使用 uni.createInnerAudioContext 而不是直接赋值
  2611. if (this.aiAudioPlayer) {
  2612. // 如果已存在,先销毁
  2613. this.aiAudioPlayer.destroy();
  2614. }
  2615. // 重新创建音频上下文
  2616. this.aiAudioPlayer = uni.createInnerAudioContext();
  2617. // 设置音频属性
  2618. this.aiAudioPlayer.autoplay = false; // 不自动播放,手动控制
  2619. this.aiAudioPlayer.obeyMuteSwitch = false; // 忽略静音开关
  2620. // 监听播放开始事件
  2621. this.aiAudioPlayer.onPlay(() => {
  2622. console.log('AI语音开始播放');
  2623. // 显示正在播放提示
  2624. uni.showToast({
  2625. title: '正在播放面试官的回复',
  2626. icon: 'none',
  2627. duration: 2000
  2628. });
  2629. });
  2630. // 监听播放结束事件
  2631. this.aiAudioPlayer.onEnded(() => {
  2632. console.log('AI语音播放结束');
  2633. // 标记播放结束
  2634. this.isPlayingAiVoice = false;
  2635. // 清空字幕
  2636. this.currentSubtitle = '';
  2637. // 销毁音频播放器
  2638. if (this.aiAudioPlayer) {
  2639. this.aiAudioPlayer.destroy();
  2640. this.aiAudioPlayer = null;
  2641. }
  2642. // 播放结束后显示继续提问选项
  2643. this.showContinueQuestionOptions();
  2644. // 检查是否需要自动跳转
  2645. this.checkPendingNavigation();
  2646. });
  2647. // 监听播放错误事件
  2648. this.aiAudioPlayer.onError((err) => {
  2649. console.error('AI语音播放错误:', err);
  2650. // 尝试使用备选方法播放
  2651. if (!this.hasTriedFallbackMethod) {
  2652. this.hasTriedFallbackMethod = true;
  2653. console.log('尝试使用备选方法播放音频');
  2654. this.tryFallbackAudioPlay();
  2655. return;
  2656. }
  2657. // 标记播放结束
  2658. this.isPlayingAiVoice = false;
  2659. // 清空字幕
  2660. this.currentSubtitle = '';
  2661. // 销毁音频播放器
  2662. if (this.aiAudioPlayer) {
  2663. this.aiAudioPlayer.destroy();
  2664. this.aiAudioPlayer = null;
  2665. }
  2666. // 显示错误提示
  2667. uni.showToast({
  2668. title: '音频播放失败,请查看文字回复',
  2669. icon: 'none',
  2670. duration: 2000
  2671. });
  2672. // 播放错误时也显示继续提问选项
  2673. this.showContinueQuestionOptions();
  2674. // 检查是否需要自动跳转
  2675. this.checkPendingNavigation();
  2676. });
  2677. // 监听音频加载事件
  2678. this.aiAudioPlayer.onCanplay(() => {
  2679. console.log('音频已准备好播放');
  2680. // 可以在这里添加额外的处理
  2681. });
  2682. // 设置音频源
  2683. this.aiAudioPlayer.src = this.aiVoiceUrl;
  2684. // 添加超时处理,如果5秒内没有开始播放,则认为出错
  2685. const playTimeout = setTimeout(() => {
  2686. if (this.isPlayingAiVoice && this.aiAudioPlayer) {
  2687. console.warn('音频播放超时,尝试备选方法');
  2688. this.tryFallbackAudioPlay();
  2689. }
  2690. }, 5000);
  2691. // 延迟一小段时间再播放,确保src已经设置完成
  2692. setTimeout(() => {
  2693. if (this.aiAudioPlayer) {
  2694. this.aiAudioPlayer.play();
  2695. // 播放开始后清除超时
  2696. clearTimeout(playTimeout);
  2697. }
  2698. }, 300);
  2699. } catch (e) {
  2700. console.error('播放AI语音时发生错误:', e);
  2701. // 标记播放结束
  2702. this.isPlayingAiVoice = false;
  2703. // 清空字幕
  2704. this.currentSubtitle = '';
  2705. // 尝试销毁音频播放器
  2706. if (this.aiAudioPlayer) {
  2707. try {
  2708. this.aiAudioPlayer.destroy();
  2709. } catch (destroyError) {
  2710. console.error('销毁音频播放器失败:', destroyError);
  2711. }
  2712. this.aiAudioPlayer = null;
  2713. }
  2714. // 显示错误提示
  2715. uni.showToast({
  2716. title: '音频播放失败,请查看文字回复',
  2717. icon: 'none',
  2718. duration: 2000
  2719. });
  2720. // 发生错误时显示继续提问选项
  2721. this.showContinueQuestionOptions();
  2722. // 检查是否需要自动跳转
  2723. this.checkPendingNavigation();
  2724. }
  2725. },
  2726. // 添加新方法:尝试备选音频播放方法
  2727. tryFallbackAudioPlay() {
  2728. console.log('使用备选方法播放音频:', this.aiVoiceUrl);
  2729. // 如果当前播放器存在,先销毁
  2730. if (this.aiAudioPlayer) {
  2731. try {
  2732. this.aiAudioPlayer.destroy();
  2733. } catch (e) {
  2734. console.error('销毁音频播放器失败:', e);
  2735. }
  2736. this.aiAudioPlayer = null;
  2737. }
  2738. // 使用uni.downloadFile先下载音频文件
  2739. uni.downloadFile({
  2740. url: this.aiVoiceUrl,
  2741. success: (res) => {
  2742. if (res.statusCode === 200) {
  2743. console.log('音频文件下载成功:', res.tempFilePath);
  2744. // 使用新的音频上下文播放本地文件
  2745. const newAudioPlayer = uni.createInnerAudioContext();
  2746. this.aiAudioPlayer = newAudioPlayer;
  2747. newAudioPlayer.autoplay = true;
  2748. newAudioPlayer.src = res.tempFilePath;
  2749. // 设置事件监听
  2750. newAudioPlayer.onPlay(() => {
  2751. console.log('备选方法:音频开始播放');
  2752. });
  2753. newAudioPlayer.onEnded(() => {
  2754. console.log('备选方法:音频播放结束');
  2755. this.isPlayingAiVoice = false;
  2756. this.currentSubtitle = '';
  2757. newAudioPlayer.destroy();
  2758. this.aiAudioPlayer = null;
  2759. this.showContinueQuestionOptions();
  2760. this.checkPendingNavigation();
  2761. });
  2762. newAudioPlayer.onError((err) => {
  2763. console.error('备选方法:音频播放错误:', err);
  2764. this.isPlayingAiVoice = false;
  2765. this.currentSubtitle = '';
  2766. newAudioPlayer.destroy();
  2767. this.aiAudioPlayer = null;
  2768. // 显示错误提示
  2769. uni.showToast({
  2770. title: '无法播放音频,请查看文字回复',
  2771. icon: 'none',
  2772. duration: 2000
  2773. });
  2774. this.showContinueQuestionOptions();
  2775. this.checkPendingNavigation();
  2776. });
  2777. } else {
  2778. console.error('音频文件下载失败:', res);
  2779. this.handleAudioPlaybackFailure();
  2780. }
  2781. },
  2782. fail: (err) => {
  2783. console.error('音频文件下载请求失败:', err);
  2784. this.handleAudioPlaybackFailure();
  2785. }
  2786. });
  2787. },
  2788. // 添加新方法:处理音频播放失败的情况
  2789. handleAudioPlaybackFailure() {
  2790. // 标记播放结束
  2791. this.isPlayingAiVoice = false;
  2792. // 显示错误提示
  2793. uni.showToast({
  2794. title: '无法播放音频,将直接显示文字回复',
  2795. icon: 'none',
  2796. duration: 2000
  2797. });
  2798. // 确保字幕显示足够长的时间(10秒)让用户阅读
  2799. this.currentSubtitle = this.aiText;
  2800. // 设置定时器,10秒后清除字幕并显示继续提问选项
  2801. setTimeout(() => {
  2802. this.currentSubtitle = '';
  2803. this.showContinueQuestionOptions();
  2804. this.checkPendingNavigation();
  2805. }, 10000);
  2806. },
  2807. // 添加新方法:从视频中提取音频
  2808. async extractAudioFromVideo(videoBlob) {
  2809. console.log('开始从视频中提取音频');
  2810. return new Promise((resolve, reject) => {
  2811. try {
  2812. // 创建一个视频元素来加载视频
  2813. const videoElement = document.createElement('video');
  2814. videoElement.muted = false;
  2815. videoElement.autoplay = false;
  2816. // 创建音频上下文
  2817. const audioContext = new (window.AudioContext || window.webkitAudioContext)();
  2818. let audioDestination = null;
  2819. let mediaRecorder = null;
  2820. const audioChunks = [];
  2821. // 设置视频源
  2822. videoElement.src = URL.createObjectURL(videoBlob);
  2823. videoElement.onloadedmetadata = () => {
  2824. console.log('视频元数据已加载,视频时长:', videoElement.duration);
  2825. // 创建媒体源和目标节点
  2826. const source = audioContext.createMediaElementSource(videoElement);
  2827. audioDestination = audioContext.createMediaStreamDestination();
  2828. source.connect(audioDestination);
  2829. // 创建MediaRecorder来录制音频
  2830. mediaRecorder = new MediaRecorder(audioDestination.stream);
  2831. mediaRecorder.ondataavailable = (event) => {
  2832. if (event.data.size > 0) {
  2833. audioChunks.push(event.data);
  2834. }
  2835. };
  2836. mediaRecorder.onstop = () => {
  2837. const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
  2838. console.log('音频提取完成,大小:', audioBlob.size);
  2839. resolve(audioBlob);
  2840. };
  2841. // 开始播放视频并录制音频
  2842. videoElement.onplay = () => {
  2843. mediaRecorder.start(100);
  2844. };
  2845. videoElement.onended = () => {
  2846. mediaRecorder.stop();
  2847. audioContext.close();
  2848. };
  2849. // 开始播放
  2850. videoElement.play();
  2851. };
  2852. videoElement.onerror = (err) => {
  2853. console.error('视频加载失败:', err);
  2854. reject(new Error('视频加载失败'));
  2855. };
  2856. } catch (err) {
  2857. console.error('提取音频失败:', err);
  2858. reject(err);
  2859. }
  2860. });
  2861. },
  2862. // 添加新方法:上传音频文件
  2863. async uploadAudioFile(audioBlob, videoUrl) {
  2864. console.log('准备上传音频文件');
  2865. // 创建FormData
  2866. const formData = new FormData();
  2867. // 将Blob转换为File对象
  2868. const fileName = `audio_${Date.now()}.wav`;
  2869. const audioFile = new File([audioBlob], fileName, { type: 'audio/wav' });
  2870. // 添加文件和其他参数
  2871. formData.append('audio_file', audioFile);
  2872. formData.append('video_url', videoUrl);
  2873. formData.append('tenant_id', uni.getStorageSync('tenant_id') || '1');
  2874. formData.append('openid', uni.getStorageSync('userInfo') ? JSON.parse(uni.getStorageSync('userInfo')).openid : '');
  2875. formData.append('application_id', uni.getStorageSync('appId') || '');
  2876. return new Promise((resolve, reject) => {
  2877. // 创建XMLHttpRequest
  2878. const xhr = new XMLHttpRequest();
  2879. xhr.open('POST', `${apiBaseUrl}/api/voice_ai_interaction`, true);
  2880. xhr.timeout = 60000; // 60秒超时
  2881. xhr.onload = () => {
  2882. if (xhr.status === 200) {
  2883. try {
  2884. const response = JSON.parse(xhr.responseText);
  2885. resolve(response);
  2886. } catch (e) {
  2887. reject(new Error('解析响应失败'));
  2888. }
  2889. } else {
  2890. reject(new Error('HTTP状态: ' + xhr.status));
  2891. }
  2892. };
  2893. xhr.onerror = () => {
  2894. reject(new Error('网络错误'));
  2895. };
  2896. xhr.ontimeout = () => {
  2897. reject(new Error('请求超时'));
  2898. };
  2899. xhr.send(formData);
  2900. });
  2901. },
  2902. // 添加一个新方法:使用小程序原生音频API
  2903. playMiniProgramAudio() {
  2904. console.log('使用小程序原生音频API播放:', this.aiVoiceUrl);
  2905. // 标记正在播放AI语音
  2906. this.isPlayingAiVoice = true;
  2907. // 确保在播放期间不显示继续提问按钮
  2908. this.showContinueQuestionButton = false;
  2909. this.showEndInterviewButton = false;
  2910. // 检查音频URL是否有效
  2911. if (!this.aiVoiceUrl || this.aiVoiceUrl.trim() === '') {
  2912. console.error('无效的音频URL');
  2913. // 显示错误提示
  2914. uni.showToast({
  2915. title: '音频加载失败',
  2916. icon: 'none',
  2917. duration: 2000
  2918. });
  2919. // 标记播放结束
  2920. this.isPlayingAiVoice = false;
  2921. // 显示继续提问选项
  2922. this.showContinueQuestionOptions();
  2923. return;
  2924. }
  2925. try {
  2926. // 使用wx.createInnerAudioContext API (微信小程序)
  2927. const audioContext = wx.createInnerAudioContext();
  2928. // 设置音频属性
  2929. audioContext.autoplay = false;
  2930. audioContext.obeyMuteSwitch = false; // 忽略静音开关
  2931. // 监听播放开始事件
  2932. audioContext.onPlay(() => {
  2933. console.log('AI语音开始播放');
  2934. // 显示正在播放提示
  2935. uni.showToast({
  2936. title: '正在播放AI回复',
  2937. icon: 'none',
  2938. duration: 2000
  2939. });
  2940. });
  2941. // 监听播放结束事件
  2942. audioContext.onEnded(() => {
  2943. console.log('AI语音播放结束');
  2944. // 标记播放结束
  2945. this.isPlayingAiVoice = false;
  2946. // 清空字幕
  2947. this.currentSubtitle = '';
  2948. // 销毁音频播放器
  2949. audioContext.destroy();
  2950. // 播放结束后显示继续提问选项,而不是直接跳转
  2951. this.showContinueQuestionOptions();
  2952. });
  2953. // 监听播放错误事件
  2954. audioContext.onError((err) => {
  2955. console.error('AI语音播放错误:', err);
  2956. // 标记播放结束
  2957. this.isPlayingAiVoice = false;
  2958. // 清空字幕
  2959. this.currentSubtitle = '';
  2960. // 销毁音频播放器
  2961. audioContext.destroy();
  2962. // 播放错误时也显示继续提问选项
  2963. this.showContinueQuestionOptions();
  2964. });
  2965. // 设置音频源
  2966. audioContext.src = this.aiVoiceUrl;
  2967. // 添加超时处理,如果5秒内没有开始播放,则认为出错
  2968. const playTimeout = setTimeout(() => {
  2969. if (this.isPlayingAiVoice) {
  2970. console.warn('小程序音频播放超时,尝试备选方法');
  2971. this.tryMiniProgramFallbackAudioPlay();
  2972. }
  2973. }, 5000);
  2974. // 延迟一小段时间再播放,确保src已经设置完成
  2975. setTimeout(() => {
  2976. audioContext.play();
  2977. // 播放开始后清除超时
  2978. clearTimeout(playTimeout);
  2979. }, 300);
  2980. } catch (e) {
  2981. console.error('小程序播放AI语音时发生错误:', e);
  2982. // 标记播放结束
  2983. this.isPlayingAiVoice = false;
  2984. // 显示错误提示
  2985. uni.showToast({
  2986. title: '音频播放失败,请查看文字回复',
  2987. icon: 'none',
  2988. duration: 2000
  2989. });
  2990. // 使用文本显示方式作为备选方案
  2991. this.handleAudioPlaybackFailure();
  2992. }
  2993. },
  2994. // 添加新方法:小程序环境的备选音频播放方法
  2995. tryMiniProgramFallbackAudioPlay() {
  2996. console.log('使用小程序备选方法播放音频:', this.aiVoiceUrl);
  2997. // 先下载音频文件到本地
  2998. uni.downloadFile({
  2999. url: this.aiVoiceUrl,
  3000. success: (res) => {
  3001. if (res.statusCode === 200) {
  3002. console.log('小程序音频文件下载成功:', res.tempFilePath);
  3003. // 使用新的音频上下文播放本地文件
  3004. const newAudioContext = wx.createInnerAudioContext();
  3005. newAudioContext.autoplay = true;
  3006. newAudioContext.src = res.tempFilePath;
  3007. // 设置事件监听
  3008. newAudioContext.onPlay(() => {
  3009. console.log('小程序备选方法:音频开始播放');
  3010. });
  3011. newAudioContext.onEnded(() => {
  3012. console.log('小程序备选方法:音频播放结束');
  3013. this.isPlayingAiVoice = false;
  3014. this.currentSubtitle = '';
  3015. newAudioContext.destroy();
  3016. this.showContinueQuestionOptions();
  3017. this.checkPendingNavigation();
  3018. });
  3019. newAudioContext.onError((err) => {
  3020. console.error('小程序备选方法:音频播放错误:', err);
  3021. this.isPlayingAiVoice = false;
  3022. this.currentSubtitle = '';
  3023. newAudioContext.destroy();
  3024. // 尝试使用系统播放器作为最后的备选方案
  3025. this.trySystemAudioPlayer();
  3026. });
  3027. } else {
  3028. console.error('小程序音频文件下载失败:', res);
  3029. this.handleAudioPlaybackFailure();
  3030. }
  3031. },
  3032. fail: (err) => {
  3033. console.error('小程序音频文件下载请求失败:', err);
  3034. this.handleAudioPlaybackFailure();
  3035. }
  3036. });
  3037. },
  3038. // 添加新方法:尝试使用系统播放器
  3039. trySystemAudioPlayer() {
  3040. console.log('尝试使用系统播放器播放音频');
  3041. // 检查平台
  3042. const systemInfo = uni.getSystemInfoSync();
  3043. if (systemInfo.platform === 'android' || systemInfo.platform === 'ios') {
  3044. // 在移动端尝试使用系统播放器
  3045. uni.showToast({
  3046. title: '正在使用系统播放器',
  3047. icon: 'none',
  3048. duration: 2000
  3049. });
  3050. // 使用uni.playVoice API (如果可用)
  3051. if (typeof uni.playVoice === 'function') {
  3052. uni.playVoice({
  3053. filePath: this.aiVoiceUrl,
  3054. success: () => {
  3055. console.log('系统播放器播放成功');
  3056. setTimeout(() => {
  3057. this.isPlayingAiVoice = false;
  3058. this.currentSubtitle = '';
  3059. this.showContinueQuestionOptions();
  3060. }, 5000); // 假设音频长度约为5秒
  3061. },
  3062. fail: (err) => {
  3063. console.error('系统播放器播放失败:', err);
  3064. this.handleAudioPlaybackFailure();
  3065. }
  3066. });
  3067. } else {
  3068. // 如果uni.playVoice不可用,尝试使用uni.openDocument
  3069. uni.openDocument({
  3070. filePath: this.aiVoiceUrl,
  3071. fileType: 'audio',
  3072. success: () => {
  3073. console.log('使用系统应用打开音频文件');
  3074. // 由于控制权交给了系统,我们需要手动处理后续流程
  3075. setTimeout(() => {
  3076. this.isPlayingAiVoice = false;
  3077. this.currentSubtitle = '';
  3078. this.showContinueQuestionOptions();
  3079. }, 8000); // 给用户足够的时间听完音频
  3080. },
  3081. fail: (err) => {
  3082. console.error('无法使用系统应用打开音频:', err);
  3083. this.handleAudioPlaybackFailure();
  3084. }
  3085. });
  3086. }
  3087. } else {
  3088. // 在其他平台上直接使用文本显示
  3089. this.handleAudioPlaybackFailure();
  3090. }
  3091. },
  3092. // 修改 showContinueQuestionOptions 方法,确保状态正确设置
  3093. showContinueQuestionOptions() {
  3094. // 如果正在播放AI语音,不执行此方法
  3095. if (this.isPlayingAiVoice) {
  3096. console.log('AI语音正在播放,暂不显示继续提问选项');
  3097. return;
  3098. }
  3099. // 增加提问轮次计数
  3100. this.questionRound++;
  3101. // 清空字幕
  3102. this.currentSubtitle = '';
  3103. // 如果未达到最大提问轮次,显示继续提问按钮
  3104. if (this.questionRound < this.maxQuestionRounds) {
  3105. this.showContinueQuestionButton = true;
  3106. this.showEndInterviewButton = true;
  3107. // 显示提示
  3108. uni.showToast({
  3109. title: `第${this.questionRound}轮提问完成`,
  3110. icon: 'none',
  3111. duration: 2000
  3112. });
  3113. } else {
  3114. // 如果已达到最大提问轮次,自动执行跳转逻辑
  3115. this.showContinueQuestionButton = false;
  3116. this.showEndInterviewButton = false;
  3117. // 检查是否正在播放AI语音或上传视频
  3118. if (this.isPlayingAiVoice || this.isUploading) {
  3119. console.log('等待AI回复或上传完成后再跳转');
  3120. // 设置一个标志,表示需要在AI回复和上传完成后跳转
  3121. this.pendingAutoNavigation = true;
  3122. } else {
  3123. // 如果没有正在进行的AI回复或上传,延迟3秒后自动跳转
  3124. setTimeout(() => {
  3125. this.navigateToNextPage();
  3126. }, 3000);
  3127. }
  3128. }
  3129. // 确保所有录制状态被重置
  3130. this.isRecording = false;
  3131. if (this.recordingTimer) {
  3132. clearInterval(this.recordingTimer);
  3133. this.recordingTimer = null;
  3134. }
  3135. // 重置录制相关数据
  3136. this.recordedChunks = [];
  3137. this.recordingTimerCount = 0;
  3138. this.remainingTime = this.maxRecordingTime;
  3139. },
  3140. // 修复 handleContinueQuestionClick 方法,确保状态正确重置
  3141. handleContinueQuestionClick() {
  3142. // 如果AI语音仍在播放,不允许继续提问
  3143. if (this.isPlayingAiVoice) {
  3144. uni.showToast({
  3145. title: '请等待面试官回复完成',
  3146. icon: 'none',
  3147. duration: 2000
  3148. });
  3149. return;
  3150. }
  3151. // 隐藏继续提问和结束面试按钮
  3152. this.showContinueQuestionButton = false;
  3153. this.showEndInterviewButton = false;
  3154. // 重置录制相关状态
  3155. this.isRecording = false;
  3156. this.recordingTimerCount = 0;
  3157. this.remainingTime = this.maxRecordingTime;
  3158. this.recordingTimeDisplay = '00:00 / ' + this.formatTime(this.maxRecordingTime);
  3159. // 清空已录制的数据
  3160. this.recordedChunks = [];
  3161. // 如果有正在进行的录制,先停止
  3162. if (this.mediaRecorder && this.mediaRecorder.state === 'recording') {
  3163. this.mediaRecorder.stop();
  3164. }
  3165. if (this.recorder) {
  3166. try {
  3167. this.cameraContext.stopRecord();
  3168. } catch (e) {
  3169. console.error('停止录制失败:', e);
  3170. }
  3171. this.recorder = null;
  3172. }
  3173. // 延迟一小段时间再开始新的录制,确保之前的录制已完全停止
  3174. setTimeout(() => {
  3175. // 开始新一轮录制
  3176. this.startRecordingAnswer();
  3177. }, 500);
  3178. },
  3179. // 添加新方法:处理结束面试按钮点击
  3180. handleEndInterviewClick() {
  3181. // 隐藏继续提问和结束面试按钮
  3182. this.showContinueQuestionButton = false;
  3183. this.showEndInterviewButton = false;
  3184. // 显示结束提示
  3185. /* uni.showToast({
  3186. title: '面试已结束',
  3187. icon: 'success',
  3188. duration: 1500
  3189. }); */
  3190. // 执行现有的跳转逻辑
  3191. this.navigateToNextPage();
  3192. },
  3193. // 添加新方法:处理录制错误
  3194. handleRecordingError(error) {
  3195. console.error('录制错误:', error);
  3196. // 显示错误提示
  3197. uni.showToast({
  3198. title: '录制失败,请重试',
  3199. icon: 'none',
  3200. duration: 2000
  3201. });
  3202. // 重置录制状态
  3203. this.isRecording = false;
  3204. this.showStopRecordingButton = false;
  3205. // 显示重试按钮
  3206. this.showStartRecordingButton = true;
  3207. },
  3208. // 添加新方法:处理上传错误
  3209. handleUploadError(error) {
  3210. console.error('上传错误:', error);
  3211. // 显示错误提示
  3212. uni.showToast({
  3213. title: '上传失败,请重试',
  3214. icon: 'none',
  3215. duration: 2000
  3216. });
  3217. // 显示重试按钮
  3218. this.showRetryButton = true;
  3219. // 隐藏上传状态
  3220. this.showUploadStatus = false;
  3221. this.isUploading = false;
  3222. },
  3223. // 添加新方法:检查是否有待处理的自动跳转
  3224. checkPendingNavigation() {
  3225. if (this.pendingAutoNavigation && !this.isPlayingAiVoice && !this.isUploading) {
  3226. console.log('所有处理已完成,执行自动跳转');
  3227. // 重置标志
  3228. this.pendingAutoNavigation = false;
  3229. // 延迟2秒后跳转,给用户一点时间看到最终状态
  3230. setTimeout(() => {
  3231. this.navigateToNextPage();
  3232. }, 2000);
  3233. }
  3234. },
  3235. // 添加新方法:显示文本回复
  3236. displayTextResponse() {
  3237. // 标记为正在"播放",防止用户操作
  3238. this.isPlayingAiVoice = true;
  3239. // 显示AI回复文本
  3240. this.currentSubtitle = this.aiText;
  3241. // 显示提示
  3242. uni.showToast({
  3243. title: '显示面试官文字回复',
  3244. icon: 'none',
  3245. duration: 2000
  3246. });
  3247. // 根据文本长度计算显示时间(每个字符约需要0.1秒阅读时间,最少5秒,最多15秒)
  3248. const textLength = this.aiText.length;
  3249. const displayTime = Math.min(Math.max(textLength * 100, 5000), 15000);
  3250. // 设置定时器,显示一段时间后清除
  3251. setTimeout(() => {
  3252. // 标记播放结束
  3253. this.isPlayingAiVoice = false;
  3254. // 清空字幕
  3255. this.currentSubtitle = '';
  3256. // 显示继续提问选项
  3257. this.showContinueQuestionOptions();
  3258. // 检查是否需要自动跳转
  3259. this.checkPendingNavigation();
  3260. }, displayTime);
  3261. },
  3262. // 添加新方法:检查不支持的音频格式
  3263. checkUnsupportedAudioFormat(url) {
  3264. if (!url) return false;
  3265. // 获取URL的文件扩展名
  3266. const extension = url.split('.').pop().toLowerCase();
  3267. // 检查平台
  3268. const systemInfo = uni.getSystemInfoSync();
  3269. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
  3270. if (isMiniProgram) {
  3271. // 微信小程序支持的音频格式有限,主要是mp3和wav
  3272. // 检查是否是不支持的格式
  3273. const unsupportedFormats = ['ogg', 'flac', 'aac', 'm4a', 'opus'];
  3274. return unsupportedFormats.includes(extension);
  3275. }
  3276. return false;
  3277. }
  3278. }
  3279. }
  3280. </script>
  3281. <style scoped>
  3282. .identity-verify-container {
  3283. padding: 0;
  3284. max-width: 100%;
  3285. margin: 0 auto;
  3286. height: 100vh;
  3287. display: flex;
  3288. flex-direction: column;
  3289. background-color: #f5f5f5;
  3290. }
  3291. .digital-human-container {
  3292. position: relative;
  3293. width: 100%;
  3294. height: 100vh;
  3295. overflow: hidden;
  3296. background-color: #f0f0f0;
  3297. }
  3298. .digital-human-video {
  3299. width: 100%;
  3300. height: 100%;
  3301. display: flex;
  3302. justify-content: center;
  3303. align-items: center;
  3304. }
  3305. /* 用户摄像头容器样式 */
  3306. .user-camera-container {
  3307. position: absolute;
  3308. top: 50px;
  3309. right: 5px;
  3310. width: 110px; /* 稍微增加宽度 */
  3311. height: 160px; /* 稍微增加高度 */
  3312. border-radius: 4px; /* 减小圆角 */
  3313. overflow: hidden;
  3314. box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
  3315. z-index: 20;
  3316. }
  3317. /* 用户摄像头视频样式 */
  3318. .user-camera-video {
  3319. width: 100%;
  3320. height: 100%;
  3321. object-fit: cover;
  3322. background-color: #333;
  3323. }
  3324. .video-player {
  3325. width: 100%;
  3326. height: 100%;
  3327. object-fit: cover;
  3328. outline: none; /* 移除视频获得焦点时的轮廓 */
  3329. -webkit-tap-highlight-color: transparent; /* 移除移动设备上的点击高亮 */
  3330. }
  3331. /* 隐藏视频控制条 */
  3332. video::-webkit-media-controls {
  3333. display: none !important;
  3334. }
  3335. video::-webkit-media-controls-enclosure {
  3336. display: none !important;
  3337. }
  3338. video::-webkit-media-controls-panel {
  3339. display: none !important;
  3340. }
  3341. video::-webkit-media-controls-play-button {
  3342. display: none !important;
  3343. }
  3344. video::-webkit-media-controls-timeline {
  3345. display: none !important;
  3346. }
  3347. video::-webkit-media-controls-current-time-display {
  3348. display: none !important;
  3349. }
  3350. video::-webkit-media-controls-time-remaining-display {
  3351. display: none !important;
  3352. }
  3353. video::-webkit-media-controls-mute-button {
  3354. display: none !important;
  3355. }
  3356. video::-webkit-media-controls-volume-slider {
  3357. display: none !important;
  3358. }
  3359. video::-webkit-media-controls-fullscreen-button {
  3360. display: none !important;
  3361. }
  3362. /* 修改字幕覆盖层样式,使其与图片中的样式一致 */
  3363. .subtitle-overlay {
  3364. position: absolute;
  3365. bottom: 180px; /* 调整位置,使其更靠近底部 */
  3366. left: 5%; /* 从左侧留出5%的空间 */
  3367. width: 80%; /* 宽度设为90%,两侧各留5%实现居中 */
  3368. padding: 15px 20px; /* 增加左右内边距 */
  3369. border-radius: 15px;
  3370. background-color: rgba(255, 255, 255, 0.9); /* 白色半透明背景 */
  3371. color: #333; /* 文字颜色为深色 */
  3372. text-align: left; /* 文字左对齐 */
  3373. font-size: 16px;
  3374. line-height: 1.5;
  3375. z-index: 10;
  3376. margin: 0 auto; /* 添加自动边距实现居中 */
  3377. box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 添加轻微阴影 */
  3378. }
  3379. /* 添加计时器样式,右侧显示橙色圆点和时间 */
  3380. .subtitle-overlay::after {
  3381. content: attr(data-time);
  3382. position: absolute;
  3383. right: 20px;
  3384. bottom: 15px;
  3385. color: #333;
  3386. font-size: 14px;
  3387. }
  3388. .control-panel {
  3389. padding: 15px;
  3390. display: flex;
  3391. justify-content: center;
  3392. }
  3393. .control-button {
  3394. padding: 10px 20px;
  3395. background-color: #4CAF50;
  3396. color: white;
  3397. border: none;
  3398. border-radius: 4px;
  3399. cursor: pointer;
  3400. }
  3401. .loading {
  3402. text-align: center;
  3403. margin: 20px 0;
  3404. font-size: 16px;
  3405. }
  3406. .response-container {
  3407. margin-top: 20px;
  3408. padding: 0 20px;
  3409. display: none; /* 默认隐藏调试信息 */
  3410. }
  3411. /* 当showDebugInfo为true时显示 */
  3412. .showDebugInfo .response-container {
  3413. display: block;
  3414. }
  3415. .response-item {
  3416. padding: 10px;
  3417. border: 1px solid #eee;
  3418. border-radius: 4px;
  3419. margin-bottom: 10px;
  3420. background-color: #f9f9f9;
  3421. }
  3422. .response-content {
  3423. display: flex;
  3424. flex-direction: column;
  3425. }
  3426. .answer-button-container {
  3427. position: absolute;
  3428. bottom: 50px; /* 将按钮放在底部而不是75%的位置 */
  3429. left: 50%;
  3430. transform: translateX(-50%); /* 只在X轴上平移,保持水平居中 */
  3431. z-index: 20;
  3432. }
  3433. /* 修改回答按钮样式 */
  3434. .answer-button {
  3435. width: 120px;
  3436. height: 40px; /* 改为矩形按钮 */
  3437. border-radius: 20px; /* 圆角矩形 */
  3438. background-color: #ffffff; /* 白色背景 */
  3439. color: #333; /* 深色文字 */
  3440. font-size: 16px;
  3441. border: none;
  3442. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  3443. display: flex;
  3444. justify-content: center;
  3445. align-items: center;
  3446. cursor: pointer;
  3447. animation: none; /* 移除脉动动画 */
  3448. }
  3449. .stop-recording-button-container {
  3450. position: absolute;
  3451. bottom: 50px; /* 统一与其他按钮的位置 */
  3452. left: 50%;
  3453. transform: translateX(-50%);
  3454. z-index: 20;
  3455. }
  3456. .stop-recording-button {
  3457. width: 120px;
  3458. height: 40px; /* 改为矩形按钮 */
  3459. border-radius: 20px; /* 圆角矩形 */
  3460. background-color: #0039b3; /* 白色背景 */
  3461. color: #fff; /* 深色文字 */
  3462. font-size: 16px;
  3463. border: none;
  3464. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  3465. display: flex;
  3466. justify-content: center;
  3467. align-items: center;
  3468. cursor: pointer;
  3469. animation: none; /* 移除脉动动画 */
  3470. }
  3471. .recording-indicator {
  3472. position: absolute;
  3473. top: 20px;
  3474. left: 20px;
  3475. display: flex;
  3476. align-items: center;
  3477. background-color: rgba(255, 255, 255, 0.9); /* 改为白色半透明背景 */
  3478. padding: 5px 10px;
  3479. border-radius: 15px;
  3480. z-index: 20;
  3481. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  3482. }
  3483. .recording-dot {
  3484. width: 12px;
  3485. height: 12px;
  3486. background-color: #ff6b00; /* 改为橙色,与图片中的颜色一致 */
  3487. border-radius: 50%;
  3488. margin-right: 8px;
  3489. animation: blink 1s infinite;
  3490. }
  3491. .recording-text {
  3492. color: #333; /* 改为深色文字 */
  3493. font-size: 14px;
  3494. }
  3495. .timer-text {
  3496. color: #333; /* 改为深色文字 */
  3497. font-size: 14px;
  3498. margin-left: 8px;
  3499. }
  3500. .start-recording-button-container {
  3501. position: absolute;
  3502. bottom: 50px; /* 统一与其他按钮的位置 */
  3503. left: 50%;
  3504. transform: translateX(-50%);
  3505. z-index: 101;
  3506. }
  3507. .start-recording-button {
  3508. width: 120px;
  3509. height: 40px; /* 改为矩形按钮 */
  3510. border-radius: 20px; /* 圆角矩形 */
  3511. background-color: #ffffff; /* 白色背景 */
  3512. color: #333; /* 深色文字 */
  3513. font-size: 16px;
  3514. border: none;
  3515. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  3516. display: flex;
  3517. justify-content: center;
  3518. align-items: center;
  3519. cursor: pointer;
  3520. animation: none; /* 移除脉动动画 */
  3521. }
  3522. .retry-button-container {
  3523. position: absolute;
  3524. bottom: 30px; /* 统一与其他按钮的位置 */
  3525. left: 50%;
  3526. transform: translateX(-50%);
  3527. z-index: 20;
  3528. }
  3529. .retry-button {
  3530. padding: 10px 20px;
  3531. background-color: #ffffff; /* 白色背景 */
  3532. color: #333; /* 深色文字 */
  3533. font-size: 16px;
  3534. border: none;
  3535. border-radius: 20px; /* 圆角矩形 */
  3536. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  3537. cursor: pointer;
  3538. }
  3539. .retry-button:hover {
  3540. background-color: #2980b9;
  3541. }
  3542. /* 录制时长显示 */
  3543. .recording-timer {
  3544. position: absolute;
  3545. top: 20px;
  3546. left: 130px; /* 放在录制指示器旁边 */
  3547. background-color: rgba(0, 0, 0, 0.6);
  3548. padding: 5px 10px;
  3549. border-radius: 15px;
  3550. z-index: 20;
  3551. display: flex;
  3552. flex-direction: column;
  3553. }
  3554. .timer-text {
  3555. color: #000;
  3556. font-size: 14px;
  3557. font-family: monospace; /* 使用等宽字体,使时间显示更稳定 */
  3558. }
  3559. .remaining-time {
  3560. color: white;
  3561. font-size: 12px;
  3562. margin-top: 2px;
  3563. }
  3564. .remaining-time.warning {
  3565. color: #ff6b6b; /* 剩余时间少时显示红色 */
  3566. animation: blink 1s infinite; /* 使用闪烁动画提醒用户 */
  3567. }
  3568. /* 添加上传状态指示器 */
  3569. .upload-status-indicator {
  3570. position: absolute;
  3571. top: 20px;
  3572. left: 130px; /* 放在录制指示器旁边 */
  3573. background-color: rgba(0, 0, 0, 0.6);
  3574. padding: 5px 10px;
  3575. border-radius: 15px;
  3576. z-index: 20;
  3577. }
  3578. .upload-status-content {
  3579. display: flex;
  3580. align-items: center;
  3581. }
  3582. .upload-status-icon {
  3583. width: 12px;
  3584. height: 12px;
  3585. border-radius: 50%;
  3586. margin-right: 8px;
  3587. }
  3588. .upload-status-text {
  3589. color: white;
  3590. font-size: 14px;
  3591. }
  3592. .uploading {
  3593. background-color: #e74c3c;
  3594. }
  3595. /* 添加倒计时蒙层样式 */
  3596. .countdown-overlay {
  3597. position: fixed;
  3598. top: 0;
  3599. left: 0;
  3600. width: 100%;
  3601. height: 100%;
  3602. background-color: rgba(0, 0, 0, 0.7);
  3603. z-index: 100;
  3604. display: flex;
  3605. justify-content: center;
  3606. align-items: center;
  3607. }
  3608. .countdown-content {
  3609. display: flex;
  3610. flex-direction: column;
  3611. align-items: center;
  3612. }
  3613. .countdown-number {
  3614. font-size: 80px;
  3615. color: #ffffff;
  3616. font-weight: bold;
  3617. margin-bottom: 20px;
  3618. }
  3619. .countdown-text {
  3620. font-size: 24px;
  3621. color: #ffffff;
  3622. }
  3623. /* 添加GIF播放器样式 */
  3624. .gif-player {
  3625. width: 100%;
  3626. height: 100%;
  3627. object-fit: cover;
  3628. position: absolute;
  3629. top: 0;
  3630. left: 0;
  3631. z-index: 5; /* 确保GIF在视频上方但在字幕和按钮下方 */
  3632. }
  3633. /* AI语音播放蒙层样式 */
  3634. .ai-voice-overlay {
  3635. position: fixed;
  3636. top: 0;
  3637. left: 0;
  3638. width: 100%;
  3639. height: 100%;
  3640. background-color: rgba(0, 0, 0, 0.8); /* 0.8的透明度 */
  3641. z-index: 99; /* 确保在其他元素之上,但在倒计时蒙层之下 */
  3642. display: flex;
  3643. justify-content: center;
  3644. align-items: center;
  3645. }
  3646. .ai-voice-content {
  3647. display: flex;
  3648. flex-direction: column;
  3649. align-items: center;
  3650. color: #ffffff;
  3651. }
  3652. .ai-voice-icon {
  3653. width: 40px;
  3654. height: 40px;
  3655. border-radius: 50%;
  3656. background-color: #ffffff;
  3657. margin-bottom: 15px;
  3658. position: relative;
  3659. animation: pulse 1.5s infinite;
  3660. }
  3661. .ai-voice-icon::before {
  3662. content: '';
  3663. position: absolute;
  3664. top: 50%;
  3665. left: 50%;
  3666. transform: translate(-50%, -50%);
  3667. width: 20px;
  3668. height: 20px;
  3669. 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>');
  3670. background-repeat: no-repeat;
  3671. background-position: center;
  3672. }
  3673. .ai-voice-text {
  3674. font-size: 18px;
  3675. color: #ffffff;
  3676. }
  3677. @keyframes pulse {
  3678. 0% {
  3679. transform: scale(1);
  3680. opacity: 1;
  3681. }
  3682. 50% {
  3683. transform: scale(1.1);
  3684. opacity: 0.8;
  3685. }
  3686. 100% {
  3687. transform: scale(1);
  3688. opacity: 1;
  3689. }
  3690. }
  3691. /* 继续提问按钮样式 */
  3692. .continue-question-container {
  3693. position: absolute;
  3694. bottom: 100px; /* 位置高于结束面试按钮 */
  3695. left: 50%;
  3696. transform: translateX(-50%);
  3697. z-index: 20;
  3698. }
  3699. .continue-question-button {
  3700. width: 120px;
  3701. height: 40px;
  3702. border-radius: 20px;
  3703. background-color: #ffffff;
  3704. color: #333;
  3705. font-size: 16px;
  3706. border: none;
  3707. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  3708. display: flex;
  3709. justify-content: center;
  3710. align-items: center;
  3711. cursor: pointer;
  3712. }
  3713. /* 结束面试按钮样式 */
  3714. .end-interview-container {
  3715. position: absolute;
  3716. bottom: 50px;
  3717. left: 50%;
  3718. transform: translateX(-50%);
  3719. z-index: 20;
  3720. }
  3721. .end-interview-button {
  3722. width: 120px;
  3723. height: 40px;
  3724. border-radius: 20px;
  3725. background-color: #e74c3c; /* 红色背景 */
  3726. color: #ffffff; /* 白色文字 */
  3727. font-size: 16px;
  3728. border: none;
  3729. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  3730. display: flex;
  3731. justify-content: center;
  3732. align-items: center;
  3733. cursor: pointer;
  3734. }
  3735. /* 提问轮次指示器样式 */
  3736. .question-round-indicator {
  3737. position: absolute;
  3738. top: 20px;
  3739. right: 120px; /* 位置在用户摄像头左侧 */
  3740. background-color: rgba(255, 255, 255, 0.9);
  3741. padding: 5px 10px;
  3742. border-radius: 15px;
  3743. z-index: 20;
  3744. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  3745. }
  3746. .round-text {
  3747. color: #333;
  3748. font-size: 14px;
  3749. }
  3750. </style>