identity-verify.vue 112 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566
  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. <!-- 添加重新录制按钮 -->
  149. <div class="rerecord-button-container" v-if="showRerecordButton">
  150. <button class="rerecord-button" @click="handleRerecordButtonClick">
  151. 重新作答
  152. </button>
  153. </div>
  154. </div>
  155. </template>
  156. <script>
  157. import { apiBaseUrl } from '@/common/config.js';
  158. export default {
  159. name: 'IdentityVerify',
  160. data() {
  161. return {
  162. loading: false,
  163. responses: [],
  164. processedResponses: [],
  165. assistantResponse: '',
  166. audioTranscript: '',
  167. videoPlaying: false,
  168. showDebugInfo: false, // 设置为true可以显示调试信息
  169. videoUrl: '', // 修改为空字符串,将通过API获取
  170. showReplayButton: false,
  171. cameraStream: null, // 存储摄像头流
  172. cameraError: null, // 存储摄像头错误信息
  173. useMiniProgramCameraComponent: false, // 添加小程序相机组件标志
  174. cameraContext: null, // 添加相机上下文
  175. currentSubtitle: '',
  176. subtitles: [], // 修改为空数组,将通过API获取
  177. // 移除硬编码的字幕数组
  178. // secondVideoSubtitles: [...],
  179. // thirdVideoSubtitles: [...],
  180. // 等等...
  181. showAnswerButton: false, // 控制答题按钮显示
  182. currentVideoIndex: 0, // 当前播放的视频索引
  183. videoList: [], // 修改为空数组,将通过API获取
  184. // 其他属性保持不变...
  185. questions: [], // 添加新属性存储API返回的问题数据
  186. introVideoUrl: 'http://121.36.251.245:9000/minlong/tenant_1/general_uploads/880a117c8fcc4196b0d8c0750608d373.mp4', // 保留介绍视频
  187. isRecording: false,
  188. recordingTimer: null,
  189. showStopRecordingButton: false,
  190. mediaRecorder: null,
  191. recordedChunks: [],
  192. recorder: null,
  193. lastUploadedVideoUrl: '',
  194. showStartRecordingButton: false,
  195. showRetryButton: false, // 控制重试按钮显示
  196. lastVideoToRetry: null, // 存储上次失败的视频URL,用于重试
  197. recordingStartTime: null, // 录制开始时间
  198. recordingTimerCount: 0, // 录制计时器计数
  199. recordingTimeDisplay: '00:00', // 格式化的录制时间显示
  200. // 添加上传队列相关数据
  201. uploadQueue: [], // 存储待上传的视频
  202. isUploading: false, // 标记是否正在上传
  203. uploadProgress: {}, // 存储每个视频的上传进度
  204. uploadStatus: {}, // 存储每个视频的上传状态
  205. showUploadStatus: false, // 是否显示上传状态指示器
  206. uploadStatusText: '', // 上传状态文本
  207. mediaRecorderTimeout: null, // 用于存储MediaRecorder的超时机制
  208. maxRecordingTime: 300, // 最大录制时间(秒)- 从60秒改为300秒(5分钟)
  209. remainingTime: 300, // 剩余录制时间(秒)- 从60秒改为300秒
  210. countdownValue: 10, // 倒计时数值
  211. showCountdown: false, // 是否显示倒计时蒙层
  212. countdownTimer: null,
  213. showGif: false, // 控制是否显示GIF
  214. gifUrl: '', // GIF图片的URL
  215. globalSocketTask: null, // 添加全局 WebSocket 连接对象
  216. lowScoreVideoUrl: 'https://data.qicai321.com/minlong/latentsync/0530e7f5-1957-422d-8f34-ba4a92608081_result.mp4', // 低分提示视频URL
  217. showRerecordButton: false, // 控制重新录制按钮显示
  218. isPlayingLowScoreVideo: false, // 标记是否正在播放低分提示视频
  219. lowScoreVideoSubtitles: [
  220. {
  221. startTime: 0,
  222. endTime: 10, // 假设视频长度为10秒,可根据实际情况调整
  223. text: '我未听清楚您在说什么,请您再说一遍!'
  224. }
  225. ], // 用于存储低分提示视频的字幕
  226. retryCount: 0, // 添加重试次数计数器
  227. maxRetryAttempts: 2, // 最大重试次数限制
  228. }
  229. },
  230. mounted() {
  231. /* this.fetchData() */
  232. this.fetchQuestions(); // 添加获取问题数据的方法调用
  233. this.checkAudioPermission();
  234. this.initCamera();
  235. this.checkIOSCameraRecordPermission();
  236. // 添加防御性检查,避免渲染错误
  237. this.checkAndFixRenderingIssues();
  238. // 添加音频测试
  239. setTimeout(() => {
  240. if (this.cameraStream && !this.useMiniProgramCameraComponent) {
  241. this.testAudioInput();
  242. }
  243. }, 3000);
  244. // 初始化 WebSocket 连接
  245. this.initWebSocketConnection();
  246. uni.setKeepScreenOn({
  247. keepScreenOn: true
  248. });
  249. },
  250. beforeDestroy() {
  251. // 组件销毁前停止摄像头
  252. this.stopUserCamera();
  253. // 清除倒计时定时器
  254. this.clearCountdown();
  255. // 关闭 WebSocket 连接
  256. this.closeWebSocketConnection();
  257. },
  258. methods: {
  259. // 初始化相机
  260. async initCamera() {
  261. // 检查平台
  262. const systemInfo = uni.getSystemInfoSync();
  263. // 判断是否在小程序环境中
  264. const isMiniProgram = systemInfo.uniPlatform === 'mp-weixin' ||
  265. systemInfo.uniPlatform === 'mp-alipay' ||
  266. systemInfo.uniPlatform === 'mp-baidu';
  267. if (isMiniProgram) {
  268. // 小程序环境使用小程序的相机API
  269. this.useMiniProgramCameraComponent = true;
  270. // 创建相机上下文
  271. this.cameraContext = uni.createCameraContext();
  272. // 确保已获取录音和相机权限
  273. uni.getSetting({
  274. success: (res) => {
  275. // 检查录音权限
  276. if (!res.authSetting['scope.record']) {
  277. uni.authorize({
  278. scope: 'scope.record',
  279. success: () => {
  280. console.log('录音权限已获取');
  281. },
  282. fail: (err) => {
  283. console.error('录音权限获取失败:', err);
  284. this.showPermissionDialog('录音');
  285. }
  286. });
  287. }
  288. // 检查相机权限
  289. if (!res.authSetting['scope.camera']) {
  290. uni.authorize({
  291. scope: 'scope.camera',
  292. success: () => {
  293. console.log('相机权限已获取');
  294. },
  295. fail: (err) => {
  296. console.error('相机权限获取失败:', err);
  297. this.showPermissionDialog('相机');
  298. }
  299. });
  300. }
  301. // 在iOS上,可能需要额外的权限检查
  302. const systemInfo = uni.getSystemInfoSync();
  303. if (systemInfo.platform === 'ios') {
  304. // 在iOS上,不要使用无效的权限范围
  305. // 移除以下代码块
  306. /*
  307. if (!res.authSetting['scope.camera.record']) {
  308. uni.authorize({
  309. scope: 'scope.camera.record',
  310. success: () => {
  311. console.log('相机录制权限已获取');
  312. },
  313. fail: (err) => {
  314. console.error('相机录制权限获取失败:', err);
  315. this.showPermissionDialog('相机录制');
  316. }
  317. });
  318. }
  319. */
  320. // 确保同时获取了相机和录音权限
  321. if (!res.authSetting['scope.camera'] || !res.authSetting['scope.record']) {
  322. console.log('iOS需要同时获取相机和录音权限');
  323. }
  324. }
  325. }
  326. });
  327. } else {
  328. // H5/App环境使用浏览器的API
  329. try {
  330. // 请求摄像头和麦克风权限并获取媒体流,添加更多约束
  331. const constraints = {
  332. audio: {
  333. echoCancellation: true,
  334. noiseSuppression: true,
  335. autoGainControl: true
  336. },
  337. video: {
  338. width: { ideal: 640, max: 1280 }, // 控制视频宽度
  339. height: { ideal: 480, max: 720 }, // 控制视频高度
  340. frameRate: { ideal: 15, max: 24 }, // 控制帧率
  341. facingMode: 'user'
  342. }
  343. };
  344. const stream = await navigator.mediaDevices.getUserMedia(constraints);
  345. // 保存流以便后续使用
  346. this.cameraStream = stream;
  347. // 检查音频轨道
  348. const audioTracks = stream.getAudioTracks();
  349. console.log('音频轨道数量:', audioTracks.length);
  350. if (audioTracks.length > 0) {
  351. console.log('音频轨道已获取:', audioTracks[0].label);
  352. // 确保音频轨道已启用
  353. audioTracks[0].enabled = true;
  354. } else {
  355. console.warn('未检测到音频轨道,尝试单独获取音频');
  356. this.tryGetAudioOnly();
  357. }
  358. // 将流设置到视频元素
  359. const videoElement = this.$refs.userCameraVideo;
  360. if (videoElement) {
  361. videoElement.srcObject = stream;
  362. videoElement.muted = true; // 避免回声,但仍然录制声音
  363. }
  364. } catch (error) {
  365. console.error('获取摄像头失败:', error);
  366. this.cameraError = error.message || '无法访问摄像头';
  367. // 显示错误提示
  368. uni.showToast({
  369. title: '无法访问摄像头,请检查权限设置',
  370. icon: 'none'
  371. });
  372. }
  373. }
  374. },
  375. // 停止用户摄像头
  376. stopUserCamera() {
  377. if (this.cameraStream) {
  378. // 停止所有轨道
  379. this.cameraStream.getTracks().forEach(track => {
  380. track.stop();
  381. });
  382. this.cameraStream = null;
  383. }
  384. },
  385. async fetchData() {
  386. this.loading = true
  387. this.assistantResponse = ''
  388. this.audioTranscript = ''
  389. this.processedResponses = []
  390. try {
  391. // 使用uni.request代替fetch
  392. const requestTask = uni.request({
  393. url: 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions',
  394. method: 'POST',
  395. header: {
  396. 'Content-Type': 'application/json',
  397. 'Authorization': 'Bearer sk-9e1ec73a7d97493b8613c63f06b6110c'
  398. },
  399. data: {
  400. "model": "qwen-omni-turbo",
  401. "messages": [
  402. {
  403. "role": "user",
  404. "content": [
  405. {
  406. "type": "input_audio",
  407. "input_audio": {
  408. "data": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250211/tixcef/cherry.wav",
  409. "format": "wav"
  410. }
  411. },
  412. {
  413. "type": "text",
  414. "text": "这段音频在说什么"
  415. }
  416. ]
  417. }
  418. ],
  419. "stream":true,
  420. "stream_options":{
  421. "include_usage":true
  422. },
  423. "modalities":["text","audio"],
  424. "audio":{"voice":"Cherry","format":"wav"}
  425. },
  426. success: (res) => {
  427. console.log('请求成功,响应数据:', res.data);
  428. // 检查响应数据是否包含多个JSON对象
  429. if (typeof res.data === 'string' && res.data.includes('data: {')) {
  430. // 处理包含多个JSON对象的情况
  431. const chunks = res.data.split('data: ').filter(chunk => chunk.trim() !== '');
  432. chunks.forEach(chunk => {
  433. this.handleStreamResponse(chunk);
  434. });
  435. } else {
  436. // 处理单个响应对象的情况
  437. this.handleStreamResponse(res.data);
  438. }
  439. // 模拟获取到数字人视频并播放
  440. this.playDigitalHumanVideo();
  441. },
  442. fail: (err) => {
  443. console.error('请求失败:', err);
  444. },
  445. complete: () => {
  446. this.loading = false;
  447. }
  448. });
  449. } catch (error) {
  450. console.error('获取数据失败:', error);
  451. this.loading = false;
  452. }
  453. },
  454. handleStreamResponse(data) {
  455. // 处理流式响应数据
  456. if (typeof data === 'string') {
  457. // 处理字符串格式的响应
  458. if (data === '[DONE]') return;
  459. try {
  460. // 移除可能存在的换行符和多余空格
  461. const cleanData = data.trim();
  462. // 检查是否是有效的JSON字符串
  463. if (cleanData.startsWith('{') && cleanData.endsWith('}')) {
  464. const jsonData = JSON.parse(cleanData);
  465. this.processStreamChunk(jsonData);
  466. }
  467. } catch (e) {
  468. console.error('解析JSON失败:', e, '原始数据:', data);
  469. }
  470. } else {
  471. // 处理对象格式的响应
  472. this.processStreamChunk(data);
  473. }
  474. },
  475. processStreamChunk(chunk) {
  476. if (chunk.choices && chunk.choices.length > 0) {
  477. const choice = chunk.choices[0];
  478. // 处理助手回复内容
  479. if (choice.delta && choice.delta.content) {
  480. this.assistantResponse += choice.delta.content;
  481. }
  482. // 处理音频转写内容
  483. if (choice.delta && choice.delta.audio && choice.delta.audio.transcript) {
  484. this.audioTranscript += choice.delta.audio.transcript;
  485. }
  486. // 处理角色和音频转写
  487. if (choice.delta) {
  488. const result = {};
  489. if (choice.delta.role) {
  490. result.role = choice.delta.role;
  491. }
  492. if (choice.delta.audio && choice.delta.audio.transcript) {
  493. result.transcript = choice.delta.audio.transcript;
  494. }
  495. if (Object.keys(result).length > 0) {
  496. this.processedResponses.push(result);
  497. }
  498. }
  499. }
  500. },
  501. processResponseData() {
  502. // 处理返回的数据
  503. this.processedResponses = this.responses.map(item => {
  504. const result = {}
  505. // 处理角色信息
  506. if (item.delta && item.delta.role) {
  507. result.role = item.delta.role
  508. }
  509. // 处理音频转写文本
  510. if (item.delta && item.delta.audio && item.delta.audio.transcript) {
  511. result.transcript = item.delta.audio.transcript
  512. }
  513. return result
  514. }).filter(item => Object.keys(item).length > 0)
  515. },
  516. // 播放数字人视频
  517. playDigitalHumanVideo() {
  518. // 如果还没有加载问题数据,先获取问题数据
  519. if (this.videoList.length === 0) {
  520. this.fetchQuestions();
  521. return;
  522. }
  523. // 设置当前视频
  524. this.videoUrl = this.videoList[this.currentVideoIndex];
  525. this.videoPlaying = true;
  526. // 使用 uni.createVideoContext 来控制视频
  527. this.$nextTick(() => {
  528. const videoContext = uni.createVideoContext('myVideo', this);
  529. if (videoContext) {
  530. videoContext.play();
  531. // 设置超时检查,确认视频是否真的在播放
  532. setTimeout(() => {
  533. if (this.videoPlaying && this.$refs.videoPlayer) {
  534. console.log('视频应该正在播放');
  535. } else {
  536. console.log('视频可能未成功播放,尝试替代方案');
  537. this.tryAlternativeVideoPath();
  538. }
  539. }, 1000);
  540. } else {
  541. console.error('无法创建视频上下文');
  542. this.tryAlternativeVideoPath();
  543. }
  544. });
  545. },
  546. // 修改 tryAlternativeVideoPath 方法
  547. tryAlternativeVideoPath() {
  548. console.log('尝试使用替代路径');
  549. // 尝试不同的路径格式
  550. const alternativePaths = [
  551. './static/demo.mp4',
  552. '../static/demo.mp4',
  553. 'static/demo.mp4',
  554. '/static/demo.mp4',
  555. // 添加绝对路径
  556. `${window.location.origin}/static/demo.mp4`
  557. ];
  558. // 获取当前路径索引
  559. const currentPathIndex = alternativePaths.indexOf(this.videoUrl);
  560. const nextPathIndex = (currentPathIndex + 1) % alternativePaths.length;
  561. // 设置下一个路径
  562. this.videoUrl = alternativePaths[nextPathIndex];
  563. console.log('尝试新路径:', this.videoUrl);
  564. this.$nextTick(() => {
  565. const videoContext = uni.createVideoContext('myVideo', this);
  566. if (videoContext) {
  567. videoContext.stop();
  568. videoContext.play();
  569. // 检查是否成功播放
  570. setTimeout(() => {
  571. if (nextPathIndex === alternativePaths.length - 1 && !this.videoPlaying) {
  572. console.log('所有路径均失败,尝试使用uni.getVideoInfo检查视频');
  573. this.checkVideoWithAPI();
  574. }
  575. }, 1000);
  576. }
  577. });
  578. },
  579. // 添加新方法:使用uni API检查视频
  580. checkVideoWithAPI() {
  581. // 尝试使用uni.getVideoInfo API检查视频是否可用
  582. uni.getVideoInfo({
  583. src: '/static/demo.mp4',
  584. success: (res) => {
  585. console.log('视频信息获取成功:', res);
  586. // 如果能获取到视频信息,再次尝试播放
  587. this.videoUrl = '/static/demo.mp4';
  588. this.$nextTick(() => {
  589. const videoContext = uni.createVideoContext('myVideo', this);
  590. if (videoContext) {
  591. videoContext.play();
  592. }
  593. });
  594. },
  595. fail: (err) => {
  596. console.error('视频信息获取失败:', err);
  597. // 最后尝试使用uni.chooseVideo API
  598. this.fallbackToLocalVideo();
  599. }
  600. });
  601. },
  602. // 添加新方法:回退到本地视频
  603. fallbackToLocalVideo() {
  604. console.log('尝试使用本地视频资源');
  605. // 检查平台
  606. const platform = uni.getSystemInfoSync().platform;
  607. if (platform === 'android' || platform === 'ios') {
  608. // 移动端可以尝试使用本地资源
  609. this.videoUrl = platform === 'android' ? 'android.resource://package_name/raw/demo' : 'file:///assets/demo.mp4';
  610. this.$nextTick(() => {
  611. const videoContext = uni.createVideoContext('myVideo', this);
  612. if (videoContext) {
  613. videoContext.play();
  614. }
  615. });
  616. } else {
  617. // 最终回退到静态图片
  618. this.videoPlaying = false;
  619. uni.showToast({
  620. title: '视频加载失败,显示静态图片',
  621. icon: 'none'
  622. });
  623. }
  624. },
  625. // 修改 handleVideoError 方法
  626. handleVideoError(e) {
  627. console.error('视频加载错误:', e);
  628. // 记录更详细的错误信息
  629. if (e && e.detail) {
  630. console.error('详细错误信息:', e.detail);
  631. }
  632. // 检查视频文件是否存在
  633. uni.getFileInfo({
  634. filePath: this.videoUrl.startsWith('/') ? this.videoUrl.substring(1) : this.videoUrl,
  635. success: (res) => {
  636. console.log('文件存在,大小:', res.size);
  637. // 文件存在但播放失败,可能是格式问题
  638. this.tryDifferentFormat();
  639. },
  640. fail: (err) => {
  641. console.error('文件不存在或无法访问:', err);
  642. // 尝试不同路径
  643. this.tryAlternativeVideoPath();
  644. }
  645. });
  646. // 如果多次尝试后仍然失败,显示错误信息
  647. uni.showToast({
  648. title: '视频加载失败,请检查文件是否存在',
  649. icon: 'none',
  650. duration: 2000
  651. });
  652. },
  653. // 添加新方法:尝试不同格式
  654. tryDifferentFormat() {
  655. console.log('尝试不同的视频格式');
  656. // 尝试不同的视频格式
  657. const formats = [
  658. { ext: 'mp4', mime: 'video/mp4' },
  659. { ext: 'webm', mime: 'video/webm' },
  660. { ext: 'ogg', mime: 'video/ogg' },
  661. { ext: 'mov', mime: 'video/quicktime' }
  662. ];
  663. // 获取当前文件名(不含扩展名)
  664. const currentPath = this.videoUrl;
  665. const basePath = currentPath.substring(0, currentPath.lastIndexOf('.')) || '/static/demo';
  666. // 尝试下一个格式
  667. let nextFormat = formats.find(f => !currentPath.endsWith(f.ext));
  668. if (nextFormat) {
  669. this.videoUrl = `${basePath}.${nextFormat.ext}`;
  670. console.log('尝试新格式:', this.videoUrl);
  671. this.$nextTick(() => {
  672. const videoContext = uni.createVideoContext('myVideo', this);
  673. if (videoContext) {
  674. videoContext.stop();
  675. videoContext.play();
  676. }
  677. });
  678. } else {
  679. // 所有格式都尝试过了,使用内置资源
  680. this.useBuiltInResource();
  681. }
  682. },
  683. // 添加新方法:使用内置资源
  684. useBuiltInResource() {
  685. console.log('尝试使用内置资源');
  686. // 检查平台
  687. const platform = uni.getSystemInfoSync().platform;
  688. // 根据平台选择合适的视频源
  689. if (platform === 'windows') {
  690. // Windows平台特定处理
  691. // 尝试使用相对于应用根目录的路径
  692. const appRoot = process.env.UNI_INPUT_DIR || '';
  693. this.videoUrl = `./static/demo.mp4`;
  694. // 或者尝试使用file://协议
  695. // this.videoUrl = `file:///${appRoot.replace(/\\/g, '/')}/static/demo.mp4`;
  696. console.log('Windows平台尝试路径:', this.videoUrl);
  697. } else if (platform === 'android' || platform === 'ios') {
  698. // 移动端
  699. this.useNativeVideo();
  700. } else {
  701. // Web平台
  702. // 尝试使用完整URL
  703. const baseUrl = window.location.origin;
  704. this.videoUrl = `${baseUrl}/static/demo.mp4`;
  705. console.log('Web平台尝试URL:', this.videoUrl);
  706. }
  707. this.$nextTick(() => {
  708. const videoContext = uni.createVideoContext('myVideo', this);
  709. if (videoContext) {
  710. videoContext.play();
  711. }
  712. });
  713. },
  714. // 添加新方法:使用原生视频能力
  715. useNativeVideo() {
  716. console.log('尝试使用原生视频能力');
  717. // 在移动端,可以尝试使用原生视频播放器
  718. uni.chooseVideo({
  719. sourceType: ['album'],
  720. success: (res) => {
  721. this.videoUrl = res.tempFilePath;
  722. this.$nextTick(() => {
  723. const videoContext = uni.createVideoContext('myVideo', this);
  724. if (videoContext) {
  725. videoContext.play();
  726. }
  727. });
  728. },
  729. fail: () => {
  730. // 如果用户取消选择,回退到静态图片
  731. this.videoPlaying = false;
  732. uni.showToast({
  733. title: '无法加载视频,显示静态图片',
  734. icon: 'none'
  735. });
  736. }
  737. });
  738. },
  739. // 处理视频结束事件
  740. handleVideoEnded() {
  741. console.log('视频播放结束');
  742. this.videoPlaying = false;
  743. // 检查是否是低分提示视频
  744. if (this.isPlayingLowScoreVideo) {
  745. console.log('低分提示视频播放完成');
  746. // 检查重试次数
  747. if (this.retryCount < this.maxRetryAttempts) {
  748. console.log(`显示重新录制按钮 (重试次数: ${this.retryCount + 1}/${this.maxRetryAttempts})`);
  749. // 显示重新录制按钮
  750. this.showRerecordButton = true;
  751. } else {
  752. console.log('已达到最大重试次数,继续下一题');
  753. // 重置重试次数
  754. this.retryCount = 0;
  755. // 继续下一个问题
  756. this.proceedToNextQuestion();
  757. }
  758. // 重置标记和清除字幕
  759. this.isPlayingLowScoreVideo = false;
  760. this.currentSubtitle = '';
  761. return;
  762. }
  763. // 恢复原有的视频结束处理逻辑
  764. // 对于所有视频,都显示相应的按钮
  765. if (this.currentVideoIndex >= 1) {
  766. // 对于问题视频,显示"开始回答"按钮
  767. this.showStartRecordingButton = true;
  768. this.startCountdown();
  769. } else {
  770. // 对于介绍视频(第一个视频),显示"开始面试"按钮
  771. this.showAnswerButton = true;
  772. }
  773. },
  774. // 添加新方法:开始倒计时
  775. startCountdown() {
  776. // 显示倒计时蒙层
  777. this.showCountdown = true;
  778. this.countdownValue = 10;
  779. // 开始倒计时
  780. this.countdownTimer = setInterval(() => {
  781. this.countdownValue--;
  782. if (this.countdownValue <= 0) {
  783. // 倒计时结束,清除定时器
  784. this.clearCountdown();
  785. // 隐藏"开始回答"按钮
  786. this.showStartRecordingButton = false;
  787. // 开始录制
  788. this.startRecordingAnswer();
  789. }
  790. }, 1000);
  791. },
  792. // 添加新方法:清除倒计时
  793. clearCountdown() {
  794. if (this.countdownTimer) {
  795. clearInterval(this.countdownTimer);
  796. this.countdownTimer = null;
  797. }
  798. this.showCountdown = false;
  799. },
  800. // 修改 handleStartRecordingClick 方法,使其可以终止倒计时
  801. handleStartRecordingClick() {
  802. // 隐藏"开始回答"按钮
  803. this.showStartRecordingButton = false;
  804. // 如果倒计时正在进行,清除倒计时
  805. this.clearCountdown();
  806. // 直接开始录制
  807. this.startRecordingAnswer();
  808. },
  809. // 修改 stopRecordingAnswer 方法,确保清除倒计时
  810. stopRecordingAnswer() {
  811. // 如果倒计时正在进行,先清除倒计时
  812. this.clearCountdown();
  813. // 检查录制时长
  814. const recordingDuration = this.getRecordingDuration();
  815. const minimumDuration = 5; // 最小录制时长(秒)
  816. if (recordingDuration < minimumDuration) {
  817. // 录制时间过短,显示提示
  818. uni.showToast({
  819. title: '录制时间过短,请至少录制5秒',
  820. icon: 'none',
  821. duration: 2000
  822. });
  823. // 不执行停止录制逻辑,继续录制
  824. return;
  825. }
  826. // 录制时长足够,直接停止
  827. this.completeRecordingStop();
  828. },
  829. // 添加新方法:开始录制用户回答
  830. startRecordingAnswer() {
  831. console.log('开始录制用户回答');
  832. this.isRecording = true;
  833. // 记录录制开始时间
  834. this.recordingStartTime = Date.now();
  835. this.recordingTimerCount = 0;
  836. this.remainingTime = this.maxRecordingTime;
  837. // 启动计时器,每秒更新计时
  838. this.recordingTimer = setInterval(() => {
  839. this.recordingTimerCount++;
  840. this.remainingTime = Math.max(0, this.maxRecordingTime - this.recordingTimerCount);
  841. // 更新UI显示录制时长和剩余时间
  842. this.recordingTimeDisplay = this.formatTime(this.recordingTimerCount) +
  843. ' / ' + this.formatTime(this.maxRecordingTime);
  844. // 检查是否达到最大录制时间
  845. if (this.recordingTimerCount >= this.maxRecordingTime) {
  846. console.log('已达到最大录制时间(60秒),自动停止录制');
  847. this.stopRecordingAnswer();
  848. }
  849. }, 1000);
  850. // 显示录制中的提示
  851. // uni.showLoading({
  852. // title: '正在录制...',
  853. // mask: true
  854. // });
  855. // 根据平台选择不同的录制方法
  856. const systemInfo = uni.getSystemInfoSync();
  857. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
  858. if (isMiniProgram) {
  859. // 小程序环境使用小程序的录制API
  860. this.startMiniProgramRecording();
  861. } else {
  862. // H5/App环境使用MediaRecorder API
  863. this.startBrowserRecording();
  864. }
  865. // 显示停止录制按钮
  866. this.showStopRecordingButton = true;
  867. },
  868. // 添加一个新方法:重置相机组件
  869. resetCamera() {
  870. console.log('重置相机组件');
  871. // 先完全移除相机组件
  872. this.useMiniProgramCameraComponent = false;
  873. // 释放相机上下文
  874. if (this.cameraContext) {
  875. this.cameraContext = null;
  876. }
  877. // 延迟后重新创建相机组件
  878. setTimeout(() => {
  879. this.useMiniProgramCameraComponent = true;
  880. // 再次延迟创建相机上下文,确保组件已完全渲染
  881. setTimeout(() => {
  882. this.cameraContext = uni.createCameraContext();
  883. console.log('相机组件已重置');
  884. }, 500);
  885. }, 500);
  886. },
  887. // 修改 startMiniProgramRecording 方法
  888. startMiniProgramRecording() {
  889. console.log('开始小程序录制方法');
  890. // 获取平台信息
  891. const systemInfo = uni.getSystemInfoSync();
  892. const isIOS = systemInfo.platform === 'ios';
  893. // 在iOS上,先重置相机
  894. if (isIOS) {
  895. // 先重置相机组件
  896. this.resetCamera();
  897. // 延迟执行录制,给相机组件足够的初始化时间
  898. setTimeout(() => {
  899. this.actualStartRecording(isIOS);
  900. }, 1000);
  901. } else {
  902. // Android直接开始
  903. this.actualStartRecording(isIOS);
  904. }
  905. },
  906. // 添加新方法:实际开始录制
  907. actualStartRecording(isIOS) {
  908. if (!this.cameraContext) {
  909. this.cameraContext = uni.createCameraContext();
  910. console.log('创建新的相机上下文');
  911. }
  912. // 确保有录音权限
  913. uni.getSetting({
  914. success: (res) => {
  915. const hasRecordAuth = res.authSetting['scope.record'];
  916. const hasCameraAuth = res.authSetting['scope.camera'];
  917. if (!hasRecordAuth || !hasCameraAuth) {
  918. console.warn('缺少必要权限,请求权限');
  919. this.requestMiniProgramPermissions();
  920. return;
  921. }
  922. // 在iOS上,先检查相机状态
  923. if (isIOS) {
  924. console.log('iOS: 检查相机状态');
  925. // 使用最简单的选项,设置最大录制时间为5分钟
  926. const options = {
  927. timeout: 300000, // 300秒超时 (5分钟)
  928. quality: 'low', // 降低质量
  929. compressed: true,
  930. success: () => {
  931. console.log('iOS录制开始成功');
  932. },
  933. fail: (err) => {
  934. console.error('iOS录制失败:', err);
  935. // 如果失败,尝试使用不同的方法
  936. this.useAlternativeRecordingMethod();
  937. }
  938. };
  939. try {
  940. console.log('尝试开始录制');
  941. this.recorder = this.cameraContext.startRecord(options);
  942. } catch (e) {
  943. console.error('开始录制异常:', e);
  944. this.useAlternativeRecordingMethod();
  945. }
  946. } else {
  947. // Android使用标准选项,设置最大录制时间为5分钟
  948. const options = {
  949. timeout: 300000, // 300秒超时 (5分钟)
  950. quality: 'medium',
  951. compressed: true,
  952. success: () => {
  953. console.log('Android录制开始成功');
  954. },
  955. fail: (err) => {
  956. console.error('Android录制失败:', err);
  957. uni.showToast({
  958. title: '录制失败,请检查相机权限',
  959. icon: 'none'
  960. });
  961. this.proceedToNextQuestion();
  962. }
  963. };
  964. this.recorder = this.cameraContext.startRecord(options);
  965. }
  966. }
  967. });
  968. },
  969. // 添加新方法:使用替代录制方法
  970. useAlternativeRecordingMethod() {
  971. console.log('使用替代录制方法');
  972. // 在iOS上,可以尝试使用chooseVideo API作为备选
  973. uni.showActionSheet({
  974. itemList: ['使用相册中的视频', '跳过此问题'],
  975. success: (res) => {
  976. if (res.tapIndex === 0) {
  977. // 选择相册中的视频
  978. uni.chooseVideo({
  979. sourceType: ['album'],
  980. maxDuration: 300, // 从60秒改为300秒
  981. camera: 'front',
  982. success: (res) => {
  983. console.log('选择视频成功:', res.tempFilePath);
  984. // 停止录制状态
  985. this.isRecording = false;
  986. this.showStopRecordingButton = false;
  987. // 上传选择的视频
  988. this.uploadRecordedVideo(res.tempFilePath);
  989. },
  990. fail: () => {
  991. console.log('用户取消选择视频');
  992. this.proceedToNextQuestion();
  993. }
  994. });
  995. } else {
  996. // 跳过此问题
  997. console.log('用户选择跳过问题');
  998. this.proceedToNextQuestion();
  999. }
  1000. },
  1001. fail: () => {
  1002. console.log('操作取消');
  1003. this.proceedToNextQuestion();
  1004. }
  1005. });
  1006. },
  1007. // 添加新方法:请求小程序权限
  1008. requestMiniProgramPermissions() {
  1009. // 请求录音权限
  1010. uni.authorize({
  1011. scope: 'scope.record',
  1012. success: () => {
  1013. console.log('录音权限已获取');
  1014. // 请求相机权限
  1015. uni.authorize({
  1016. scope: 'scope.camera',
  1017. success: () => {
  1018. console.log('相机权限已获取');
  1019. // 权限都获取到后,开始录制
  1020. this.startMiniProgramRecording();
  1021. },
  1022. fail: (err) => {
  1023. console.error('相机权限获取失败:', err);
  1024. this.showPermissionDialog('相机');
  1025. }
  1026. });
  1027. },
  1028. fail: (err) => {
  1029. console.error('录音权限获取失败:', err);
  1030. this.showPermissionDialog('录音');
  1031. }
  1032. });
  1033. },
  1034. // 修改浏览器环境下的录制方法
  1035. startBrowserRecording() {
  1036. if (!this.cameraStream) {
  1037. console.error('没有可用的摄像头流');
  1038. uni.showToast({
  1039. title: '录制失败,摄像头未就绪',
  1040. icon: 'none'
  1041. });
  1042. this.proceedToNextQuestion();
  1043. return;
  1044. }
  1045. try {
  1046. // 检查流中是否包含音频轨道
  1047. const hasAudio = this.cameraStream.getAudioTracks().length > 0;
  1048. if (!hasAudio) {
  1049. console.warn('警告:媒体流中没有音频轨道,尝试重新获取带音频的媒体流');
  1050. // 尝试重新获取带音频的媒体流
  1051. navigator.mediaDevices.getUserMedia({
  1052. audio: {
  1053. echoCancellation: true,
  1054. noiseSuppression: true,
  1055. autoGainControl: true
  1056. },
  1057. video: true
  1058. })
  1059. .then(newStream => {
  1060. // 检查新流是否包含音频轨道
  1061. const audioTracks = newStream.getAudioTracks();
  1062. if (audioTracks.length > 0) {
  1063. console.log('成功获取音频轨道:', audioTracks[0].label);
  1064. // 合并视频和音频轨道
  1065. const videoTrack = this.cameraStream.getVideoTracks()[0];
  1066. const audioTrack = newStream.getAudioTracks()[0];
  1067. // 创建新的媒体流,包含视频和音频轨道
  1068. const combinedStream = new MediaStream();
  1069. if (videoTrack) combinedStream.addTrack(videoTrack);
  1070. if (audioTrack) combinedStream.addTrack(audioTrack);
  1071. this.cameraStream = combinedStream;
  1072. // 更新视频元素的源
  1073. const videoElement = this.$refs.userCameraVideo;
  1074. if (videoElement) {
  1075. videoElement.srcObject = combinedStream;
  1076. videoElement.muted = true; // 避免回声,但仍然录制声音
  1077. }
  1078. // 继续录制过程
  1079. this.setupMediaRecorder(combinedStream);
  1080. } else {
  1081. console.warn('仍然无法获取音频轨道');
  1082. // 使用现有流继续
  1083. this.setupMediaRecorder(this.cameraStream);
  1084. }
  1085. })
  1086. .catch(err => {
  1087. console.error('获取音频失败:', err);
  1088. // 使用现有流继续
  1089. this.setupMediaRecorder(this.cameraStream);
  1090. });
  1091. } else {
  1092. console.log('检测到音频轨道,直接使用');
  1093. // 已有音频轨道,直接使用
  1094. this.setupMediaRecorder(this.cameraStream);
  1095. }
  1096. } catch (error) {
  1097. console.error('浏览器录制失败:', error);
  1098. uni.showToast({
  1099. title: '录制失败,浏览器可能不支持此功能',
  1100. icon: 'none'
  1101. });
  1102. this.proceedToNextQuestion();
  1103. }
  1104. },
  1105. // 修改 setupMediaRecorder 方法
  1106. setupMediaRecorder(stream) {
  1107. // 检查流中的轨道
  1108. const videoTracks = stream.getVideoTracks();
  1109. const audioTracks = stream.getAudioTracks();
  1110. console.log('设置MediaRecorder - 视频轨道:', videoTracks.length, '音频轨道:', audioTracks.length);
  1111. // 尝试使用支持度更广的编码格式
  1112. let mimeType = '';
  1113. const supportedTypes = [
  1114. 'video/webm;codecs=vp9,opus',
  1115. 'video/webm;codecs=vp8,opus',
  1116. 'video/webm;codecs=h264,opus',
  1117. 'video/mp4;codecs=h264,aac',
  1118. 'video/webm',
  1119. 'video/mp4'
  1120. ];
  1121. for (const type of supportedTypes) {
  1122. if (MediaRecorder.isTypeSupported(type)) {
  1123. mimeType = type;
  1124. console.log('使用支持的MIME类型:', mimeType);
  1125. break;
  1126. }
  1127. }
  1128. // 创建MediaRecorder实例,设置较低的比特率以减小文件大小
  1129. const options = {
  1130. mimeType: mimeType || '',
  1131. audioBitsPerSecond: 64000, // 降低音频比特率
  1132. videoBitsPerSecond: 1000000, // 降低视频比特率到1Mbps
  1133. };
  1134. try {
  1135. this.mediaRecorder = new MediaRecorder(stream, options);
  1136. console.log('MediaRecorder创建成功,使用选项:', options);
  1137. } catch (e) {
  1138. console.warn('使用指定选项创建MediaRecorder失败,尝试使用默认选项');
  1139. this.mediaRecorder = new MediaRecorder(stream);
  1140. }
  1141. // 存储录制的数据块
  1142. this.recordedChunks = [];
  1143. // 监听数据可用事件
  1144. this.mediaRecorder.ondataavailable = (event) => {
  1145. if (event.data && event.data.size > 0) {
  1146. this.recordedChunks.push(event.data);
  1147. console.log(`收到数据块: ${event.data.size} 字节`);
  1148. }
  1149. };
  1150. // 监听录制停止事件
  1151. this.mediaRecorder.onstop = async () => {
  1152. console.log('MediaRecorder停止,数据块数量:', this.recordedChunks.length);
  1153. if (this.recordedChunks.length === 0) {
  1154. console.error('没有录制到数据');
  1155. uni.showToast({
  1156. title: '录制失败,未捕获到数据',
  1157. icon: 'none'
  1158. });
  1159. this.proceedToNextQuestion();
  1160. return;
  1161. }
  1162. // 创建Blob对象
  1163. const mimeType = this.mediaRecorder.mimeType || 'video/webm';
  1164. const blob = new Blob(this.recordedChunks, { type: mimeType });
  1165. console.log('创建Blob,原始大小:', blob.size, '类型:', mimeType);
  1166. // 显示压缩中提示
  1167. uni.showLoading({
  1168. title: '正在处理视频...',
  1169. mask: true
  1170. });
  1171. try {
  1172. // 压缩视频
  1173. const compressedBlob = await this.compressVideo(blob);
  1174. // 将Blob转换为File对象
  1175. const fileName = `answer_${this.currentVideoIndex}_${Date.now()}.webm`;
  1176. const file = new File([compressedBlob], fileName, { type: mimeType });
  1177. // 隐藏压缩提示
  1178. uni.hideLoading();
  1179. // 上传文件
  1180. this.uploadRecordedVideo(file);
  1181. } catch (error) {
  1182. console.error('视频处理失败:', error);
  1183. uni.hideLoading();
  1184. // 如果压缩失败,使用原始视频
  1185. const fileName = `answer_${this.currentVideoIndex}_${Date.now()}.webm`;
  1186. const file = new File([blob], fileName, { type: mimeType });
  1187. this.uploadRecordedVideo(file);
  1188. }
  1189. };
  1190. // 监听错误
  1191. this.mediaRecorder.onerror = (event) => {
  1192. console.error('MediaRecorder错误:', event.error);
  1193. };
  1194. // 开始录制
  1195. try {
  1196. this.mediaRecorder.start(1000); // 每秒触发一次dataavailable事件
  1197. console.log('MediaRecorder开始录制');
  1198. // 设置最大录制时间为60秒
  1199. // 注意:我们已经在startRecordingAnswer方法中设置了全局计时器
  1200. // 这里作为备份机制,确保即使全局计时器失效,也能停止录制
  1201. this.mediaRecorderTimeout = setTimeout(() => {
  1202. if (this.mediaRecorder && this.mediaRecorder.state === 'recording') {
  1203. console.log('MediaRecorder备份超时机制触发,停止录制');
  1204. this.mediaRecorder.stop();
  1205. }
  1206. }, 300000); // 300秒 (5分钟)
  1207. } catch (e) {
  1208. console.error('开始录制失败:', e);
  1209. }
  1210. },
  1211. // 添加新方法:停止录制用户回答
  1212. stopRecordingAnswer() {
  1213. console.log('停止录制用户回答');
  1214. // 如果倒计时正在进行,先清除倒计时
  1215. if (this.countdownTimer) {
  1216. clearInterval(this.countdownTimer);
  1217. this.countdownTimer = null;
  1218. this.showCountdown = false;
  1219. }
  1220. // 检查录制时长
  1221. const recordingDuration = this.getRecordingDuration();
  1222. const minimumDuration = 5; // 最小录制时长(秒),从3秒改为5秒
  1223. if (recordingDuration < minimumDuration) {
  1224. // 录制时间过短,显示提示
  1225. uni.showToast({
  1226. title: '录制时间过短,请至少录制5秒',
  1227. icon: 'none',
  1228. duration: 2000
  1229. });
  1230. // 不执行停止录制逻辑,继续录制
  1231. return;
  1232. }
  1233. // 录制时长足够,直接停止
  1234. this.completeRecordingStop();
  1235. },
  1236. // 添加新方法:获取录制时长
  1237. getRecordingDuration() {
  1238. // 如果有明确的录制开始时间,计算实际录制时长
  1239. if (this.recordingStartTime) {
  1240. return (Date.now() - this.recordingStartTime) / 1000;
  1241. }
  1242. // 如果没有明确记录开始时间,尝试从视频元素获取
  1243. if (this.mediaRecorder && this.$refs.userCameraVideo) {
  1244. return this.$refs.userCameraVideo.currentTime || 0;
  1245. }
  1246. // 如果无法获取准确时长,返回估计值(如果有计时器)
  1247. if (this.recordingTimerCount) {
  1248. return this.recordingTimerCount;
  1249. }
  1250. // 默认返回0
  1251. return 0;
  1252. },
  1253. // 添加新方法:重置录制
  1254. resetRecording() {
  1255. // 保持录制状态,但重置计时器
  1256. if (this.recordingTimer) {
  1257. clearTimeout(this.recordingTimer);
  1258. }
  1259. // 重置录制开始时间
  1260. this.recordingStartTime = Date.now();
  1261. this.recordingTimerCount = 0;
  1262. // 如果是浏览器环境,需要重置MediaRecorder
  1263. if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
  1264. // 停止当前录制
  1265. this.mediaRecorder.stop();
  1266. // 清空已录制的数据块
  1267. this.recordedChunks = [];
  1268. // 短暂延迟后重新开始录制
  1269. setTimeout(() => {
  1270. this.startBrowserRecording();
  1271. }, 500);
  1272. }
  1273. // 如果是小程序环境,需要重置相机录制
  1274. else if (this.cameraContext) {
  1275. // 停止当前录制
  1276. this.cameraContext.stopRecord({
  1277. success: () => {
  1278. console.log('重置录制:停止当前录制成功');
  1279. // 短暂延迟后重新开始录制
  1280. setTimeout(() => {
  1281. this.startMiniProgramRecording();
  1282. }, 500);
  1283. },
  1284. fail: (err) => {
  1285. console.error('重置录制:停止当前录制失败', err);
  1286. // 尝试直接重新开始录制
  1287. this.startMiniProgramRecording();
  1288. }
  1289. });
  1290. }
  1291. // 显示提示
  1292. uni.showToast({
  1293. title: '请重新开始回答',
  1294. icon: 'none',
  1295. duration: 2000
  1296. });
  1297. },
  1298. // 添加新方法:完成录制停止流程
  1299. completeRecordingStop() {
  1300. this.isRecording = false;
  1301. // 清除定时器
  1302. if (this.recordingTimer) {
  1303. clearInterval(this.recordingTimer);
  1304. this.recordingTimer = null;
  1305. }
  1306. // 清除MediaRecorder超时定时器
  1307. if (this.mediaRecorderTimeout) {
  1308. clearTimeout(this.mediaRecorderTimeout);
  1309. this.mediaRecorderTimeout = null;
  1310. }
  1311. // 隐藏录制中提示
  1312. uni.hideLoading();
  1313. // 隐藏停止录制按钮
  1314. this.showStopRecordingButton = false;
  1315. // 根据平台选择不同的停止录制方法
  1316. const systemInfo = uni.getSystemInfoSync();
  1317. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
  1318. if (isMiniProgram) {
  1319. // 小程序环境停止录制
  1320. this.stopMiniProgramRecording();
  1321. } else {
  1322. // H5/App环境停止录制
  1323. this.stopBrowserRecording();
  1324. }
  1325. },
  1326. // 修改 stopMiniProgramRecording 方法
  1327. stopMiniProgramRecording() {
  1328. if (!this.cameraContext) {
  1329. console.error('相机上下文不存在');
  1330. this.proceedToNextQuestion();
  1331. return;
  1332. }
  1333. const systemInfo = uni.getSystemInfoSync();
  1334. const isIOS = systemInfo.platform === 'ios';
  1335. // 在iOS上添加额外的错误处理
  1336. const stopOptions = {
  1337. success: (res) => {
  1338. console.log('小程序录像停止成功:', res);
  1339. // 获取临时文件路径
  1340. const tempFilePath = res.tempVideoPath;
  1341. if (!tempFilePath) {
  1342. console.error('未获取到视频文件路径');
  1343. uni.showToast({
  1344. title: '录制失败,未获取到视频文件',
  1345. icon: 'none'
  1346. });
  1347. this.proceedToNextQuestion();
  1348. return;
  1349. }
  1350. // 在iOS上,检查文件是否存在
  1351. if (isIOS) {
  1352. uni.getFileInfo({
  1353. filePath: tempFilePath,
  1354. success: () => {
  1355. // 文件存在,上传视频
  1356. this.uploadRecordedVideo(tempFilePath);
  1357. },
  1358. fail: (err) => {
  1359. console.error('视频文件不存在:', err);
  1360. uni.showToast({
  1361. title: '录制失败,视频文件不存在',
  1362. icon: 'none'
  1363. });
  1364. this.proceedToNextQuestion();
  1365. }
  1366. });
  1367. } else {
  1368. // Android直接上传
  1369. this.uploadRecordedVideo(tempFilePath);
  1370. }
  1371. },
  1372. fail: (err) => {
  1373. console.error('小程序录像停止失败:', err);
  1374. uni.showToast({
  1375. title: '录制失败',
  1376. icon: 'none'
  1377. });
  1378. this.proceedToNextQuestion();
  1379. }
  1380. };
  1381. // 停止录制
  1382. this.cameraContext.stopRecord(stopOptions);
  1383. },
  1384. // 添加新方法:停止浏览器录制
  1385. stopBrowserRecording() {
  1386. if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
  1387. this.mediaRecorder.stop();
  1388. console.log('浏览器录制停止成功');
  1389. } else {
  1390. console.error('MediaRecorder不存在或已经停止');
  1391. this.proceedToNextQuestion();
  1392. }
  1393. },
  1394. // 修改上传录制的视频方法
  1395. uploadRecordedVideo(fileOrPath) {
  1396. console.log('准备上传视频:', typeof fileOrPath === 'string' ? fileOrPath : fileOrPath.name);
  1397. // 获取当前问题ID
  1398. let questionId;
  1399. // 获取当前正在回答的问题
  1400. const currentQuestion = this.getCurrentQuestionByIndex(this.currentVideoIndex);
  1401. if (currentQuestion && currentQuestion.id) {
  1402. // 直接使用API返回的问题ID
  1403. questionId = currentQuestion.id;
  1404. console.log(`使用API返回的问题ID: ${questionId}, 问题: ${currentQuestion.question}`);
  1405. } else {
  1406. // 如果没有找到对应的问题,使用默认ID
  1407. questionId = this.getDefaultQuestionId(this.currentVideoIndex);
  1408. console.log(`未找到当前问题,使用默认ID: ${questionId}`);
  1409. }
  1410. console.log('上传视频对应的问题ID:', questionId);
  1411. // 创建上传任务对象
  1412. const uploadTask = {
  1413. id: Date.now().toString(), // 生成唯一ID
  1414. file: fileOrPath,
  1415. questionId: questionId,
  1416. attempts: 0, // 上传尝试次数
  1417. maxAttempts: 3, // 最大尝试次数
  1418. };
  1419. // 添加到上传队列
  1420. this.uploadQueue.push(uploadTask);
  1421. // 初始化上传进度和状态
  1422. this.uploadProgress[uploadTask.id] = 0;
  1423. this.uploadStatus[uploadTask.id] = 'pending'; // pending, uploading, success, failed
  1424. // 显示简短的上传状态提示
  1425. uni.showToast({
  1426. title: '已完成回答',
  1427. icon: 'none',
  1428. duration: 1500
  1429. });
  1430. // 更新上传状态文本
  1431. this.updateUploadStatusText();
  1432. // 如果当前没有上传任务在进行,开始处理队列
  1433. if (!this.isUploading) {
  1434. this.processUploadQueue();
  1435. }
  1436. // 注意:不再自动进入下一个问题
  1437. // 我们会在WebSocket回调中决定是否进入下一个问题
  1438. },
  1439. // 添加新方法:处理上传队列
  1440. processUploadQueue() {
  1441. // 如果队列为空,结束处理
  1442. if (this.uploadQueue.length === 0) {
  1443. this.isUploading = false;
  1444. this.showUploadStatus = false;
  1445. return;
  1446. }
  1447. // 标记为正在上传
  1448. this.isUploading = true;
  1449. this.showUploadStatus = true;
  1450. // 获取队列中的第一个任务
  1451. const task = this.uploadQueue[0];
  1452. // 更新任务状态
  1453. this.uploadStatus[task.id] = 'uploading';
  1454. this.updateUploadStatusText();
  1455. // 增加尝试次数
  1456. task.attempts++;
  1457. // 根据文件类型选择上传方法
  1458. if (typeof task.file !== 'string') {
  1459. // 浏览器环境,使用XMLHttpRequest上传
  1460. this.uploadFileWithXHR(task);
  1461. } else {
  1462. // 小程序环境,使用uni.uploadFile上传
  1463. this.uploadFileWithUni(task);
  1464. }
  1465. },
  1466. // 添加新方法:使用XMLHttpRequest上传文件
  1467. uploadFileWithXHR(task) {
  1468. // 获取用户信息
  1469. const userInfo = uni.getStorageSync('userInfo');
  1470. const openid = userInfo ? (JSON.parse(userInfo).openid || '') : '';
  1471. const tenant_id = JSON.parse(uni.getStorageSync('userInfo')).tenant_id || '1';
  1472. // 创建FormData
  1473. const formData = new FormData();
  1474. formData.append('file', task.file);
  1475. formData.append('openid', openid);
  1476. formData.append('tenant_id', tenant_id);
  1477. formData.append('application_id', uni.getStorageSync('appId'));
  1478. formData.append('question_id', task.questionId);
  1479. formData.append('video_duration', 0);
  1480. formData.append('has_audio', 'true');
  1481. // 创建XMLHttpRequest
  1482. const xhr = new XMLHttpRequest();
  1483. xhr.open('POST', `${apiBaseUrl}/api/upload/`, true);
  1484. xhr.timeout = 120000; // 2分钟超时
  1485. // 监听上传进度
  1486. xhr.upload.onprogress = (event) => {
  1487. if (event.lengthComputable) {
  1488. const percentComplete = Math.round((event.loaded / event.total) * 100);
  1489. this.uploadProgress[task.id] = percentComplete;
  1490. this.updateUploadStatusText();
  1491. }
  1492. };
  1493. // 监听请求完成
  1494. xhr.onload = () => {
  1495. if (xhr.status === 200) {
  1496. try {
  1497. const res = JSON.parse(xhr.responseText);
  1498. console.log('上传响应:', res);
  1499. if (res.code === 2000) {
  1500. // 获取上传后的视频URL
  1501. const videoUrl = res.data.url || res.data.photoUrl || '';
  1502. if (videoUrl) {
  1503. // 上传成功,更新状态
  1504. this.uploadStatus[task.id] = 'success';
  1505. this.updateUploadStatusText();
  1506. // 提交到面试接口
  1507. this.submitVideoToInterview(videoUrl, task);
  1508. } else {
  1509. this.handleUploadFailure(task, '视频URL获取失败');
  1510. }
  1511. } else {
  1512. this.handleUploadFailure(task, res.msg || '上传失败');
  1513. }
  1514. } catch (e) {
  1515. this.handleUploadFailure(task, '解析响应失败');
  1516. }
  1517. } else {
  1518. this.handleUploadFailure(task, 'HTTP状态: ' + xhr.status);
  1519. }
  1520. };
  1521. // 监听错误
  1522. xhr.onerror = () => {
  1523. this.handleUploadFailure(task, '网络错误');
  1524. };
  1525. // 监听超时
  1526. xhr.ontimeout = () => {
  1527. this.handleUploadFailure(task, '上传超时');
  1528. };
  1529. // 发送请求
  1530. xhr.send(formData);
  1531. },
  1532. // 添加新方法:使用uni.uploadFile上传文件
  1533. uploadFileWithUni(task) {
  1534. // 获取用户信息
  1535. const userInfo = uni.getStorageSync('userInfo');
  1536. const openid = userInfo ? (JSON.parse(userInfo).openid || '') : '';
  1537. const tenant_id = JSON.parse(uni.getStorageSync('userInfo')).tenant_id || '1';
  1538. // 创建上传任务
  1539. const uploadTask = uni.uploadFile({
  1540. url: `${apiBaseUrl}/api/upload/`,
  1541. filePath: task.file,
  1542. name: 'file',
  1543. formData: {
  1544. openid: openid,
  1545. tenant_id: tenant_id,
  1546. application_id: uni.getStorageSync('appId'),
  1547. question_id: task.questionId,
  1548. video_duration: 0,
  1549. has_audio: 'true'
  1550. },
  1551. success: (uploadRes) => {
  1552. try {
  1553. const res = JSON.parse(uploadRes.data);
  1554. console.log('上传响应:', res);
  1555. if (res.code === 2000) {
  1556. // 获取上传后的视频URL
  1557. const videoUrl = res.data.permanent_link || res.data.url || '';
  1558. if (videoUrl) {
  1559. // 上传成功,更新状态
  1560. this.uploadStatus[task.id] = 'success';
  1561. this.updateUploadStatusText();
  1562. // 提交到面试接口
  1563. this.submitVideoToInterview(videoUrl, task);
  1564. } else {
  1565. this.handleUploadFailure(task, '视频URL获取失败');
  1566. }
  1567. } else {
  1568. this.handleUploadFailure(task, res.msg || '上传失败');
  1569. }
  1570. } catch (e) {
  1571. this.handleUploadFailure(task, '解析响应失败');
  1572. }
  1573. },
  1574. fail: (err) => {
  1575. this.handleUploadFailure(task, err.errMsg || '上传失败');
  1576. }
  1577. });
  1578. // 监听上传进度
  1579. uploadTask.onProgressUpdate((res) => {
  1580. this.uploadProgress[task.id] = res.progress;
  1581. this.updateUploadStatusText();
  1582. });
  1583. },
  1584. // 添加新方法:处理上传失败
  1585. handleUploadFailure(task, errorMsg) {
  1586. console.error('上传失败:', errorMsg);
  1587. // 更新任务状态
  1588. this.uploadStatus[task.id] = 'failed';
  1589. this.updateUploadStatusText();
  1590. // 检查是否还有重试机会
  1591. if (task.attempts < task.maxAttempts) {
  1592. console.log(`将在5秒后重试上传,当前尝试次数: ${task.attempts}/${task.maxAttempts}`);
  1593. // 5秒后重试
  1594. setTimeout(() => {
  1595. // 重置进度
  1596. this.uploadProgress[task.id] = 0;
  1597. // 重新开始上传
  1598. if (typeof task.file !== 'string') {
  1599. this.uploadFileWithXHR(task);
  1600. } else {
  1601. this.uploadFileWithUni(task);
  1602. }
  1603. }, 5000);
  1604. } else {
  1605. // 超过最大重试次数,移除任务并继续处理队列
  1606. console.log('超过最大重试次数,放弃上传');
  1607. // 显示错误提示
  1608. uni.showToast({
  1609. title: '视频上传失败,请稍后重试',
  1610. icon: 'none',
  1611. duration: 2000
  1612. });
  1613. // 从队列中移除当前任务
  1614. this.uploadQueue.shift();
  1615. // 继续处理队列中的下一个任务
  1616. this.processUploadQueue();
  1617. }
  1618. },
  1619. // 修改 submitVideoToInterview 方法,添加 WebSocket 连接和分数检查
  1620. submitVideoToInterview(videoUrl, task = null) {
  1621. console.log('提交视频URL到面试接口:', videoUrl);
  1622. // 确定问题ID
  1623. let questionId;
  1624. if (task) {
  1625. questionId = task.questionId;
  1626. } else {
  1627. // 根据当前视频索引获取问题ID
  1628. if (this.currentVideoIndex >= 1 && this.questions.length > 0) {
  1629. // 获取当前正在回答的问题
  1630. const currentQuestion = this.getCurrentQuestionByIndex(this.currentVideoIndex);
  1631. if (currentQuestion && currentQuestion.id) {
  1632. // 直接使用API返回的问题ID
  1633. questionId = currentQuestion.id;
  1634. console.log(`使用API返回的问题ID: ${questionId}, 问题: ${currentQuestion.question}`);
  1635. } else {
  1636. // 如果没有找到对应的问题,使用默认ID
  1637. questionId = this.getDefaultQuestionId(this.currentVideoIndex);
  1638. console.log(`未找到当前问题,使用默认ID: ${questionId}`);
  1639. }
  1640. } else {
  1641. // 使用旧的映射逻辑作为备用
  1642. questionId = this.getDefaultQuestionId(this.currentVideoIndex);
  1643. console.log(`使用备用问题ID: ${questionId} (问题索引: ${this.currentVideoIndex})`);
  1644. }
  1645. }
  1646. // 准备请求参数
  1647. const requestData = {
  1648. application_id: uni.getStorageSync('appId'),
  1649. question_id: questionId,
  1650. video_url: videoUrl,
  1651. tenant_id: JSON.parse(uni.getStorageSync('userInfo')).tenant_id || '1'
  1652. };
  1653. console.log('提交面试请求参数:', requestData);
  1654. // 发送请求到面试接口
  1655. uni.request({
  1656. url: `${apiBaseUrl}/api/job/upload_video`,
  1657. method: 'POST',
  1658. data: requestData,
  1659. header: {
  1660. 'content-type': 'application/x-www-form-urlencoded'
  1661. },
  1662. success: (res) => {
  1663. console.log('面试接口提交成功:', res);
  1664. if (res.data.code === 200 || res.data.code === 200) {
  1665. // 提交成功
  1666. if (task) {
  1667. // 从队列中移除当前任务
  1668. this.uploadQueue.shift();
  1669. // 显示简短的成功提示
  1670. // uni.showToast({
  1671. // title: '视频提交成功',
  1672. // icon: 'success',
  1673. // duration: 1500
  1674. // });
  1675. // 连接WebSocket获取分析结果
  1676. this.connectToWebSocketForAnalysis(questionId, videoUrl);
  1677. // 继续处理队列中的下一个任务
  1678. this.processUploadQueue();
  1679. } else {
  1680. // 兼容旧代码的处理逻辑
  1681. uni.showToast({
  1682. title: '回答已提交',
  1683. icon: 'success'
  1684. });
  1685. // 连接WebSocket获取分析结果
  1686. this.connectToWebSocketForAnalysis(questionId, videoUrl);
  1687. // 保存最后上传的视频URL
  1688. this.lastUploadedVideoUrl = videoUrl;
  1689. // 隐藏重试按钮(如果之前显示了)
  1690. this.showRetryButton = false;
  1691. this.lastVideoToRetry = null;
  1692. }
  1693. } else {
  1694. // 提交失败
  1695. if (task) {
  1696. this.handleSubmitFailure(task, res.data.msg || '提交失败');
  1697. } else {
  1698. // 兼容旧代码的处理逻辑
  1699. uni.showToast({
  1700. title: res.data.msg || '提交失败,请重试',
  1701. icon: 'none'
  1702. });
  1703. // 保存失败的视频URL,用于重试
  1704. this.lastVideoToRetry = videoUrl;
  1705. // 显示重试按钮
  1706. this.showRetryButton = true;
  1707. }
  1708. }
  1709. },
  1710. fail: (err) => {
  1711. console.error('面试接口提交失败:', err);
  1712. if (task) {
  1713. this.handleSubmitFailure(task, err.errMsg || '网络错误');
  1714. } else {
  1715. // 兼容旧代码的处理逻辑
  1716. uni.hideLoading();
  1717. uni.showToast({
  1718. title: '网络错误,请重试',
  1719. icon: 'none'
  1720. });
  1721. // 保存失败的视频URL,用于重试
  1722. this.lastVideoToRetry = videoUrl;
  1723. // 显示重试按钮
  1724. this.showRetryButton = true;
  1725. }
  1726. }
  1727. });
  1728. },
  1729. // 添加新方法:处理提交失败
  1730. handleSubmitFailure(task, errorMsg) {
  1731. console.error('提交失败:', errorMsg);
  1732. // 更新任务状态
  1733. this.uploadStatus[task.id] = 'failed';
  1734. this.updateUploadStatusText();
  1735. // 检查是否还有重试机会
  1736. if (task.attempts < task.maxAttempts) {
  1737. console.log(`将在5秒后重试提交,当前尝试次数: ${task.attempts}/${task.maxAttempts}`);
  1738. // 5秒后重试
  1739. setTimeout(() => {
  1740. // 重新提交
  1741. this.submitVideoToInterview(task.videoUrl, task);
  1742. }, 5000);
  1743. } else {
  1744. // 超过最大重试次数,移除任务并继续处理队列
  1745. console.log('超过最大重试次数,放弃提交');
  1746. // 显示错误提示
  1747. uni.showToast({
  1748. title: '视频提交失败,请稍后重试',
  1749. icon: 'none',
  1750. duration: 2000
  1751. });
  1752. // 从队列中移除当前任务
  1753. this.uploadQueue.shift();
  1754. // 继续处理队列中的下一个任务
  1755. this.processUploadQueue();
  1756. }
  1757. },
  1758. // 添加新方法:更新上传状态文本
  1759. updateUploadStatusText() {
  1760. if (this.uploadQueue.length === 0) {
  1761. this.uploadStatusText = '';
  1762. return;
  1763. }
  1764. const currentTask = this.uploadQueue[0];
  1765. const progress = this.uploadProgress[currentTask.id] || 0;
  1766. const status = this.uploadStatus[currentTask.id] || 'pending';
  1767. let statusText = '';
  1768. switch (status) {
  1769. case 'pending':
  1770. statusText = '等待上传';
  1771. break;
  1772. case 'uploading':
  1773. statusText = `上传中 ${progress}%`;
  1774. break;
  1775. case 'success':
  1776. statusText = '上传成功,提交中...';
  1777. break;
  1778. case 'failed':
  1779. statusText = `上传失败,${currentTask.attempts < currentTask.maxAttempts ? '即将重试' : '已放弃'}`;
  1780. break;
  1781. }
  1782. this.uploadStatusText = `问题${currentTask.questionId - 9}:${statusText}`;
  1783. // 如果队列中有多个任务,显示总数
  1784. if (this.uploadQueue.length > 1) {
  1785. this.uploadStatusText += ` (${this.uploadQueue.length}个视频待处理)`;
  1786. }
  1787. },
  1788. // 修改 proceedToNextQuestion 方法,不要自动进入下一个问题
  1789. // 因为现在我们会在WebSocket回调中决定是否进入下一个问题
  1790. proceedToNextQuestion() {
  1791. // 重置重试计数器
  1792. this.retryCount = 0;
  1793. // 检查是否完成了第五个视频问题(索引为4)
  1794. if (this.currentVideoIndex === 4) {
  1795. // 完成第五个问题后,跳转到相机页面
  1796. uni.navigateTo({
  1797. url: '/pages/camera/camera'
  1798. });
  1799. return;
  1800. }
  1801. // 切换到下一个视频
  1802. this.currentVideoIndex++;
  1803. if (this.currentVideoIndex < this.videoList.length) {
  1804. // 还有下一段视频,播放它
  1805. this.videoUrl = this.videoList[this.currentVideoIndex];
  1806. this.videoPlaying = true;
  1807. // 重置GIF状态
  1808. /* this.showGif = false;
  1809. this.gifUrl = ''; */
  1810. // 重置当前字幕
  1811. this.currentSubtitle = '';
  1812. // 使用 nextTick 确保 DOM 更新后再播放视频
  1813. this.$nextTick(() => {
  1814. const videoContext = uni.createVideoContext('myVideo', this);
  1815. if (videoContext) {
  1816. videoContext.play();
  1817. }
  1818. });
  1819. } else {
  1820. // 所有视频都播放完毕,可以进行下一步操作
  1821. uni.showToast({
  1822. title: '面试完成',
  1823. icon: 'success',
  1824. duration: 2000
  1825. });
  1826. // 可以在这里添加面试完成后的逻辑,比如跳转到下一个页面
  1827. setTimeout(() => {
  1828. uni.navigateTo({
  1829. url: '/pages/interview-result/interview-result'
  1830. });
  1831. }, 2000);
  1832. }
  1833. },
  1834. // 修改 handleAnswerButtonClick 方法
  1835. handleAnswerButtonClick() {
  1836. // 隐藏答题按钮
  1837. this.showAnswerButton = false;
  1838. /* // 重置GIF状态
  1839. this.showGif = false;
  1840. this.gifUrl = ''; */
  1841. // 直接进入下一个问题
  1842. this.proceedToNextQuestion();
  1843. },
  1844. // 处理相机错误
  1845. handleCameraError(e) {
  1846. console.error('相机错误:', e);
  1847. // 获取平台信息
  1848. const systemInfo = uni.getSystemInfoSync();
  1849. const isIOS = systemInfo.platform === 'ios';
  1850. if (isIOS) {
  1851. console.log('iOS相机错误,尝试重新初始化');
  1852. // 显示提示
  1853. uni.showToast({
  1854. title: '相机初始化中...',
  1855. icon: 'loading',
  1856. duration: 2000
  1857. });
  1858. // 重置相机
  1859. this.resetCamera();
  1860. // 如果正在录制,停止录制
  1861. if (this.isRecording) {
  1862. this.isRecording = false;
  1863. this.showStopRecordingButton = false;
  1864. // 提供替代选项
  1865. setTimeout(() => {
  1866. this.useAlternativeRecordingMethod();
  1867. }, 1000);
  1868. }
  1869. } else {
  1870. // 显示错误提示
  1871. uni.showToast({
  1872. title: '相机初始化失败,请检查权限设置',
  1873. icon: 'none'
  1874. });
  1875. // 尝试备用选项
  1876. this.tryFallbackOptions();
  1877. }
  1878. },
  1879. // 添加新方法:尝试备用选项
  1880. tryFallbackOptions() {
  1881. // 检查环境
  1882. const systemInfo = uni.getSystemInfoSync();
  1883. // 在小程序环境中使用小程序API
  1884. if (systemInfo.uniPlatform === 'mp-weixin' || systemInfo.uniPlatform === 'mp-alipay') {
  1885. this.useMiniProgramCamera();
  1886. }
  1887. // 在H5环境中显示静态图像
  1888. else {
  1889. this.showStaticCameraPlaceholder();
  1890. }
  1891. },
  1892. // 添加新方法:使用小程序相机API
  1893. useMiniProgramCamera() {
  1894. console.log('尝试使用小程序相机组件');
  1895. // 这里需要在模板中添加小程序相机组件
  1896. // 并设置一个标志来控制显示
  1897. this.useMiniProgramCameraComponent = true;
  1898. },
  1899. // 添加新方法:显示静态图像
  1900. showStaticCameraPlaceholder() {
  1901. console.log('显示静态摄像头占位图');
  1902. // 创建一个图像元素
  1903. const img = document.createElement('img');
  1904. img.src = '/static/images/camera-placeholder.png'; // 确保有这个图片资源
  1905. img.className = 'static-camera-image';
  1906. img.style.width = '100%';
  1907. img.style.height = '100%';
  1908. img.style.objectFit = 'cover';
  1909. // 获取容器并添加图像
  1910. const container = this.$refs.userCameraVideo.parentNode;
  1911. container.appendChild(img);
  1912. },
  1913. // 处理视频时间更新事件
  1914. handleTimeUpdate(e) {
  1915. // 获取当前视频播放时间
  1916. const currentTime = e.target.currentTime;
  1917. // 如果正在录制,更新录制时间显示
  1918. if (this.isRecording && this.recordingTimerCount) {
  1919. this.recordingTimeDisplay = this.formatTime(this.recordingTimerCount);
  1920. }
  1921. // 如果正在播放低分提示视频,使用专门的字幕数组
  1922. if (this.isPlayingLowScoreVideo) {
  1923. if (this.lowScoreVideoSubtitles) {
  1924. const subtitle = this.lowScoreVideoSubtitles.find(
  1925. sub => currentTime >= sub.startTime && currentTime < sub.endTime
  1926. );
  1927. this.currentSubtitle = subtitle ? subtitle.text : '';
  1928. }
  1929. return;
  1930. }
  1931. // 以下是原有的字幕处理逻辑
  1932. // 根据当前播放的视频索引选择对应的字幕数组
  1933. let currentSubtitles;
  1934. if (this.currentVideoIndex === 0) {
  1935. currentSubtitles = this.subtitles;
  1936. } else {
  1937. // 动态获取字幕数组
  1938. const subtitleArrayName = `question${this.currentVideoIndex}Subtitles`;
  1939. currentSubtitles = this[subtitleArrayName] || [];
  1940. }
  1941. // 查找当前时间应该显示的字幕
  1942. const subtitle = currentSubtitles.find(
  1943. sub => currentTime >= sub.startTime && currentTime < sub.endTime
  1944. );
  1945. // 更新当前字幕
  1946. this.currentSubtitle = subtitle ? subtitle.text : '';
  1947. },
  1948. // Add a new method to handle the "Start Recording" button click
  1949. handleStartRecordingClick() {
  1950. // 隐藏"开始回答"按钮
  1951. this.showStartRecordingButton = false;
  1952. // 如果倒计时正在进行,清除倒计时
  1953. this.clearCountdown();
  1954. // 直接开始录制
  1955. this.startRecordingAnswer();
  1956. },
  1957. // 修改 checkAudioPermission 方法,确保在录制前获取音频权限
  1958. checkAudioPermission() {
  1959. // 在小程序环境中
  1960. const systemInfo = uni.getSystemInfoSync();
  1961. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
  1962. if (isMiniProgram) {
  1963. // 小程序环境下的权限请求
  1964. uni.getSetting({
  1965. success: (res) => {
  1966. if (!res.authSetting['scope.record']) {
  1967. uni.authorize({
  1968. scope: 'scope.record',
  1969. success: () => {
  1970. console.log('录音权限已获取');
  1971. },
  1972. fail: (err) => {
  1973. console.error('录音权限获取失败:', err);
  1974. this.showPermissionDialog('录音');
  1975. }
  1976. });
  1977. }
  1978. if (!res.authSetting['scope.camera']) {
  1979. uni.authorize({
  1980. scope: 'scope.camera',
  1981. success: () => {
  1982. console.log('相机权限已获取');
  1983. },
  1984. fail: (err) => {
  1985. console.error('相机权限获取失败:', err);
  1986. this.showPermissionDialog('相机');
  1987. }
  1988. });
  1989. }
  1990. }
  1991. });
  1992. } else {
  1993. // 浏览器环境下的权限请求
  1994. // ... 保持原有代码不变
  1995. }
  1996. },
  1997. // 添加新方法:测试音频输入
  1998. testAudioInput() {
  1999. if (!this.cameraStream) {
  2000. console.warn('没有可用的媒体流,无法测试音频');
  2001. return;
  2002. }
  2003. const audioTracks = this.cameraStream.getAudioTracks();
  2004. if (audioTracks.length === 0) {
  2005. console.warn('没有检测到音频轨道,尝试重新获取');
  2006. this.tryGetAudioOnly();
  2007. return;
  2008. }
  2009. console.log('音频轨道信息:', audioTracks[0].getSettings());
  2010. // 创建音频上下文和分析器
  2011. try {
  2012. const AudioContext = window.AudioContext || window.webkitAudioContext;
  2013. if (!AudioContext) {
  2014. console.warn('浏览器不支持AudioContext');
  2015. return;
  2016. }
  2017. const audioContext = new AudioContext();
  2018. const analyser = audioContext.createAnalyser();
  2019. const microphone = audioContext.createMediaStreamSource(this.cameraStream);
  2020. microphone.connect(analyser);
  2021. // 设置分析器
  2022. analyser.fftSize = 256;
  2023. const bufferLength = analyser.frequencyBinCount;
  2024. const dataArray = new Uint8Array(bufferLength);
  2025. // 检测音频输入
  2026. let silenceCounter = 0;
  2027. const checkAudio = () => {
  2028. if (this.isRecording) return; // 如果正在录制,停止检测
  2029. analyser.getByteFrequencyData(dataArray);
  2030. // 计算平均音量
  2031. let sum = 0;
  2032. for (let i = 0; i < bufferLength; i++) {
  2033. sum += dataArray[i];
  2034. }
  2035. const average = sum / bufferLength;
  2036. if (average > 10) {
  2037. console.log('检测到音频输入,音量:', average);
  2038. silenceCounter = 0;
  2039. } else {
  2040. silenceCounter++;
  2041. if (silenceCounter > 10) {
  2042. console.warn('持续检测不到音频输入,可能麦克风未正常工作');
  2043. silenceCounter = 0;
  2044. }
  2045. }
  2046. // 继续检测
  2047. requestAnimationFrame(checkAudio);
  2048. };
  2049. // 开始检测
  2050. checkAudio();
  2051. } catch (e) {
  2052. console.error('音频测试失败:', e);
  2053. }
  2054. },
  2055. // 添加新方法:尝试单独获取音频
  2056. tryGetAudioOnly() {
  2057. navigator.mediaDevices.getUserMedia({ audio: true })
  2058. .then(audioStream => {
  2059. // 如果已有视频流,合并音频和视频轨道
  2060. if (this.cameraStream) {
  2061. const videoTrack = this.cameraStream.getVideoTracks()[0];
  2062. const audioTrack = audioStream.getAudioTracks()[0];
  2063. // 创建新的媒体流,包含视频和音频轨道
  2064. const combinedStream = new MediaStream();
  2065. if (videoTrack) combinedStream.addTrack(videoTrack);
  2066. if (audioTrack) combinedStream.addTrack(audioTrack);
  2067. // 更新摄像头流
  2068. this.cameraStream = combinedStream;
  2069. // 更新视频元素的源
  2070. const videoElement = this.$refs.userCameraVideo;
  2071. if (videoElement) {
  2072. videoElement.srcObject = combinedStream;
  2073. videoElement.muted = true; // 避免回声,但仍然录制声音
  2074. }
  2075. console.log('成功合并音频和视频轨道');
  2076. } else {
  2077. console.warn('没有视频流可合并');
  2078. }
  2079. })
  2080. .catch(err => {
  2081. console.error('单独获取音频失败:', err);
  2082. });
  2083. },
  2084. // 添加新方法:显示权限对话框
  2085. showPermissionDialog(permissionType) {
  2086. uni.showModal({
  2087. title: '需要权限',
  2088. content: `请允许使用${permissionType}权限,否则可能影响面试功能`,
  2089. confirmText: '去设置',
  2090. success: (res) => {
  2091. if (res.confirm) {
  2092. uni.openSetting({
  2093. success: (settingRes) => {
  2094. console.log('设置页面打开成功', settingRes);
  2095. }
  2096. });
  2097. }
  2098. }
  2099. });
  2100. },
  2101. // 添加重试上传方法
  2102. retryVideoUpload() {
  2103. if (this.lastVideoToRetry) {
  2104. // 隐藏重试按钮
  2105. this.showRetryButton = false;
  2106. // 显示加载提示
  2107. uni.showLoading({
  2108. title: '正在重新提交...',
  2109. mask: true
  2110. });
  2111. // 重新提交视频
  2112. this.submitVideoToInterview(this.lastVideoToRetry);
  2113. } else {
  2114. uni.showToast({
  2115. title: '没有可重试的视频',
  2116. icon: 'none'
  2117. });
  2118. }
  2119. },
  2120. // 添加一个新方法用于压缩视频
  2121. async compressVideo(videoBlob) {
  2122. // 如果视频大小小于某个阈值,直接返回原视频
  2123. if (videoBlob.size < 5 * 1024 * 1024) { // 小于5MB
  2124. return videoBlob;
  2125. }
  2126. console.log('开始压缩视频,原始大小:', videoBlob.size);
  2127. // 创建一个视频元素来加载视频
  2128. const videoElement = document.createElement('video');
  2129. videoElement.muted = true;
  2130. videoElement.autoplay = false;
  2131. // 创建一个canvas元素用于绘制视频帧
  2132. const canvas = document.createElement('canvas');
  2133. const ctx = canvas.getContext('2d');
  2134. // 设置视频源
  2135. videoElement.src = URL.createObjectURL(videoBlob);
  2136. return new Promise((resolve) => {
  2137. videoElement.onloadedmetadata = () => {
  2138. // 设置canvas尺寸为视频的一半
  2139. const width = Math.floor(videoElement.videoWidth / 2);
  2140. const height = Math.floor(videoElement.videoHeight / 2);
  2141. canvas.width = width;
  2142. canvas.height = height;
  2143. // 创建MediaRecorder来录制canvas
  2144. const stream = canvas.captureStream(15); // 15fps
  2145. // 如果原视频有音轨,添加到新流中
  2146. if (videoElement.captureStream) {
  2147. const originalStream = videoElement.captureStream();
  2148. const audioTracks = originalStream.getAudioTracks();
  2149. if (audioTracks.length > 0) {
  2150. stream.addTrack(audioTracks[0]);
  2151. }
  2152. }
  2153. // 设置较低的比特率
  2154. const options = {
  2155. mimeType: 'video/webm;codecs=vp8,opus',
  2156. audioBitsPerSecond: 64000,
  2157. videoBitsPerSecond: 800000 // 800kbps
  2158. };
  2159. const mediaRecorder = new MediaRecorder(stream, options);
  2160. const chunks = [];
  2161. mediaRecorder.ondataavailable = (e) => {
  2162. if (e.data.size > 0) {
  2163. chunks.push(e.data);
  2164. }
  2165. };
  2166. mediaRecorder.onstop = () => {
  2167. const compressedBlob = new Blob(chunks, { type: 'video/webm' });
  2168. console.log('视频压缩完成,压缩后大小:', compressedBlob.size);
  2169. resolve(compressedBlob);
  2170. };
  2171. // 开始播放视频并录制
  2172. videoElement.onplay = () => {
  2173. mediaRecorder.start(100);
  2174. // 绘制视频帧到canvas
  2175. const drawFrame = () => {
  2176. if (videoElement.paused || videoElement.ended) {
  2177. mediaRecorder.stop();
  2178. return;
  2179. }
  2180. ctx.drawImage(videoElement, 0, 0, width, height);
  2181. requestAnimationFrame(drawFrame);
  2182. };
  2183. drawFrame();
  2184. };
  2185. videoElement.play();
  2186. };
  2187. });
  2188. },
  2189. // 修改 checkIOSCameraRecordPermission 方法
  2190. checkIOSCameraRecordPermission() {
  2191. const systemInfo = uni.getSystemInfoSync();
  2192. if (systemInfo.platform !== 'ios') return;
  2193. // 在iOS上,需要同时请求相机和录音权限
  2194. uni.getSetting({
  2195. success: (res) => {
  2196. // 检查相机权限
  2197. if (!res.authSetting['scope.camera']) {
  2198. uni.authorize({
  2199. scope: 'scope.camera',
  2200. success: () => {
  2201. console.log('iOS相机权限已获取');
  2202. },
  2203. fail: (err) => {
  2204. console.error('iOS相机权限获取失败:', err);
  2205. this.showPermissionDialog('相机');
  2206. }
  2207. });
  2208. }
  2209. // 检查录音权限
  2210. if (!res.authSetting['scope.record']) {
  2211. uni.authorize({
  2212. scope: 'scope.record',
  2213. success: () => {
  2214. console.log('iOS录音权限已获取');
  2215. },
  2216. fail: (err) => {
  2217. console.error('iOS录音权限获取失败:', err);
  2218. this.showPermissionDialog('录音');
  2219. }
  2220. });
  2221. }
  2222. }
  2223. });
  2224. },
  2225. // 添加新方法:检查并修复渲染问题
  2226. checkAndFixRenderingIssues() {
  2227. // 检查全局对象,防止渲染错误
  2228. try {
  2229. // 检查是否有全局变量u
  2230. if (typeof u !== 'undefined' && u) {
  2231. // 检查currentQuestion属性
  2232. if (!u.currentQuestion) {
  2233. console.log('修复: 创建缺失的currentQuestion对象');
  2234. u.currentQuestion = {};
  2235. }
  2236. // 确保isImportant属性存在
  2237. if (u.currentQuestion && typeof u.currentQuestion.isImportant === 'undefined') {
  2238. console.log('修复: 设置缺失的isImportant属性');
  2239. u.currentQuestion.isImportant = false;
  2240. }
  2241. }
  2242. } catch (e) {
  2243. console.log('防御性检查异常:', e);
  2244. }
  2245. },
  2246. // 添加格式化时间的辅助方法
  2247. formatTime(seconds) {
  2248. if (!seconds && seconds !== 0) return '03:30'; // 默认显示03:30
  2249. const minutes = Math.floor(seconds / 60);
  2250. const remainingSeconds = seconds % 60;
  2251. return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
  2252. },
  2253. // 添加获取问题数据的方法
  2254. fetchQuestions() {
  2255. this.loading = true;
  2256. // 获取tenant_id,如果没有则使用默认值1
  2257. const tenant_id = JSON.parse(uni.getStorageSync('userInfo')).tenant_id || '1';
  2258. // 获取当前选择的职位ID
  2259. let position_id = 1; // 默认值
  2260. try {
  2261. const selectedJob = JSON.parse(uni.getStorageSync('selectedJob') || '{}');
  2262. if (selectedJob && selectedJob.id) {
  2263. position_id = selectedJob.id;
  2264. console.log('使用选择的职位ID获取问题:', position_id);
  2265. } else {
  2266. console.warn('未找到选择的职位信息,使用默认职位ID:', position_id);
  2267. }
  2268. } catch (e) {
  2269. console.error('解析职位信息失败:', e);
  2270. }
  2271. // 构建完整的请求URL,便于调试
  2272. const timestamp = Date.now();
  2273. const requestUrl = `${apiBaseUrl}/api/wechat/open_questions/?position_id=${position_id}&tenant_id=${tenant_id}&question_form=0&_t=${timestamp}`;
  2274. console.log('完整的请求URL:', requestUrl);
  2275. uni.request({
  2276. url: requestUrl,
  2277. method: 'GET',
  2278. success: (res) => {
  2279. if (res.data && res.data.code === 2000 && res.data.data && res.data.data.items) {
  2280. console.log('获取问题数据成功:', res.data.data.items);
  2281. // 存储问题数据
  2282. this.questions = res.data.data.items;
  2283. // 处理视频列表和字幕
  2284. this.processQuestionData();
  2285. // 播放介绍视频
  2286. this.playIntroVideo();
  2287. } else {
  2288. console.error('获取问题数据失败:', res.data);
  2289. uni.showToast({
  2290. title: '获取问题数据失败',
  2291. icon: 'none'
  2292. });
  2293. /* // 使用默认视频和字幕
  2294. this.useDefaultVideosAndSubtitles(); */
  2295. }
  2296. },
  2297. fail: (err) => {
  2298. console.error('请求问题数据失败:', err);
  2299. uni.showToast({
  2300. title: '网络错误,请检查网络连接',
  2301. icon: 'none'
  2302. });
  2303. /* // 使用默认视频和字幕
  2304. this.useDefaultVideosAndSubtitles(); */
  2305. },
  2306. complete: () => {
  2307. this.loading = false;
  2308. }
  2309. });
  2310. },
  2311. // 处理问题数据,提取视频URL和字幕
  2312. processQuestionData() {
  2313. // 清空视频列表和字幕
  2314. this.videoList = [];
  2315. // 首先添加介绍视频
  2316. this.videoList.push(this.introVideoUrl);
  2317. // 为介绍视频设置字幕
  2318. this.subtitles = [
  2319. {
  2320. startTime: 0,
  2321. endTime: 5,
  2322. text: '你好,我是本次面试的面试官,欢迎参加本公司的线上面试!'
  2323. },
  2324. {
  2325. startTime: 5,
  2326. endTime: 13,
  2327. text: '面试预计需要15分钟,请你提前安排在网络良好、光线亮度合适、且相对安静的环境参加这次面试'
  2328. },
  2329. {
  2330. startTime: 13,
  2331. endTime: 20,
  2332. text: '以免影响本次面试的结果。如果你在面试过程中遇到问题,请与我们的招聘人员联系。'
  2333. }
  2334. ];
  2335. // 按照sequence_number排序问题
  2336. const sortedQuestions = [...this.questions].sort((a, b) => a.sequence_number - b.sequence_number);
  2337. // 只处理前5个问题(或者更少,如果问题总数不足5个)
  2338. const questionsToUse = sortedQuestions.slice(0, 5);
  2339. // 为每个问题添加视频URL和字幕
  2340. questionsToUse.forEach(question => {
  2341. // 如果有视频URL,添加到视频列表
  2342. if (question.digital_human_video_url) {
  2343. this.videoList.push(question.digital_human_video_url);
  2344. // 为这个问题创建字幕数组
  2345. const subtitleArray = [{
  2346. startTime: 0,
  2347. endTime: 10, // 默认10秒,可以根据实际情况调整
  2348. text: question.digital_human_video_subtitle || question.question
  2349. }];
  2350. // 根据问题的序号存储字幕
  2351. const index = this.videoList.length - 1; // 减1是因为我们已经添加了视频URL
  2352. // 动态创建字幕数组属性
  2353. this[`question${index}Subtitles`] = subtitleArray;
  2354. }
  2355. });
  2356. // 如果没有获取到任何问题视频,使用默认视频
  2357. if (this.videoList.length <= 1) {
  2358. /* this.useDefaultVideosAndSubtitles(); */
  2359. } else {
  2360. console.log('处理后的视频列表:', this.videoList);
  2361. console.log('处理后的字幕:', this.subtitles);
  2362. }
  2363. },
  2364. // 使用默认视频和字幕(作为备用)
  2365. useDefaultVideosAndSubtitles() {
  2366. console.log('使用默认视频和字幕');
  2367. // 设置默认视频列表
  2368. /* this.videoList = [
  2369. this.introVideoUrl, // 介绍视频
  2370. 'http://121.36.251.245:9000/minlong/tenant_1/general_uploads/e465e23d377b4456bbb3b755d3ad9500.mp4',
  2371. 'http://121.36.251.245:9000/minlong/tenant_1/general_uploads/9bc84230d2a14978b4ea0a97e4102a15.mp4',
  2372. 'http://121.36.251.245:9000/minlong/tenant_1/general_uploads/9b48e824432f451d9e27e12b884d9074.mp4',
  2373. 'http://121.36.251.245:9000/minlong/tenant_1/general_uploads/52f1445b400345e1a673b3c7f05e5cc1.mp4',
  2374. 'http://121.36.251.245:9000/minlong/tenant_1/general_uploads/abdaa6fda8494e3a8613304743ed0433.mp4'
  2375. ]; */
  2376. // 设置默认字幕
  2377. this.subtitles = [
  2378. {
  2379. startTime: 0,
  2380. endTime: 5,
  2381. text: '你好,我是本次面试的面试官,欢迎参加本公司的线上面试!'
  2382. },
  2383. {
  2384. startTime: 5,
  2385. endTime: 13,
  2386. text: '面试预计需要15分钟,请你提前安排在网络良好、光线亮度合适、且相对安静的环境参加这次面试'
  2387. },
  2388. {
  2389. startTime: 13,
  2390. endTime: 20,
  2391. text: '以免影响本次面试的结果。如果你在面试过程中遇到问题,请与我们的招聘人员联系。'
  2392. }
  2393. ];
  2394. // 设置默认问题字幕
  2395. this.question1Subtitles = [{
  2396. startTime: 0,
  2397. endTime: 10,
  2398. text: '请结合您的基本信息与过往履历进行简单的自我介绍,并讲一讲您有哪些优势胜任本岗位:'
  2399. }];
  2400. this.question2Subtitles = [{
  2401. startTime: 0,
  2402. endTime: 4,
  2403. text: '在工作中,你如何确保个人防护装备的正确使用?'
  2404. }];
  2405. this.question3Subtitles = [{
  2406. startTime: 0,
  2407. endTime: 4,
  2408. text: '描述一次你与团队合作改善生产流程的经历。'
  2409. }];
  2410. this.question4Subtitles = [{
  2411. startTime: 0,
  2412. endTime: 6,
  2413. text: '你在团队合作中曾遇到过哪些挑战?如何解决团队内部的分歧?'
  2414. }];
  2415. this.question5Subtitles = [{
  2416. startTime: 0,
  2417. endTime: 5,
  2418. text: '您已完成本次面试全部题目,请问您对于这个岗位还有什么想要了解的吗?'
  2419. }];
  2420. },
  2421. // 播放介绍视频
  2422. playIntroVideo() {
  2423. // 设置第一个视频(介绍视频)
  2424. this.videoUrl = this.videoList[0];
  2425. this.videoPlaying = true;
  2426. this.$nextTick(() => {
  2427. const videoContext = uni.createVideoContext('myVideo', this);
  2428. if (videoContext) {
  2429. videoContext.play();
  2430. }
  2431. });
  2432. },
  2433. // 添加新方法:获取默认问题ID
  2434. getDefaultQuestionId(videoIndex) {
  2435. // 根据视频索引映射到默认问题ID
  2436. switch(videoIndex) {
  2437. case 1: // 第一个问题
  2438. return 10;
  2439. case 2: // 第二个问题
  2440. return 11;
  2441. case 3: // 第三个问题
  2442. return 12;
  2443. case 4: // 第四个问题
  2444. return 13;
  2445. default:
  2446. return 10; // 默认值
  2447. }
  2448. },
  2449. // 添加新方法:根据索引获取当前问题
  2450. getCurrentQuestionByIndex(videoIndex) {
  2451. // 视频索引减1,因为第一个视频是介绍视频
  2452. const questionIndex = videoIndex - 1;
  2453. // 按照sequence_number排序问题
  2454. const sortedQuestions = [...this.questions].sort((a, b) => a.sequence_number - b.sequence_number);
  2455. // 检查索引是否有效
  2456. if (questionIndex >= 0 && questionIndex < sortedQuestions.length) {
  2457. return sortedQuestions[questionIndex];
  2458. }
  2459. return null;
  2460. },
  2461. onShow() {
  2462. console.log('identity-verify页面onShow');
  2463. console.log('当前本地存储中的职位信息:', uni.getStorageSync('selectedJob'));
  2464. // 每次页面显示时重新获取问题
  2465. this.fetchQuestions();
  2466. },
  2467. // 添加新方法:连接WebSocket获取分析结果
  2468. connectToWebSocketForAnalysis(questionId, videoUrl) {
  2469. console.log('使用已有的 WebSocket 连接发送分析请求');
  2470. // 如果没有全局 WebSocket 连接,则创建一个
  2471. if (!this.globalSocketTask) {
  2472. console.log('全局 WebSocket 连接不存在,重新初始化');
  2473. this.initWebSocketConnection();
  2474. // 延迟发送,确保连接已建立
  2475. setTimeout(() => {
  2476. this.sendAnalysisRequest(questionId, videoUrl);
  2477. }, 1000);
  2478. } else {
  2479. // 直接使用已有连接发送请求
  2480. this.sendAnalysisRequest(questionId, videoUrl);
  2481. }
  2482. },
  2483. // 添加新方法:发送分析请求
  2484. sendAnalysisRequest(questionId, videoUrl) {
  2485. // 如果 WebSocket 连接已打开,发送分析请求
  2486. if (this.globalSocketTask && this.globalSocketTask.readyState === 1) {
  2487. // 构建请求数据
  2488. const requestData = {
  2489. type: 'start_analysis',
  2490. question_id: questionId,
  2491. video_url: videoUrl
  2492. };
  2493. // 发送请求
  2494. this.globalSocketTask.send({
  2495. data: JSON.stringify(requestData),
  2496. success: () => {
  2497. console.log('分析请求发送成功');
  2498. },
  2499. fail: (err) => {
  2500. console.error('分析请求发送失败:', err);
  2501. // 发送失败时,继续下一个问题
  2502. this.proceedToNextQuestion();
  2503. }
  2504. });
  2505. } else {
  2506. console.error('WebSocket 连接未打开,无法发送分析请求');
  2507. // 连接未打开时,继续下一个问题
  2508. this.proceedToNextQuestion();
  2509. }
  2510. },
  2511. // 添加新方法:重置录制状态,准备重新回答
  2512. resetForRerecording() {
  2513. console.log('重置录制状态,准备重新回答');
  2514. // 重置录制状态
  2515. this.isRecording = false;
  2516. this.showStopRecordingButton = false;
  2517. // 显示"开始回答"按钮
  2518. this.showStartRecordingButton = true;
  2519. // 清除倒计时
  2520. this.clearCountdown();
  2521. // 重置录制计时器
  2522. if (this.recordingTimer) {
  2523. clearInterval(this.recordingTimer);
  2524. this.recordingTimer = null;
  2525. }
  2526. // 重置录制时间显示
  2527. this.recordingTimerCount = 0;
  2528. this.recordingTimeDisplay = '00:00 / 05:00';
  2529. this.remainingTime = this.maxRecordingTime;
  2530. // 如果是浏览器环境,停止MediaRecorder
  2531. if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
  2532. this.mediaRecorder.stop();
  2533. this.recordedChunks = [];
  2534. }
  2535. // 如果是小程序环境,停止相机录制
  2536. if (this.cameraContext) {
  2537. this.cameraContext.stopRecord({
  2538. success: () => {
  2539. console.log('相机录制已停止');
  2540. },
  2541. fail: (err) => {
  2542. console.error('停止相机录制失败:', err);
  2543. }
  2544. });
  2545. }
  2546. },
  2547. // 添加新方法:初始化 WebSocket 连接
  2548. initWebSocketConnection() {
  2549. console.log('初始化 WebSocket 连接');
  2550. // 获取 appId
  2551. const appId = uni.getStorageSync('appId') || '98'; // 使用默认值 98,如图中所示
  2552. console.log('使用 appId:', appId);
  2553. // 获取 tenant_id
  2554. const tenant_id = JSON.parse(uni.getStorageSync('userInfo')).tenant_id || '1';
  2555. // 从 apiBaseUrl 构建 WebSocket URL
  2556. // 将 http:// 或 https:// 替换为 ws:// 或 wss://
  2557. let wsBaseUrl = apiBaseUrl.replace(/^http/, 'ws');
  2558. // 构建完整的 WebSocket URL
  2559. const wsUrl = `${wsBaseUrl}/ws/video_analysis/${appId}/`;
  2560. console.log('WebSocket URL:', wsUrl);
  2561. // 创建 WebSocket 连接
  2562. this.globalSocketTask = uni.connectSocket({
  2563. url: wsUrl,
  2564. success: () => {
  2565. console.log('WebSocket 连接成功');
  2566. },
  2567. fail: (err) => {
  2568. console.error('WebSocket 连接失败:', err);
  2569. }
  2570. });
  2571. // 监听 WebSocket 连接打开
  2572. this.globalSocketTask.onOpen(() => {
  2573. console.log('WebSocket 连接已打开');
  2574. });
  2575. // 监听 WebSocket 接收到服务器的消息
  2576. this.globalSocketTask.onMessage((res) => {
  2577. console.log('收到 WebSocket 消息:', res.data);
  2578. try {
  2579. // 解析消息数据
  2580. const data = JSON.parse(res.data);
  2581. // 检查是否是分析完成的消息
  2582. if (data.type === 'analysis_complete') {
  2583. // 检查 overall_score 是否小于 10
  2584. const overallScore = data.data && data.data.answer_status;
  2585. console.log('分析完成,得分:', overallScore);
  2586. if (overallScore == 1) {
  2587. console.log(`得分较低,检查重试次数 (当前: ${this.retryCount}/${this.maxRetryAttempts})`);
  2588. // 检查是否已经达到最大重试次数
  2589. if (this.retryCount >= this.maxRetryAttempts) {
  2590. console.log('已达到最大重试次数,直接进入下一题');
  2591. // 重置重试次数并继续下一题
  2592. this.retryCount = 0;
  2593. this.proceedToNextQuestion();
  2594. } else {
  2595. // 还有重试机会,播放提示视频
  2596. this.playLowScoreVideo();
  2597. }
  2598. } else {
  2599. console.log('得分正常,继续下一个问题');
  2600. // 重置重试次数并继续下一题
  2601. this.retryCount = 0;
  2602. this.proceedToNextQuestion();
  2603. }
  2604. }
  2605. } catch (e) {
  2606. console.error('解析 WebSocket 消息失败:', e);
  2607. }
  2608. });
  2609. // 监听 WebSocket 错误
  2610. this.globalSocketTask.onError((err) => {
  2611. console.error('WebSocket 错误:', err);
  2612. });
  2613. // 监听 WebSocket 连接关闭
  2614. this.globalSocketTask.onClose(() => {
  2615. console.log('WebSocket 连接已关闭');
  2616. // 可以在这里添加重连逻辑
  2617. setTimeout(() => {
  2618. this.initWebSocketConnection();
  2619. }, 5000);
  2620. });
  2621. },
  2622. // 修改 playLowScoreVideo 方法,优化字幕显示
  2623. playLowScoreVideo() {
  2624. console.log('播放低分提示视频');
  2625. // 标记正在播放低分提示视频
  2626. this.isPlayingLowScoreVideo = true;
  2627. // 隐藏其他按钮
  2628. this.showStartRecordingButton = false;
  2629. this.showStopRecordingButton = false;
  2630. this.showRerecordButton = false;
  2631. // 设置视频URL
  2632. this.videoUrl = this.lowScoreVideoUrl;
  2633. this.videoPlaying = true;
  2634. // 清除现有字幕
  2635. this.currentSubtitle = '';
  2636. // 使用 nextTick 确保 DOM 更新后再播放视频
  2637. this.$nextTick(() => {
  2638. const videoContext = uni.createVideoContext('myVideo', this);
  2639. if (videoContext) {
  2640. videoContext.play();
  2641. // 视频开始播放后短暂延迟显示字幕,确保用户注意到
  2642. setTimeout(() => {
  2643. // 设置低分提示视频的字幕
  2644. this.currentSubtitle = '我未听清楚您在说什么,请您再说一遍!';
  2645. // 创建专门的字幕数组用于低分提示视频
  2646. this.lowScoreVideoSubtitles = [
  2647. {
  2648. startTime: 0,
  2649. endTime: 10, // 假设视频长度为10秒,可根据实际情况调整
  2650. text: '我未听清楚您在说什么,请您再说一遍!'
  2651. }
  2652. ];
  2653. }, 500);
  2654. }
  2655. });
  2656. },
  2657. // 添加新方法:处理重新录制按钮点击
  2658. handleRerecordButtonClick() {
  2659. console.log('点击重新录制按钮');
  2660. // 增加重试计数
  2661. this.retryCount++;
  2662. console.log(`当前重试次数: ${this.retryCount}/${this.maxRetryAttempts}`);
  2663. // 隐藏重新录制按钮
  2664. this.showRerecordButton = false;
  2665. // 直接调用开始录制的方法
  2666. this.handleStartRecordingClick();
  2667. },
  2668. // 添加新方法:关闭 WebSocket 连接
  2669. closeWebSocketConnection() {
  2670. if (this.globalSocketTask) {
  2671. console.log('关闭 WebSocket 连接');
  2672. // 发送关闭消息给服务器
  2673. try {
  2674. this.globalSocketTask.send({
  2675. data: JSON.stringify({ type: 'client_disconnect' }),
  2676. fail: () => {
  2677. console.log('发送断开连接消息失败');
  2678. }
  2679. });
  2680. } catch (e) {
  2681. console.error('发送断开连接消息异常:', e);
  2682. }
  2683. // 关闭连接
  2684. this.globalSocketTask.close({
  2685. code: 1000,
  2686. reason: 'User left the page',
  2687. success: () => {
  2688. console.log('WebSocket 连接已成功关闭');
  2689. },
  2690. fail: (err) => {
  2691. console.error('WebSocket 连接关闭失败:', err);
  2692. },
  2693. complete: () => {
  2694. this.globalSocketTask = null;
  2695. }
  2696. });
  2697. }
  2698. },
  2699. // 添加 onUnload 生命周期钩子,确保在页面卸载时关闭连接
  2700. onUnload() {
  2701. console.log('页面卸载,关闭 WebSocket 连接');
  2702. this.closeWebSocketConnection();
  2703. },
  2704. // 添加 onHide 生命周期钩子,在页面隐藏时也关闭连接
  2705. onHide() {
  2706. console.log('页面隐藏,关闭 WebSocket 连接');
  2707. this.closeWebSocketConnection();
  2708. }
  2709. }
  2710. }
  2711. </script>
  2712. <style scoped>
  2713. .identity-verify-container {
  2714. padding: 0;
  2715. max-width: 100%;
  2716. margin: 0 auto;
  2717. height: 100vh;
  2718. display: flex;
  2719. flex-direction: column;
  2720. background-color: #f5f5f5;
  2721. }
  2722. .digital-human-container {
  2723. position: relative;
  2724. width: 100%;
  2725. height: 100vh;
  2726. overflow: hidden;
  2727. background-color: #f0f0f0;
  2728. }
  2729. .digital-human-video {
  2730. width: 100%;
  2731. height: 100%;
  2732. display: flex;
  2733. justify-content: center;
  2734. align-items: center;
  2735. }
  2736. /* 用户摄像头容器样式 */
  2737. .user-camera-container {
  2738. position: absolute;
  2739. top: 50px;
  2740. right: 5px;
  2741. width: 110px; /* 稍微增加宽度 */
  2742. height: 160px; /* 稍微增加高度 */
  2743. border-radius: 4px; /* 减小圆角 */
  2744. overflow: hidden;
  2745. box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
  2746. z-index: 20;
  2747. }
  2748. /* 用户摄像头视频样式 */
  2749. .user-camera-video {
  2750. width: 100%;
  2751. height: 100%;
  2752. object-fit: cover;
  2753. background-color: #333;
  2754. }
  2755. .video-player {
  2756. width: 100%;
  2757. height: 100%;
  2758. object-fit: cover;
  2759. outline: none; /* 移除视频获得焦点时的轮廓 */
  2760. -webkit-tap-highlight-color: transparent; /* 移除移动设备上的点击高亮 */
  2761. }
  2762. /* 隐藏视频控制条 */
  2763. video::-webkit-media-controls {
  2764. display: none !important;
  2765. }
  2766. video::-webkit-media-controls-enclosure {
  2767. display: none !important;
  2768. }
  2769. video::-webkit-media-controls-panel {
  2770. display: none !important;
  2771. }
  2772. video::-webkit-media-controls-play-button {
  2773. display: none !important;
  2774. }
  2775. video::-webkit-media-controls-timeline {
  2776. display: none !important;
  2777. }
  2778. video::-webkit-media-controls-current-time-display {
  2779. display: none !important;
  2780. }
  2781. video::-webkit-media-controls-time-remaining-display {
  2782. display: none !important;
  2783. }
  2784. video::-webkit-media-controls-mute-button {
  2785. display: none !important;
  2786. }
  2787. video::-webkit-media-controls-volume-slider {
  2788. display: none !important;
  2789. }
  2790. video::-webkit-media-controls-fullscreen-button {
  2791. display: none !important;
  2792. }
  2793. /* 修改字幕覆盖层样式,使其与图片中的样式一致 */
  2794. .subtitle-overlay {
  2795. position: absolute;
  2796. bottom: 180px; /* 调整位置,使其更靠近底部 */
  2797. left: 5%; /* 从左侧留出5%的空间 */
  2798. width: 80%; /* 宽度设为90%,两侧各留5%实现居中 */
  2799. padding: 15px 20px; /* 增加左右内边距 */
  2800. border-radius: 15px;
  2801. background-color: rgba(255, 255, 255, 0.9); /* 白色半透明背景 */
  2802. color: #333; /* 文字颜色为深色 */
  2803. text-align: left; /* 文字左对齐 */
  2804. font-size: 16px;
  2805. line-height: 1.5;
  2806. z-index: 10;
  2807. margin: 0 auto; /* 添加自动边距实现居中 */
  2808. box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 添加轻微阴影 */
  2809. }
  2810. /* 添加计时器样式,右侧显示橙色圆点和时间 */
  2811. .subtitle-overlay::after {
  2812. content: attr(data-time);
  2813. position: absolute;
  2814. right: 20px;
  2815. bottom: 15px;
  2816. color: #333;
  2817. font-size: 14px;
  2818. }
  2819. .control-panel {
  2820. padding: 15px;
  2821. display: flex;
  2822. justify-content: center;
  2823. }
  2824. .control-button {
  2825. padding: 10px 20px;
  2826. background-color: #4CAF50;
  2827. color: white;
  2828. border: none;
  2829. border-radius: 4px;
  2830. cursor: pointer;
  2831. }
  2832. .loading {
  2833. text-align: center;
  2834. margin: 20px 0;
  2835. font-size: 16px;
  2836. }
  2837. .response-container {
  2838. margin-top: 20px;
  2839. padding: 0 20px;
  2840. display: none; /* 默认隐藏调试信息 */
  2841. }
  2842. /* 当showDebugInfo为true时显示 */
  2843. .showDebugInfo .response-container {
  2844. display: block;
  2845. }
  2846. .response-item {
  2847. padding: 10px;
  2848. border: 1px solid #eee;
  2849. border-radius: 4px;
  2850. margin-bottom: 10px;
  2851. background-color: #f9f9f9;
  2852. }
  2853. .response-content {
  2854. display: flex;
  2855. flex-direction: column;
  2856. }
  2857. .answer-button-container {
  2858. position: absolute;
  2859. bottom: 50px; /* 将按钮放在底部而不是75%的位置 */
  2860. left: 50%;
  2861. transform: translateX(-50%); /* 只在X轴上平移,保持水平居中 */
  2862. z-index: 20;
  2863. }
  2864. /* 修改回答按钮样式 */
  2865. .answer-button {
  2866. width: 120px;
  2867. height: 40px; /* 改为矩形按钮 */
  2868. border-radius: 20px; /* 圆角矩形 */
  2869. background-color: #ffffff; /* 白色背景 */
  2870. color: #333; /* 深色文字 */
  2871. font-size: 16px;
  2872. border: none;
  2873. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  2874. display: flex;
  2875. justify-content: center;
  2876. align-items: center;
  2877. cursor: pointer;
  2878. animation: none; /* 移除脉动动画 */
  2879. }
  2880. .stop-recording-button-container {
  2881. position: absolute;
  2882. bottom: 50px; /* 统一与其他按钮的位置 */
  2883. left: 50%;
  2884. transform: translateX(-50%);
  2885. z-index: 20;
  2886. }
  2887. .stop-recording-button {
  2888. width: 120px;
  2889. height: 40px; /* 改为矩形按钮 */
  2890. border-radius: 20px; /* 圆角矩形 */
  2891. background-color: #e74c3c; /* 白色背景 */
  2892. color: #333; /* 深色文字 */
  2893. font-size: 16px;
  2894. border: none;
  2895. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  2896. display: flex;
  2897. justify-content: center;
  2898. align-items: center;
  2899. cursor: pointer;
  2900. animation: none; /* 移除脉动动画 */
  2901. }
  2902. .recording-indicator {
  2903. position: absolute;
  2904. top: 20px;
  2905. left: 20px;
  2906. display: flex;
  2907. align-items: center;
  2908. background-color: rgba(255, 255, 255, 0.9); /* 改为白色半透明背景 */
  2909. padding: 5px 10px;
  2910. border-radius: 15px;
  2911. z-index: 20;
  2912. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  2913. }
  2914. .recording-dot {
  2915. width: 12px;
  2916. height: 12px;
  2917. background-color: #ff6b00; /* 改为橙色,与图片中的颜色一致 */
  2918. border-radius: 50%;
  2919. margin-right: 8px;
  2920. animation: blink 1s infinite;
  2921. }
  2922. .recording-text {
  2923. color: #333; /* 改为深色文字 */
  2924. font-size: 14px;
  2925. }
  2926. .timer-text {
  2927. color: #333; /* 改为深色文字 */
  2928. font-size: 14px;
  2929. margin-left: 8px;
  2930. }
  2931. .start-recording-button-container {
  2932. position: absolute;
  2933. bottom: 50px; /* 统一与其他按钮的位置 */
  2934. left: 50%;
  2935. transform: translateX(-50%);
  2936. z-index: 101;
  2937. }
  2938. .start-recording-button {
  2939. width: 120px;
  2940. height: 40px; /* 改为矩形按钮 */
  2941. border-radius: 20px; /* 圆角矩形 */
  2942. background-color: #ffffff; /* 白色背景 */
  2943. color: #333; /* 深色文字 */
  2944. font-size: 16px;
  2945. border: none;
  2946. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  2947. display: flex;
  2948. justify-content: center;
  2949. align-items: center;
  2950. cursor: pointer;
  2951. animation: none; /* 移除脉动动画 */
  2952. }
  2953. .retry-button-container {
  2954. position: absolute;
  2955. bottom: 30px; /* 统一与其他按钮的位置 */
  2956. left: 50%;
  2957. transform: translateX(-50%);
  2958. z-index: 20;
  2959. }
  2960. .retry-button {
  2961. padding: 10px 20px;
  2962. background-color: #ffffff; /* 白色背景 */
  2963. color: #333; /* 深色文字 */
  2964. font-size: 16px;
  2965. border: none;
  2966. border-radius: 20px; /* 圆角矩形 */
  2967. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  2968. cursor: pointer;
  2969. }
  2970. .retry-button:hover {
  2971. background-color: #2980b9;
  2972. }
  2973. /* 录制时长显示 */
  2974. .recording-timer {
  2975. position: absolute;
  2976. top: 20px;
  2977. left: 130px; /* 放在录制指示器旁边 */
  2978. background-color: rgba(0, 0, 0, 0.6);
  2979. padding: 5px 10px;
  2980. border-radius: 15px;
  2981. z-index: 20;
  2982. display: flex;
  2983. flex-direction: column;
  2984. }
  2985. .timer-text {
  2986. color: #000;
  2987. font-size: 14px;
  2988. font-family: monospace; /* 使用等宽字体,使时间显示更稳定 */
  2989. }
  2990. .remaining-time {
  2991. color: white;
  2992. font-size: 12px;
  2993. margin-top: 2px;
  2994. }
  2995. .remaining-time.warning {
  2996. color: #ff6b6b; /* 剩余时间少时显示红色 */
  2997. animation: blink 1s infinite; /* 使用闪烁动画提醒用户 */
  2998. }
  2999. /* 添加上传状态指示器 */
  3000. .upload-status-indicator {
  3001. position: absolute;
  3002. top: 20px;
  3003. left: 130px; /* 放在录制指示器旁边 */
  3004. background-color: rgba(0, 0, 0, 0.6);
  3005. padding: 5px 10px;
  3006. border-radius: 15px;
  3007. z-index: 20;
  3008. }
  3009. .upload-status-content {
  3010. display: flex;
  3011. align-items: center;
  3012. }
  3013. .upload-status-icon {
  3014. width: 12px;
  3015. height: 12px;
  3016. border-radius: 50%;
  3017. margin-right: 8px;
  3018. }
  3019. .upload-status-text {
  3020. color: white;
  3021. font-size: 14px;
  3022. }
  3023. .uploading {
  3024. background-color: #e74c3c;
  3025. }
  3026. /* 添加倒计时蒙层样式 */
  3027. .countdown-overlay {
  3028. position: fixed;
  3029. top: 0;
  3030. left: 0;
  3031. width: 100%;
  3032. height: 100%;
  3033. background-color: rgba(0, 0, 0, 0.7);
  3034. z-index: 100;
  3035. display: flex;
  3036. justify-content: center;
  3037. align-items: center;
  3038. }
  3039. .countdown-content {
  3040. display: flex;
  3041. flex-direction: column;
  3042. align-items: center;
  3043. }
  3044. .countdown-number {
  3045. font-size: 80px;
  3046. color: #ffffff;
  3047. font-weight: bold;
  3048. margin-bottom: 20px;
  3049. }
  3050. .countdown-text {
  3051. font-size: 24px;
  3052. color: #ffffff;
  3053. }
  3054. /* 添加GIF播放器样式 */
  3055. .gif-player {
  3056. width: 100%;
  3057. height: 100%;
  3058. object-fit: cover;
  3059. position: absolute;
  3060. top: 0;
  3061. left: 0;
  3062. z-index: 5; /* 确保GIF在视频上方但在字幕和按钮下方 */
  3063. }
  3064. /* 重新录制按钮容器样式 */
  3065. .rerecord-button-container {
  3066. position: absolute;
  3067. bottom: 50px; /* 统一与其他按钮的位置 */
  3068. left: 50%;
  3069. transform: translateX(-50%);
  3070. z-index: 20;
  3071. }
  3072. /* 重新录制按钮样式 */
  3073. .rerecord-button {
  3074. width: 120px;
  3075. height: 40px;
  3076. border-radius: 20px;
  3077. background-color: #ffffff;
  3078. color: #333;
  3079. font-size: 16px;
  3080. border: none;
  3081. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  3082. display: flex;
  3083. justify-content: center;
  3084. align-items: center;
  3085. cursor: pointer;
  3086. }
  3087. .rerecord-button:hover {
  3088. background-color: #f0f0f0;
  3089. }
  3090. </style>