identity-verify.vue 122 KB

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