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