interview-question.vue 110 KB

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