identity-verify.vue 122 KB

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