identity-verify.vue 119 KB

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