identity-verify.vue 120 KB

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