interview-question.vue 111 KB

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