identity-verify.vue 118 KB

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