interview-question.vue 94 KB

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