interview-question.vue 94 KB

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