identity-verify.vue 120 KB

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