identity-verify.vue 99 KB

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