interview-question.js 121 KB

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