interview-question.vue 168 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395
  1. <template>
  2. <div class="identity-verify-container">
  3. <div class="digital-human-container">
  4. <!-- AI数字人视频/图像显示区域 -->
  5. <div class="digital-human-video">
  6. <!-- 添加GIF图片显示区域 -->
  7. <!-- <img v-if="showGif && gifUrl" :src="gifUrl" class="gif-player" alt="面试官GIF" /> -->
  8. <!-- <video
  9. v-if="showGif && gifUrl"
  10. :src="gifUrl"
  11. id="mpVideo"
  12. autoplay
  13. class="video-player"
  14. :controls="false"
  15. loop
  16. muted
  17. object-fit="contain"
  18. ></video> v-if="!showGif" -->
  19. <!-- 视频播放区域,当showGif为false时显示 -->
  20. <video
  21. :src="videoUrl"
  22. id="myVideo"
  23. ref="videoPlayer"
  24. autoplay
  25. playsinline
  26. disablePictureInPicture
  27. controlsList="nodownload nofullscreen noremoteplayback"
  28. class="video-player"
  29. :controls="false"
  30. @error="handleVideoError"
  31. @ended="handleVideoEnded"
  32. @timeupdate="handleTimeUpdate">
  33. </video>
  34. <!-- 添加透明蒙层 -->
  35. <div class="video-overlay"></div>
  36. <div class="answer-button-container" v-if="showAnswerButton">
  37. <button class="answer-button" @click="handleAnswerButtonClick">
  38. 开始提问
  39. </button>
  40. </div>
  41. <!-- 添加字幕覆盖层 :data-time="formatTime(recordingTimerCount) || '03:30'"-->
  42. <div class="subtitle-overlay"
  43. v-if="currentSubtitle"
  44. :class="{ 'expanded': isSubtitleExpanded }"
  45. :style="{ 'max-height': subtitleHeight ? `${subtitleHeight}px` : null }">
  46. {{ currentSubtitle }}
  47. <button v-if="showNextButton" class="next-button" @click="handleNextButtonClick">我已阅读完成,继续</button>
  48. </div>
  49. <!-- 添加答题按钮 -->
  50. </div>
  51. <!-- 用户摄像头视频显示区域 -->
  52. <div class="user-camera-container">
  53. <!-- 在小程序环境中使用camera组件 -->
  54. <camera v-if="useMiniProgramCameraComponent"
  55. device-position="front"
  56. flash="off"
  57. class="user-camera-video"
  58. @error="handleCameraError"
  59. :record-audio="true"
  60. frame-size="small"
  61. resolution="low"
  62. :disable-zoom="true"
  63. :enable-camera="true"
  64. :enable-record="true"
  65. mode="normal">
  66. </camera>
  67. <!-- 在H5/App环境中使用video元素 -->
  68. <video v-else
  69. id="userCamera"
  70. ref="userCameraVideo"
  71. autoplay
  72. playsinline
  73. muted
  74. class="user-camera-video"
  75. :controls="false">
  76. </video>
  77. </div>
  78. <!-- 字幕/文本覆盖区域 -->
  79. <!-- <div class="subtitle-overlay" v-if="assistantResponse">
  80. {{ assistantResponse }}
  81. </div> -->
  82. </div>
  83. <!-- 加载状态 -->
  84. <div v-if="loading" class="loading">加载中...</div>
  85. <!-- 控制面板(可选,可以隐藏) -->
  86. <!-- 响应数据(可以设为隐藏,仅用于调试) -->
  87. <div v-if="showDebugInfo" class="response-container">
  88. <div v-if="assistantResponse" class="response-item">
  89. <div class="response-content">
  90. <span>助手回复: {{ assistantResponse }}</span>
  91. </div>
  92. </div>
  93. <div v-if="audioTranscript" class="response-item">
  94. <div class="response-content">
  95. <span>音频转写: {{ audioTranscript }}</span>
  96. </div>
  97. </div>
  98. <div v-for="(item, index) in processedResponses" :key="index" class="response-item">
  99. <div class="response-content">
  100. <span v-if="item.role">角色: {{ item.role }}</span>
  101. <span v-if="item.transcript">文本: {{ item.transcript }}</span>
  102. </div>
  103. </div>
  104. </div>
  105. <!-- 添加停止录制按钮 -->
  106. <div class="stop-recording-button-container" v-if="showStopRecordingButton">
  107. <button class="stop-recording-button" @click="stopRecordingAnswer">
  108. 完成提问
  109. </button>
  110. </div>
  111. <!-- 添加录制指示器 -->
  112. <div class="recording-indicator" v-if="isRecording">
  113. <div class="recording-dot"></div>
  114. <span class="recording-text">正在录制...</span>
  115. <span class="timer-text">{{ recordingTimeDisplay || '00:00 / 05:00' }}</span>
  116. </div>
  117. <!-- 添加开始回答按钮 -->
  118. <div class="start-recording-button-container" v-if="showStartRecordingButton">
  119. <button class="start-recording-button" @click="handleStartRecordingClick">
  120. 开始提问
  121. </button>
  122. </div>
  123. <!-- 添加重试上传按钮 -->
  124. <div class="retry-button-container" v-if="showRetryButton">
  125. <button class="retry-button" @click="retryVideoUpload">
  126. 重新上传
  127. </button>
  128. </div>
  129. <!-- 在模板部分添加录制时长显示 -->
  130. <!-- <div class="recording-timer" v-if="isRecording">
  131. <span class="timer-text">{{ recordingTimeDisplay || '00:00' }}</span>
  132. </div> -->
  133. <!-- 添加上传状态指示器 -->
  134. <!-- <div class="upload-status-indicator" v-if="showUploadStatus && uploadStatusText">
  135. <div class="upload-status-content">
  136. <div class="upload-status-icon" :class="{'uploading': isUploading}"></div>
  137. <span class="upload-status-text">{{ uploadStatusText }}</span>
  138. </div>
  139. </div> -->
  140. <!-- 修改录制时长显示 -->
  141. <!-- <div class="recording-timer" v-if="isRecording">
  142. <span class="timer-text">{{ recordingTimeDisplay || '00:00 / 05:00' }}</span>
  143. <span class="remaining-time" :class="{'warning': remainingTime <= 10}">
  144. 剩余: {{ formatTime(remainingTime) }}
  145. </span>
  146. </div> -->
  147. <!-- 在模板部分添加倒计时蒙层 -->
  148. <div class="countdown-overlay" v-if="showCountdown">
  149. <div class="countdown-content">
  150. <div class="countdown-number">{{ countdownValue }}</div>
  151. <div class="countdown-text">准备开始回答</div>
  152. </div>
  153. </div>
  154. <!-- 在template中添加蒙层 -->
  155. <div class="ai-voice-overlay" v-if="isPlayingAiVoice">
  156. <div class="ai-voice-content">
  157. <div class="ai-voice-icon"></div>
  158. <div class="ai-voice-text">面试官正在回复...</div>
  159. </div>
  160. </div>
  161. <!-- 在模板部分添加继续提问和结束面试按钮 -->
  162. <div class="continue-question-container" v-if="showContinueQuestionButton">
  163. <button class="continue-question-button" @click="handleContinueQuestionClick">
  164. 继续提问
  165. </button>
  166. </div>
  167. <!-- <div class="end-interview-container" v-if="showEndInterviewButton">
  168. <button class="end-interview-button" @click="handleEndInterviewClick">
  169. 结束提问
  170. </button>
  171. </div> -->
  172. <!-- 添加提问轮次显示 -->
  173. <!-- <div class="question-round-indicator" v-if="questionRound > 0">
  174. <span class="round-text">第 {{ questionRound }}/{{ maxQuestionRounds }} 轮提问</span>
  175. </div> -->
  176. </div>
  177. </template>
  178. <script>
  179. import { apiBaseUrl } from '@/common/config.js';
  180. export default {
  181. name: 'IdentityVerify',
  182. data() {
  183. return {
  184. loading: false,
  185. responses: [],
  186. processedResponses: [],
  187. assistantResponse: '',
  188. audioTranscript: '',
  189. videoPlaying: false,
  190. showDebugInfo: false, // 设置为true可以显示调试信息
  191. videoUrl: 'https://data.qicai321.com/minlong/1809457d-30c5-40bb-b6d8-a8c2e8e1e9e2.mp4', //'http://121.36.251.245:9000/minlong/tenant_1/general_uploads/abdaa6fda8494e3a8613304743ed0433.mp4', // 用于存储AI数字人视频URL
  192. showReplayButton: false,
  193. cameraStream: null, // 存储摄像头流
  194. cameraError: null, // 存储摄像头错误信息
  195. useMiniProgramCameraComponent: false, // 添加小程序相机组件标志
  196. cameraContext: null, // 添加相机上下文
  197. currentSubtitle: '',
  198. subtitles: [
  199. {
  200. startTime: 0, // 开始时间(秒)
  201. endTime: 6, // 结束时间(秒)
  202. text: '您已完成本次面试全部题目,请问您对于这个岗位还有什么想要了解的吗?'
  203. },
  204. ],
  205. // secondVideoSubtitles: [
  206. // {
  207. // startTime: 0,
  208. // endTime: 10,
  209. // text: '请结合您的基本信息与过往履历进行简单的自我介绍,并讲一讲您有哪些优势胜任本岗位:'
  210. // }
  211. // ],
  212. // thirdVideoSubtitles: [
  213. // {
  214. // startTime: 0,
  215. // endTime: 4,
  216. // text: '在工作中,你如何确保个人防护装备的正确使用?'
  217. // }
  218. // ],
  219. // fourthVideoSubtitles: [
  220. // {
  221. // startTime: 0,
  222. // endTime: 4,
  223. // text: '描述一次你与团队合作改善生产流程的经历。'
  224. // }
  225. // ],
  226. // fifthVideoSubtitles: [
  227. // {
  228. // startTime: 0,
  229. // endTime: 6,
  230. // text: '你在团队合作中曾遇到过哪些挑战?如何解决团队内部的分歧?'
  231. // }
  232. // ],
  233. // sixthVideoSubtitles: [
  234. // {
  235. // startTime: 0,
  236. // endTime: 5,
  237. // text: '您已完成本次面试全部题目,请问您对于这个岗位还有什么想要了解的吗?'
  238. // }
  239. // ],
  240. showAnswerButton: false, // 控制答题按钮显示
  241. currentVideoIndex: 0, // 当前播放的视频索引
  242. videoList: [
  243. 'https://data.qicai321.com/minlong/1809457d-30c5-40bb-b6d8-a8c2e8e1e9e2.mp4'//结束
  244. ],
  245. isRecording: false,
  246. recordingTimer: null,
  247. showStopRecordingButton: false,
  248. mediaRecorder: null,
  249. recordedChunks: [],
  250. recorder: null,
  251. lastUploadedVideoUrl: '',
  252. showStartRecordingButton: false,
  253. showRetryButton: false, // 控制重试按钮显示
  254. lastVideoToRetry: null, // 存储上次失败的视频URL,用于重试
  255. recordingStartTime: null, // 录制开始时间
  256. recordingTimerCount: 0, // 录制计时器计数
  257. recordingTimeDisplay: '00:00', // 格式化的录制时间显示
  258. // 添加上传队列相关数据
  259. uploadQueue: [], // 存储待上传的视频
  260. isUploading: false, // 标记是否正在上传
  261. uploadProgress: {}, // 存储每个视频的上传进度
  262. uploadStatus: {}, // 存储每个视频的上传状态
  263. showUploadStatus: false, // 是否显示上传状态指示器
  264. uploadStatusText: '', // 上传状态文本
  265. mediaRecorderTimeout: null, // 用于存储MediaRecorder的超时机制
  266. maxRecordingTime: 300, // 最大录制时间(秒)- 从60秒改为300秒(5分钟)
  267. remainingTime: 300, // 剩余录制时间(秒)- 从60秒改为300秒
  268. // 修改初始视频索引,添加参数控制
  269. startFromLastVideo: false, // 是否从最后一个视频开始播放
  270. countdownValue: 10, // 倒计时数值
  271. showCountdown: false, // 是否显示倒计时蒙层
  272. countdownTimer: null,
  273. showGif: false, // 控制是否显示GIF
  274. gifUrl: '', // GIF图片的URL
  275. // 添加AI语音交互相关属性
  276. aiVoiceUrl: '', // AI语音URL
  277. aiText: '', // AI回复文本
  278. transcribedText: '', // 转写文本
  279. isPlayingAiVoice: false, // 是否正在播放AI语音
  280. aiAudioPlayer: null, // AI语音播放器
  281. // 添加新的状态变量
  282. showContinueQuestionButton: false, // 控制"继续提问"按钮显示
  283. showEndInterviewButton: false, // 控制"结束面试"按钮显示
  284. questionRound: 0, // 当前提问轮次
  285. maxQuestionRounds: 1, // 最大提问轮次(可配置)
  286. conversationHistory: [], // 对话历史记录
  287. pendingAutoNavigation: false, // 标记是否有待处理的自动跳转
  288. hasTriedFallbackMethod: false, // 标记是否尝试过备选方法播放音频
  289. hasShownTextFallbackToast: false, // 标记是否已显示文本回退提示
  290. showNextButton: false, // 添加一个变量控制按钮显示
  291. isSubtitleExpanded: false, // 控制字幕是否展开
  292. subtitleHeight: 0, // 记录字幕内容高度
  293. }
  294. },
  295. onLoad(options) {
  296. // 检查是否有参数指定从最后一个视频开始
  297. if (options && options.startFromLast === 'true') {
  298. this.startFromLastVideo = true;
  299. // 设置为最后一个视频的索引
  300. this.currentVideoIndex = this.videoList.length - 1;
  301. }
  302. },
  303. mounted() {
  304. /* this.fetchData() */
  305. // 如果需要从最后一个视频开始,直接设置
  306. if (this.startFromLastVideo) {
  307. console.log('从最后一个视频开始播放');
  308. this.currentVideoIndex = this.videoList.length - 1;
  309. this.videoUrl = this.videoList[this.currentVideoIndex];
  310. }
  311. this.playDigitalHumanVideo();
  312. this.checkAudioPermission();
  313. this.initCamera();
  314. this.checkIOSCameraRecordPermission();
  315. // 添加防御性检查,避免渲染错误
  316. this.checkAndFixRenderingIssues();
  317. // 添加音频测试
  318. setTimeout(() => {
  319. if (this.cameraStream && !this.useMiniProgramCameraComponent) {
  320. this.testAudioInput();
  321. }
  322. }, 3000);
  323. uni.setKeepScreenOn({
  324. keepScreenOn: true
  325. });
  326. },
  327. beforeDestroy() {
  328. // 组件销毁前停止摄像头
  329. this.stopUserCamera();
  330. // 销毁AI音频播放器
  331. if (this.aiAudioPlayer) {
  332. try {
  333. this.aiAudioPlayer.destroy();
  334. } catch (e) {
  335. console.error('销毁音频播放器失败:', e);
  336. }
  337. this.aiAudioPlayer = null;
  338. }
  339. // 清除所有计时器
  340. if (this.recordingTimer) {
  341. clearInterval(this.recordingTimer);
  342. this.recordingTimer = null;
  343. }
  344. if (this.countdownTimer) {
  345. clearInterval(this.countdownTimer);
  346. this.countdownTimer = null;
  347. }
  348. if (this.mediaRecorderTimeout) {
  349. clearTimeout(this.mediaRecorderTimeout);
  350. this.mediaRecorderTimeout = null;
  351. }
  352. // 如果有正在进行的录制,停止录制
  353. if (this.mediaRecorder && this.mediaRecorder.state === 'recording') {
  354. try {
  355. this.mediaRecorder.stop();
  356. } catch (e) {
  357. console.error('停止MediaRecorder失败:', e);
  358. }
  359. }
  360. if (this.recorder) {
  361. try {
  362. this.cameraContext.stopRecord();
  363. } catch (e) {
  364. console.error('停止小程序录制失败:', e);
  365. }
  366. }
  367. // 关闭屏幕常亮
  368. uni.setKeepScreenOn({
  369. keepScreenOn: false
  370. });
  371. },
  372. methods: {
  373. // 初始化相机
  374. async initCamera() {
  375. // 检查平台
  376. const systemInfo = uni.getSystemInfoSync();
  377. // 判断是否在小程序环境中
  378. const isMiniProgram = systemInfo.uniPlatform === 'mp-weixin' ||
  379. systemInfo.uniPlatform === 'mp-alipay' ||
  380. systemInfo.uniPlatform === 'mp-baidu';
  381. if (isMiniProgram) {
  382. // 小程序环境使用小程序的相机API
  383. this.useMiniProgramCameraComponent = true;
  384. // 创建相机上下文
  385. this.cameraContext = uni.createCameraContext();
  386. // 确保已获取录音和相机权限
  387. uni.getSetting({
  388. success: (res) => {
  389. // 检查录音权限
  390. if (!res.authSetting['scope.record']) {
  391. uni.authorize({
  392. scope: 'scope.record',
  393. success: () => {
  394. console.log('录音权限已获取');
  395. },
  396. fail: (err) => {
  397. console.error('录音权限获取失败:', err);
  398. this.showPermissionDialog('录音');
  399. }
  400. });
  401. }
  402. // 检查相机权限
  403. if (!res.authSetting['scope.camera']) {
  404. uni.authorize({
  405. scope: 'scope.camera',
  406. success: () => {
  407. console.log('相机权限已获取');
  408. },
  409. fail: (err) => {
  410. console.error('相机权限获取失败:', err);
  411. this.showPermissionDialog('相机');
  412. }
  413. });
  414. }
  415. // 在iOS上,可能需要额外的权限检查
  416. const systemInfo = uni.getSystemInfoSync();
  417. if (systemInfo.platform === 'ios') {
  418. // 在iOS上,不要使用无效的权限范围
  419. // 移除以下代码块
  420. /*
  421. if (!res.authSetting['scope.camera.record']) {
  422. uni.authorize({
  423. scope: 'scope.camera.record',
  424. success: () => {
  425. console.log('相机录制权限已获取');
  426. },
  427. fail: (err) => {
  428. console.error('相机录制权限获取失败:', err);
  429. this.showPermissionDialog('相机录制');
  430. }
  431. });
  432. }
  433. */
  434. // 确保同时获取了相机和录音权限
  435. if (!res.authSetting['scope.camera'] || !res.authSetting['scope.record']) {
  436. console.log('iOS需要同时获取相机和录音权限');
  437. }
  438. }
  439. }
  440. });
  441. } else {
  442. // H5/App环境使用浏览器的API
  443. try {
  444. // 请求摄像头和麦克风权限并获取媒体流,添加更多约束
  445. const constraints = {
  446. audio: {
  447. echoCancellation: true,
  448. noiseSuppression: true,
  449. autoGainControl: true
  450. },
  451. video: {
  452. width: { ideal: 640, max: 1280 }, // 控制视频宽度
  453. height: { ideal: 480, max: 720 }, // 控制视频高度
  454. frameRate: { ideal: 15, max: 24 }, // 控制帧率
  455. facingMode: 'user'
  456. }
  457. };
  458. const stream = await navigator.mediaDevices.getUserMedia(constraints);
  459. // 保存流以便后续使用
  460. this.cameraStream = stream;
  461. // 检查音频轨道
  462. const audioTracks = stream.getAudioTracks();
  463. console.log('音频轨道数量:', audioTracks.length);
  464. if (audioTracks.length > 0) {
  465. console.log('音频轨道已获取:', audioTracks[0].label);
  466. // 确保音频轨道已启用
  467. audioTracks[0].enabled = true;
  468. } else {
  469. console.warn('未检测到音频轨道,尝试单独获取音频');
  470. this.tryGetAudioOnly();
  471. }
  472. // 将流设置到视频元素
  473. const videoElement = this.$refs.userCameraVideo;
  474. if (videoElement) {
  475. videoElement.srcObject = stream;
  476. videoElement.muted = true; // 避免回声,但仍然录制声音
  477. }
  478. } catch (error) {
  479. console.error('获取摄像头失败:', error);
  480. this.cameraError = error.message || '无法访问摄像头';
  481. // 显示错误提示
  482. uni.showToast({
  483. title: '无法访问摄像头,请检查权限设置',
  484. icon: 'none'
  485. });
  486. }
  487. }
  488. },
  489. // 停止用户摄像头
  490. stopUserCamera() {
  491. if (this.cameraStream) {
  492. // 停止所有轨道
  493. this.cameraStream.getTracks().forEach(track => {
  494. track.stop();
  495. });
  496. this.cameraStream = null;
  497. }
  498. },
  499. async fetchData() {
  500. this.loading = true
  501. this.assistantResponse = ''
  502. this.audioTranscript = ''
  503. this.processedResponses = []
  504. try {
  505. // 使用uni.request代替fetch
  506. const requestTask = uni.request({
  507. url: 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions',
  508. method: 'POST',
  509. header: {
  510. 'Content-Type': 'application/json',
  511. 'Authorization': 'Bearer sk-9e1ec73a7d97493b8613c63f06b6110c'
  512. },
  513. data: {
  514. "model": "qwen-omni-turbo",
  515. "messages": [
  516. {
  517. "role": "user",
  518. "content": [
  519. {
  520. "type": "input_audio",
  521. "input_audio": {
  522. "data": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250211/tixcef/cherry.wav",
  523. "format": "wav"
  524. }
  525. },
  526. {
  527. "type": "text",
  528. "text": "这段音频在说什么"
  529. }
  530. ]
  531. }
  532. ],
  533. "stream":true,
  534. "stream_options":{
  535. "include_usage":true
  536. },
  537. "modalities":["text","audio"],
  538. "audio":{"voice":"Cherry","format":"wav"}
  539. },
  540. success: (res) => {
  541. console.log('请求成功,响应数据:', res.data);
  542. // 检查响应数据是否包含多个JSON对象
  543. if (typeof res.data === 'string' && res.data.includes('data: {')) {
  544. // 处理包含多个JSON对象的情况
  545. const chunks = res.data.split('data: ').filter(chunk => chunk.trim() !== '');
  546. chunks.forEach(chunk => {
  547. this.handleStreamResponse(chunk);
  548. });
  549. } else {
  550. // 处理单个响应对象的情况
  551. this.handleStreamResponse(res.data);
  552. }
  553. // 模拟获取到数字人视频并播放
  554. this.playDigitalHumanVideo();
  555. },
  556. fail: (err) => {
  557. console.error('请求失败:', err);
  558. },
  559. complete: () => {
  560. this.loading = false;
  561. }
  562. });
  563. } catch (error) {
  564. console.error('获取数据失败:', error);
  565. this.loading = false;
  566. }
  567. },
  568. handleStreamResponse(data) {
  569. // 处理流式响应数据
  570. if (typeof data === 'string') {
  571. // 处理字符串格式的响应
  572. if (data === '[DONE]') return;
  573. try {
  574. // 移除可能存在的换行符和多余空格
  575. const cleanData = data.trim();
  576. // 检查是否是有效的JSON字符串
  577. if (cleanData.startsWith('{') && cleanData.endsWith('}')) {
  578. const jsonData = JSON.parse(cleanData);
  579. this.processStreamChunk(jsonData);
  580. }
  581. } catch (e) {
  582. console.error('解析JSON失败:', e, '原始数据:', data);
  583. }
  584. } else {
  585. // 处理对象格式的响应
  586. this.processStreamChunk(data);
  587. }
  588. },
  589. processStreamChunk(chunk) {
  590. if (chunk.choices && chunk.choices.length > 0) {
  591. const choice = chunk.choices[0];
  592. // 处理助手回复内容
  593. if (choice.delta && choice.delta.content) {
  594. this.assistantResponse += choice.delta.content;
  595. }
  596. // 处理音频转写内容
  597. if (choice.delta && choice.delta.audio && choice.delta.audio.transcript) {
  598. this.audioTranscript += choice.delta.audio.transcript;
  599. }
  600. // 处理角色和音频转写
  601. if (choice.delta) {
  602. const result = {};
  603. if (choice.delta.role) {
  604. result.role = choice.delta.role;
  605. }
  606. if (choice.delta.audio && choice.delta.audio.transcript) {
  607. result.transcript = choice.delta.audio.transcript;
  608. }
  609. if (Object.keys(result).length > 0) {
  610. this.processedResponses.push(result);
  611. }
  612. }
  613. }
  614. },
  615. processResponseData() {
  616. // 处理返回的数据
  617. this.processedResponses = this.responses.map(item => {
  618. const result = {}
  619. // 处理角色信息
  620. if (item.delta && item.delta.role) {
  621. result.role = item.delta.role
  622. }
  623. // 处理音频转写文本
  624. if (item.delta && item.delta.audio && item.delta.audio.transcript) {
  625. result.transcript = item.delta.audio.transcript
  626. }
  627. return result
  628. }).filter(item => Object.keys(item).length > 0)
  629. },
  630. // 播放数字人视频
  631. playDigitalHumanVideo() {
  632. // 设置当前视频
  633. if(JSON.parse(uni.getStorageSync('configData'))==null){
  634. this.videoUrl = this.videoList[this.currentVideoIndex];
  635. }else{
  636. this.videoUrl =JSON.parse(uni.getStorageSync('configData')).digital_human?.ending_video_url || this.videoList[this.currentVideoIndex];
  637. }
  638. this.videoPlaying = true;
  639. console.log(`播放视频 ${this.currentVideoIndex + 1}/${this.videoList.length}: ${this.videoUrl}`);
  640. // 使用 uni.createVideoContext 来控制视频
  641. this.$nextTick(() => {
  642. const videoContext = uni.createVideoContext('myVideo', this);
  643. if (videoContext) {
  644. videoContext.play();
  645. // 设置超时检查,确认视频是否真的在播放
  646. setTimeout(() => {
  647. if (this.videoPlaying && this.$refs.videoPlayer) {
  648. console.log('视频应该正在播放');
  649. } else {
  650. console.log('视频可能未成功播放,尝试替代方案');
  651. this.tryAlternativeVideoPath();
  652. }
  653. }, 1000);
  654. } else {
  655. console.error('无法创建视频上下文');
  656. this.tryAlternativeVideoPath();
  657. }
  658. });
  659. },
  660. // 修改 tryAlternativeVideoPath 方法
  661. tryAlternativeVideoPath() {
  662. console.log('尝试使用替代路径');
  663. // 尝试不同的路径格式
  664. const alternativePaths = [
  665. './static/demo.mp4',
  666. '../static/demo.mp4',
  667. 'static/demo.mp4',
  668. '/static/demo.mp4',
  669. // 添加绝对路径
  670. `${window.location.origin}/static/demo.mp4`
  671. ];
  672. // 获取当前路径索引
  673. const currentPathIndex = alternativePaths.indexOf(this.videoUrl);
  674. const nextPathIndex = (currentPathIndex + 1) % alternativePaths.length;
  675. // 设置下一个路径
  676. this.videoUrl = alternativePaths[nextPathIndex];
  677. console.log('尝试新路径:', this.videoUrl);
  678. this.$nextTick(() => {
  679. const videoContext = uni.createVideoContext('myVideo', this);
  680. if (videoContext) {
  681. videoContext.stop();
  682. videoContext.play();
  683. // 检查是否成功播放
  684. setTimeout(() => {
  685. if (nextPathIndex === alternativePaths.length - 1 && !this.videoPlaying) {
  686. console.log('所有路径均失败,尝试使用uni.getVideoInfo检查视频');
  687. this.checkVideoWithAPI();
  688. }
  689. }, 1000);
  690. }
  691. });
  692. },
  693. // 添加新方法:使用uni API检查视频
  694. checkVideoWithAPI() {
  695. // 尝试使用uni.getVideoInfo API检查视频是否可用
  696. uni.getVideoInfo({
  697. src: '/static/demo.mp4',
  698. success: (res) => {
  699. console.log('视频信息获取成功:', res);
  700. // 如果能获取到视频信息,再次尝试播放
  701. this.videoUrl = '/static/demo.mp4';
  702. this.$nextTick(() => {
  703. const videoContext = uni.createVideoContext('myVideo', this);
  704. if (videoContext) {
  705. videoContext.play();
  706. }
  707. });
  708. },
  709. fail: (err) => {
  710. console.error('视频信息获取失败:', err);
  711. // 最后尝试使用uni.chooseVideo API
  712. this.fallbackToLocalVideo();
  713. }
  714. });
  715. },
  716. // 添加新方法:回退到本地视频
  717. fallbackToLocalVideo() {
  718. console.log('尝试使用本地视频资源');
  719. // 检查平台
  720. const platform = uni.getSystemInfoSync().platform;
  721. if (platform === 'android' || platform === 'ios') {
  722. // 移动端可以尝试使用本地资源
  723. this.videoUrl = platform === 'android' ? 'android.resource://package_name/raw/demo' : 'file:///assets/demo.mp4';
  724. this.$nextTick(() => {
  725. const videoContext = uni.createVideoContext('myVideo', this);
  726. if (videoContext) {
  727. videoContext.play();
  728. }
  729. });
  730. } else {
  731. // 最终回退到静态图片
  732. this.videoPlaying = false;
  733. uni.showToast({
  734. title: '视频加载失败,显示静态图片',
  735. icon: 'none'
  736. });
  737. }
  738. },
  739. // 修改 handleVideoError 方法
  740. handleVideoError(e) {
  741. console.error('视频加载错误:', e);
  742. // 记录更详细的错误信息
  743. if (e && e.detail) {
  744. console.error('详细错误信息:', e.detail);
  745. }
  746. // 检查视频文件是否存在
  747. uni.getFileInfo({
  748. filePath: this.videoUrl.startsWith('/') ? this.videoUrl.substring(1) : this.videoUrl,
  749. success: (res) => {
  750. console.log('文件存在,大小:', res.size);
  751. // 文件存在但播放失败,可能是格式问题
  752. this.tryDifferentFormat();
  753. },
  754. fail: (err) => {
  755. console.error('文件不存在或无法访问:', err);
  756. // 尝试不同路径
  757. this.tryAlternativeVideoPath();
  758. }
  759. });
  760. // 如果多次尝试后仍然失败,显示错误信息
  761. uni.showToast({
  762. title: '视频加载失败,请检查文件是否存在',
  763. icon: 'none',
  764. duration: 2000
  765. });
  766. },
  767. // 添加新方法:尝试不同格式
  768. tryDifferentFormat() {
  769. console.log('尝试不同的视频格式');
  770. // 尝试不同的视频格式
  771. const formats = [
  772. { ext: 'mp4', mime: 'video/mp4' },
  773. { ext: 'webm', mime: 'video/webm' },
  774. { ext: 'ogg', mime: 'video/ogg' },
  775. { ext: 'mov', mime: 'video/quicktime' }
  776. ];
  777. // 获取当前文件名(不含扩展名)
  778. const currentPath = this.videoUrl;
  779. const basePath = currentPath.substring(0, currentPath.lastIndexOf('.')) || '/static/demo';
  780. // 尝试下一个格式
  781. let nextFormat = formats.find(f => !currentPath.endsWith(f.ext));
  782. if (nextFormat) {
  783. this.videoUrl = `${basePath}.${nextFormat.ext}`;
  784. console.log('尝试新格式:', this.videoUrl);
  785. this.$nextTick(() => {
  786. const videoContext = uni.createVideoContext('myVideo', this);
  787. if (videoContext) {
  788. videoContext.stop();
  789. videoContext.play();
  790. }
  791. });
  792. } else {
  793. // 所有格式都尝试过了,使用内置资源
  794. this.useBuiltInResource();
  795. }
  796. },
  797. // 添加新方法:使用内置资源
  798. useBuiltInResource() {
  799. console.log('尝试使用内置资源');
  800. // 检查平台
  801. const platform = uni.getSystemInfoSync().platform;
  802. // 根据平台选择合适的视频源
  803. if (platform === 'windows') {
  804. // Windows平台特定处理
  805. // 尝试使用相对于应用根目录的路径
  806. const appRoot = process.env.UNI_INPUT_DIR || '';
  807. this.videoUrl = `./static/demo.mp4`;
  808. // 或者尝试使用file://协议
  809. // this.videoUrl = `file:///${appRoot.replace(/\\/g, '/')}/static/demo.mp4`;
  810. console.log('Windows平台尝试路径:', this.videoUrl);
  811. } else if (platform === 'android' || platform === 'ios') {
  812. // 移动端
  813. this.useNativeVideo();
  814. } else {
  815. // Web平台
  816. // 尝试使用完整URL
  817. const baseUrl = window.location.origin;
  818. this.videoUrl = `${baseUrl}/static/demo.mp4`;
  819. console.log('Web平台尝试URL:', this.videoUrl);
  820. }
  821. this.$nextTick(() => {
  822. const videoContext = uni.createVideoContext('myVideo', this);
  823. if (videoContext) {
  824. videoContext.play();
  825. }
  826. });
  827. },
  828. // 添加新方法:使用原生视频能力
  829. useNativeVideo() {
  830. console.log('尝试使用原生视频能力');
  831. // 在移动端,可以尝试使用原生视频播放器
  832. uni.chooseVideo({
  833. sourceType: ['album'],
  834. success: (res) => {
  835. this.videoUrl = res.tempFilePath;
  836. this.$nextTick(() => {
  837. const videoContext = uni.createVideoContext('myVideo', this);
  838. if (videoContext) {
  839. videoContext.play();
  840. }
  841. });
  842. },
  843. fail: () => {
  844. // 如果用户取消选择,回退到静态图片
  845. this.videoPlaying = false;
  846. uni.showToast({
  847. title: '无法加载视频,显示静态图片',
  848. icon: 'none'
  849. });
  850. }
  851. });
  852. },
  853. // 处理视频结束事件
  854. handleVideoEnded() {
  855. console.log('视频播放结束,当前视频索引:', this.currentVideoIndex);
  856. this.videoPlaying = false;
  857. /* // 设置对应问题的GIF图片URL
  858. // if (this.currentVideoIndex === 0) {
  859. this.gifUrl = 'http://121.36.251.245:9000/minlong/cae2da8f92ce4af278d3929ab8c5973f.mp4';
  860. // } else if (this.currentVideoIndex === 1) {
  861. // this.gifUrl = 'http://121.36.251.245:9000/minlong/tenant_1/general_uploads/5273282d971441249aeadf35a7574f01.gif';
  862. // } else if (this.currentVideoIndex === 2) {
  863. // this.gifUrl = 'http://121.36.251.245:9000/minlong/tenant_1/general_uploads/5273282d971441249aeadf35a7574f01.gif';
  864. // } else if (this.currentVideoIndex === 3) {
  865. // this.gifUrl = 'http://121.36.251.245:9000/minlong/tenant_1/general_uploads/5273282d971441249aeadf35a7574f01.gif';
  866. // } else if (this.currentVideoIndex === 4) {
  867. // this.gifUrl = 'http://121.36.251.245:9000/minlong/tenant_1/general_uploads/5273282d971441249aeadf35a7574f01.gif';
  868. // } else if (this.currentVideoIndex === 5) {
  869. // this.gifUrl = 'http://121.36.251.245:9000/minlong/tenant_1/general_uploads/5273282d971441249aeadf35a7574f01.gif';
  870. // }
  871. // 显示GIF图片
  872. this.showGif = true; */
  873. // 视频结束后直接显示"开始作答"按钮
  874. this.showStartRecordingButton = true;
  875. this.startCountdown();
  876. this.showAnswerButton = false;
  877. },
  878. // 添加新方法:开始倒计时
  879. startCountdown() {
  880. // 显示倒计时蒙层
  881. this.showCountdown = true;
  882. this.countdownValue = 10;
  883. // 开始倒计时
  884. this.countdownTimer = setInterval(() => {
  885. this.countdownValue--;
  886. if (this.countdownValue <= 0) {
  887. // 倒计时结束,清除定时器
  888. this.clearCountdown();
  889. // 隐藏"开始回答"按钮
  890. this.showStartRecordingButton = false;
  891. // 开始录制
  892. this.startRecordingAnswer();
  893. }
  894. }, 1000);
  895. },
  896. // 添加新方法:清除倒计时
  897. clearCountdown() {
  898. if (this.countdownTimer) {
  899. clearInterval(this.countdownTimer);
  900. this.countdownTimer = null;
  901. }
  902. this.showCountdown = false;
  903. },
  904. // 修改 handleStartRecordingClick 方法,使其可以终止倒计时
  905. handleStartRecordingClick() {
  906. // 隐藏"开始回答"按钮
  907. this.showStartRecordingButton = false;
  908. // 如果倒计时正在进行,清除倒计时
  909. this.clearCountdown();
  910. // 直接开始录制
  911. this.startRecordingAnswer();
  912. },
  913. // 修复 stopRecordingAnswer 方法,确保录制正确停止并上传
  914. stopRecordingAnswer() {
  915. // 如果倒计时正在进行,先清除倒计时
  916. this.clearCountdown();
  917. // 检查录制时长
  918. const recordingDuration = this.getRecordingDuration();
  919. const minimumDuration = 5; // 最小录制时长(秒)
  920. if (recordingDuration < minimumDuration) {
  921. // 录制时间过短,显示提示
  922. uni.showToast({
  923. title: '录制时间过短,请至少录制5秒',
  924. icon: 'none',
  925. duration: 2000
  926. });
  927. // 不执行停止录制逻辑,继续录制
  928. return;
  929. }
  930. // 隐藏停止录制按钮
  931. this.showStopRecordingButton = false;
  932. // 停止录制计时器
  933. if (this.recordingTimer) {
  934. clearInterval(this.recordingTimer);
  935. this.recordingTimer = null;
  936. }
  937. // 根据平台选择不同的停止录制方法
  938. const systemInfo = uni.getSystemInfoSync();
  939. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
  940. if (isMiniProgram) {
  941. // 小程序环境使用小程序的停止录制API
  942. this.stopMiniProgramRecording();
  943. } else {
  944. // H5/App环境使用MediaRecorder API
  945. this.stopBrowserRecording();
  946. }
  947. // 标记录制已停止
  948. this.isRecording = false;
  949. },
  950. // 添加新方法:开始录制用户回答
  951. startRecordingAnswer() {
  952. console.log('开始录制用户回答');
  953. this.isRecording = true;
  954. // 记录录制开始时间
  955. this.recordingStartTime = Date.now();
  956. this.recordingTimerCount = 0;
  957. this.remainingTime = this.maxRecordingTime;
  958. // 启动计时器,每秒更新计时
  959. this.recordingTimer = setInterval(() => {
  960. this.recordingTimerCount++;
  961. this.remainingTime = Math.max(0, this.maxRecordingTime - this.recordingTimerCount);
  962. // 更新UI显示录制时长和剩余时间
  963. this.recordingTimeDisplay = this.formatTime(this.recordingTimerCount) +
  964. ' / ' + this.formatTime(this.maxRecordingTime);
  965. // 检查是否达到最大录制时间
  966. if (this.recordingTimerCount >= this.maxRecordingTime) {
  967. console.log('已达到最大录制时间(60秒),自动停止录制');
  968. this.stopRecordingAnswer();
  969. }
  970. }, 1000);
  971. // 显示录制中的提示
  972. // uni.showLoading({
  973. // title: '正在录制...',
  974. // mask: true
  975. // });
  976. // 根据平台选择不同的录制方法
  977. const systemInfo = uni.getSystemInfoSync();
  978. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
  979. if (isMiniProgram) {
  980. // 小程序环境使用小程序的录制API
  981. this.startMiniProgramRecording();
  982. } else {
  983. // H5/App环境使用MediaRecorder API
  984. this.startBrowserRecording();
  985. }
  986. // 显示停止录制按钮
  987. this.showStopRecordingButton = true;
  988. },
  989. // 添加一个新方法:重置相机组件
  990. resetCamera() {
  991. console.log('重置相机组件');
  992. // 先完全移除相机组件
  993. this.useMiniProgramCameraComponent = false;
  994. // 释放相机上下文
  995. if (this.cameraContext) {
  996. this.cameraContext = null;
  997. }
  998. // 延迟后重新创建相机组件
  999. setTimeout(() => {
  1000. this.useMiniProgramCameraComponent = true;
  1001. // 再次延迟创建相机上下文,确保组件已完全渲染
  1002. setTimeout(() => {
  1003. this.cameraContext = uni.createCameraContext();
  1004. console.log('相机组件已重置');
  1005. }, 500);
  1006. }, 500);
  1007. },
  1008. // 修改 startMiniProgramRecording 方法
  1009. startMiniProgramRecording() {
  1010. console.log('开始小程序录制方法');
  1011. // 获取平台信息
  1012. const systemInfo = uni.getSystemInfoSync();
  1013. const isIOS = systemInfo.platform === 'ios';
  1014. // 在iOS上,先重置相机
  1015. if (isIOS) {
  1016. // 先重置相机组件
  1017. this.resetCamera();
  1018. // 延迟执行录制,给相机组件足够的初始化时间
  1019. setTimeout(() => {
  1020. this.actualStartRecording(isIOS);
  1021. }, 1000);
  1022. } else {
  1023. // Android直接开始
  1024. this.actualStartRecording(isIOS);
  1025. }
  1026. },
  1027. // 添加新方法:实际开始录制
  1028. actualStartRecording(isIOS) {
  1029. if (!this.cameraContext) {
  1030. this.cameraContext = uni.createCameraContext();
  1031. console.log('创建新的相机上下文');
  1032. }
  1033. // 确保有录音权限
  1034. uni.getSetting({
  1035. success: (res) => {
  1036. const hasRecordAuth = res.authSetting['scope.record'];
  1037. const hasCameraAuth = res.authSetting['scope.camera'];
  1038. if (!hasRecordAuth || !hasCameraAuth) {
  1039. console.warn('缺少必要权限,请求权限');
  1040. this.requestMiniProgramPermissions();
  1041. return;
  1042. }
  1043. // 在iOS上,先检查相机状态
  1044. if (isIOS) {
  1045. console.log('iOS: 检查相机状态');
  1046. // 使用最简单的选项,设置最大录制时间为5分钟
  1047. const options = {
  1048. timeout: 300000, // 300秒超时 (5分钟)
  1049. quality: 'low', // 降低质量
  1050. compressed: true,
  1051. success: () => {
  1052. console.log('iOS录制开始成功');
  1053. },
  1054. fail: (err) => {
  1055. console.error('iOS录制失败:', err);
  1056. // 如果失败,尝试使用不同的方法
  1057. this.useAlternativeRecordingMethod();
  1058. }
  1059. };
  1060. try {
  1061. console.log('尝试开始录制');
  1062. this.recorder = this.cameraContext.startRecord(options);
  1063. } catch (e) {
  1064. console.error('开始录制异常:', e);
  1065. this.useAlternativeRecordingMethod();
  1066. }
  1067. } else {
  1068. // Android使用标准选项,设置最大录制时间为5分钟
  1069. const options = {
  1070. timeout: 300000, // 300秒超时 (5分钟)
  1071. quality: 'medium',
  1072. compressed: true,
  1073. success: () => {
  1074. console.log('Android录制开始成功');
  1075. },
  1076. fail: (err) => {
  1077. console.error('Android录制失败:', err);
  1078. uni.showToast({
  1079. title: '录制失败,请检查相机权限',
  1080. icon: 'none'
  1081. });
  1082. this.proceedToNextQuestion();
  1083. }
  1084. };
  1085. this.recorder = this.cameraContext.startRecord(options);
  1086. }
  1087. }
  1088. });
  1089. },
  1090. // 添加新方法:使用替代录制方法
  1091. useAlternativeRecordingMethod() {
  1092. console.log('使用替代录制方法');
  1093. // 在iOS上,可以尝试使用chooseVideo API作为备选
  1094. uni.showActionSheet({
  1095. itemList: ['使用相册中的视频', '跳过此问题'],
  1096. success: (res) => {
  1097. if (res.tapIndex === 0) {
  1098. // 选择相册中的视频
  1099. uni.chooseVideo({
  1100. sourceType: ['album'],
  1101. maxDuration: 300, // 从60秒改为300秒
  1102. camera: 'front',
  1103. success: (res) => {
  1104. console.log('选择视频成功:', res.tempFilePath);
  1105. // 停止录制状态
  1106. this.isRecording = false;
  1107. this.showStopRecordingButton = false;
  1108. // 上传选择的视频
  1109. this.uploadRecordedVideo(res.tempFilePath);
  1110. },
  1111. fail: () => {
  1112. console.log('用户取消选择视频');
  1113. this.proceedToNextQuestion();
  1114. }
  1115. });
  1116. } else {
  1117. // 跳过此问题
  1118. console.log('用户选择跳过问题');
  1119. this.proceedToNextQuestion();
  1120. }
  1121. },
  1122. fail: () => {
  1123. console.log('操作取消');
  1124. this.proceedToNextQuestion();
  1125. }
  1126. });
  1127. },
  1128. // 添加新方法:请求小程序权限
  1129. requestMiniProgramPermissions() {
  1130. // 请求录音权限
  1131. uni.authorize({
  1132. scope: 'scope.record',
  1133. success: () => {
  1134. console.log('录音权限已获取');
  1135. // 请求相机权限
  1136. uni.authorize({
  1137. scope: 'scope.camera',
  1138. success: () => {
  1139. console.log('相机权限已获取');
  1140. // 权限都获取到后,开始录制
  1141. this.startMiniProgramRecording();
  1142. },
  1143. fail: (err) => {
  1144. console.error('相机权限获取失败:', err);
  1145. this.showPermissionDialog('相机');
  1146. }
  1147. });
  1148. },
  1149. fail: (err) => {
  1150. console.error('录音权限获取失败:', err);
  1151. this.showPermissionDialog('录音');
  1152. }
  1153. });
  1154. },
  1155. // 修改浏览器环境下的录制方法
  1156. startBrowserRecording() {
  1157. if (!this.cameraStream) {
  1158. console.error('没有可用的摄像头流');
  1159. uni.showToast({
  1160. title: '录制失败,摄像头未就绪',
  1161. icon: 'none'
  1162. });
  1163. this.proceedToNextQuestion();
  1164. return;
  1165. }
  1166. try {
  1167. // 检查流中是否包含音频轨道
  1168. const hasAudio = this.cameraStream.getAudioTracks().length > 0;
  1169. if (!hasAudio) {
  1170. console.warn('警告:媒体流中没有音频轨道,尝试重新获取带音频的媒体流');
  1171. // 尝试重新获取带音频的媒体流
  1172. navigator.mediaDevices.getUserMedia({
  1173. audio: {
  1174. echoCancellation: true,
  1175. noiseSuppression: true,
  1176. autoGainControl: true
  1177. },
  1178. video: true
  1179. })
  1180. .then(newStream => {
  1181. // 检查新流是否包含音频轨道
  1182. const audioTracks = newStream.getAudioTracks();
  1183. if (audioTracks.length > 0) {
  1184. console.log('成功获取音频轨道:', audioTracks[0].label);
  1185. // 合并视频和音频轨道
  1186. const videoTrack = this.cameraStream.getVideoTracks()[0];
  1187. const audioTrack = newStream.getAudioTracks()[0];
  1188. // 创建新的媒体流,包含视频和音频轨道
  1189. const combinedStream = new MediaStream();
  1190. if (videoTrack) combinedStream.addTrack(videoTrack);
  1191. if (audioTrack) combinedStream.addTrack(audioTrack);
  1192. this.cameraStream = combinedStream;
  1193. // 更新视频元素的源
  1194. const videoElement = this.$refs.userCameraVideo;
  1195. if (videoElement) {
  1196. videoElement.srcObject = combinedStream;
  1197. videoElement.muted = true; // 避免回声,但仍然录制声音
  1198. }
  1199. // 继续录制过程
  1200. this.setupMediaRecorder(combinedStream);
  1201. } else {
  1202. console.warn('仍然无法获取音频轨道');
  1203. // 使用现有流继续
  1204. this.setupMediaRecorder(this.cameraStream);
  1205. }
  1206. })
  1207. .catch(err => {
  1208. console.error('获取音频失败:', err);
  1209. // 使用现有流继续
  1210. this.setupMediaRecorder(this.cameraStream);
  1211. });
  1212. } else {
  1213. console.log('检测到音频轨道,直接使用');
  1214. // 已有音频轨道,直接使用
  1215. this.setupMediaRecorder(this.cameraStream);
  1216. }
  1217. } catch (error) {
  1218. console.error('浏览器录制失败:', error);
  1219. uni.showToast({
  1220. title: '录制失败,浏览器可能不支持此功能',
  1221. icon: 'none'
  1222. });
  1223. this.proceedToNextQuestion();
  1224. }
  1225. },
  1226. // 修改 setupMediaRecorder 方法
  1227. setupMediaRecorder(stream) {
  1228. // 检查流中的轨道
  1229. const videoTracks = stream.getVideoTracks();
  1230. const audioTracks = stream.getAudioTracks();
  1231. console.log('设置MediaRecorder - 视频轨道:', videoTracks.length, '音频轨道:', audioTracks.length);
  1232. // 尝试使用支持度更广的编码格式
  1233. let mimeType = '';
  1234. const supportedTypes = [
  1235. 'video/webm;codecs=vp9,opus',
  1236. 'video/webm;codecs=vp8,opus',
  1237. 'video/webm;codecs=h264,opus',
  1238. 'video/mp4;codecs=h264,aac',
  1239. 'video/webm',
  1240. 'video/mp4'
  1241. ];
  1242. for (const type of supportedTypes) {
  1243. if (MediaRecorder.isTypeSupported(type)) {
  1244. mimeType = type;
  1245. console.log('使用支持的MIME类型:', mimeType);
  1246. break;
  1247. }
  1248. }
  1249. // 创建MediaRecorder实例,设置较低的比特率以减小文件大小
  1250. const options = {
  1251. mimeType: mimeType || '',
  1252. audioBitsPerSecond: 64000, // 降低音频比特率
  1253. videoBitsPerSecond: 1000000, // 降低视频比特率到1Mbps
  1254. };
  1255. try {
  1256. this.mediaRecorder = new MediaRecorder(stream, options);
  1257. console.log('MediaRecorder创建成功,使用选项:', options);
  1258. } catch (e) {
  1259. console.warn('使用指定选项创建MediaRecorder失败,尝试使用默认选项');
  1260. this.mediaRecorder = new MediaRecorder(stream);
  1261. }
  1262. // 存储录制的数据块
  1263. this.recordedChunks = [];
  1264. // 监听数据可用事件
  1265. this.mediaRecorder.ondataavailable = (event) => {
  1266. if (event.data && event.data.size > 0) {
  1267. this.recordedChunks.push(event.data);
  1268. console.log(`收到数据块: ${event.data.size} 字节`);
  1269. }
  1270. };
  1271. // 监听录制停止事件
  1272. this.mediaRecorder.onstop = async () => {
  1273. console.log('MediaRecorder停止,数据块数量:', this.recordedChunks.length);
  1274. if (this.recordedChunks.length === 0) {
  1275. console.error('没有录制到数据');
  1276. uni.showToast({
  1277. title: '录制失败,未捕获到数据',
  1278. icon: 'none'
  1279. });
  1280. this.proceedToNextQuestion();
  1281. return;
  1282. }
  1283. // 创建Blob对象
  1284. const mimeType = this.mediaRecorder.mimeType || 'video/webm';
  1285. const blob = new Blob(this.recordedChunks, { type: mimeType });
  1286. console.log('创建Blob,原始大小:', blob.size, '类型:', mimeType);
  1287. // 显示压缩中提示
  1288. uni.showLoading({
  1289. title: '正在处理视频...',
  1290. mask: true
  1291. });
  1292. try {
  1293. // 压缩视频
  1294. const compressedBlob = await this.compressVideo(blob);
  1295. // 将Blob转换为File对象
  1296. const fileName = `answer_${this.currentVideoIndex}_${Date.now()}.webm`;
  1297. const file = new File([compressedBlob], fileName, { type: mimeType });
  1298. // 隐藏压缩提示
  1299. uni.hideLoading();
  1300. // 上传文件
  1301. this.uploadRecordedVideo(file);
  1302. } catch (error) {
  1303. console.error('视频处理失败:', error);
  1304. uni.hideLoading();
  1305. // 如果压缩失败,使用原始视频
  1306. const fileName = `answer_${this.currentVideoIndex}_${Date.now()}.webm`;
  1307. const file = new File([blob], fileName, { type: mimeType });
  1308. this.uploadRecordedVideo(file);
  1309. }
  1310. };
  1311. // 监听错误
  1312. this.mediaRecorder.onerror = (event) => {
  1313. console.error('MediaRecorder错误:', event.error);
  1314. };
  1315. // 开始录制
  1316. try {
  1317. this.mediaRecorder.start(1000); // 每秒触发一次dataavailable事件
  1318. console.log('MediaRecorder开始录制');
  1319. // 设置最大录制时间为60秒
  1320. // 注意:我们已经在startRecordingAnswer方法中设置了全局计时器
  1321. // 这里作为备份机制,确保即使全局计时器失效,也能停止录制
  1322. this.mediaRecorderTimeout = setTimeout(() => {
  1323. if (this.mediaRecorder && this.mediaRecorder.state === 'recording') {
  1324. console.log('MediaRecorder备份超时机制触发,停止录制');
  1325. this.mediaRecorder.stop();
  1326. }
  1327. }, 300000); // 300秒 (5分钟)
  1328. } catch (e) {
  1329. console.error('开始录制失败:', e);
  1330. }
  1331. },
  1332. // 添加新方法:停止录制用户回答
  1333. stopRecordingAnswer() {
  1334. console.log('停止录制用户回答');
  1335. if (this.countdownTimer) {
  1336. clearInterval(this.countdownTimer);
  1337. this.countdownTimer = null;
  1338. this.showCountdown = false;
  1339. }
  1340. // 检查录制时长
  1341. const recordingDuration = this.getRecordingDuration();
  1342. const minimumDuration = 5; // 最小录制时长(秒),从3秒改为5秒
  1343. if (recordingDuration < minimumDuration) {
  1344. // 录制时间过短,显示提示
  1345. uni.showToast({
  1346. title: '录制时间过短,请至少录制5秒',
  1347. icon: 'none',
  1348. duration: 2000
  1349. });
  1350. // 不执行停止录制逻辑,继续录制
  1351. return;
  1352. }
  1353. // 隐藏停止录制按钮
  1354. this.showStopRecordingButton = false;
  1355. // 停止录制计时器
  1356. if (this.recordingTimer) {
  1357. clearInterval(this.recordingTimer);
  1358. this.recordingTimer = null;
  1359. }
  1360. // 根据平台选择不同的停止录制方法
  1361. const systemInfo = uni.getSystemInfoSync();
  1362. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
  1363. if (isMiniProgram) {
  1364. // 小程序环境使用小程序的停止录制API
  1365. this.stopMiniProgramRecording();
  1366. } else {
  1367. // H5/App环境使用MediaRecorder API
  1368. this.stopBrowserRecording();
  1369. }
  1370. // 标记录制已停止
  1371. this.isRecording = false;
  1372. },
  1373. // 添加新方法:获取录制时长
  1374. getRecordingDuration() {
  1375. // 如果有明确的录制开始时间,计算实际录制时长
  1376. if (this.recordingStartTime) {
  1377. return (Date.now() - this.recordingStartTime) / 1000;
  1378. }
  1379. // 如果没有明确记录开始时间,尝试从视频元素获取
  1380. if (this.mediaRecorder && this.$refs.userCameraVideo) {
  1381. return this.$refs.userCameraVideo.currentTime || 0;
  1382. }
  1383. // 如果无法获取准确时长,返回估计值(如果有计时器)
  1384. if (this.recordingTimerCount) {
  1385. return this.recordingTimerCount;
  1386. }
  1387. // 默认返回0
  1388. return 0;
  1389. },
  1390. // 添加新方法:重置录制
  1391. resetRecording() {
  1392. // 保持录制状态,但重置计时器
  1393. if (this.recordingTimer) {
  1394. clearTimeout(this.recordingTimer);
  1395. }
  1396. // 重置录制开始时间
  1397. this.recordingStartTime = Date.now();
  1398. this.recordingTimerCount = 0;
  1399. // 如果是浏览器环境,需要重置MediaRecorder
  1400. if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
  1401. // 停止当前录制
  1402. this.mediaRecorder.stop();
  1403. // 清空已录制的数据块
  1404. this.recordedChunks = [];
  1405. // 短暂延迟后重新开始录制
  1406. setTimeout(() => {
  1407. this.startBrowserRecording();
  1408. }, 500);
  1409. }
  1410. // 如果是小程序环境,需要重置相机录制
  1411. else if (this.cameraContext) {
  1412. // 停止当前录制
  1413. this.cameraContext.stopRecord({
  1414. success: () => {
  1415. console.log('重置录制:停止当前录制成功');
  1416. // 短暂延迟后重新开始录制
  1417. setTimeout(() => {
  1418. this.startMiniProgramRecording();
  1419. }, 500);
  1420. },
  1421. fail: (err) => {
  1422. console.error('重置录制:停止当前录制失败', err);
  1423. // 尝试直接重新开始录制
  1424. this.startMiniProgramRecording();
  1425. }
  1426. });
  1427. }
  1428. // 显示提示
  1429. uni.showToast({
  1430. title: '请重新开始回答',
  1431. icon: 'none',
  1432. duration: 2000
  1433. });
  1434. },
  1435. // 修复 completeRecordingStop 方法,确保视频正确上传和处理
  1436. completeRecordingStop() {
  1437. console.log('完成录制停止');
  1438. // 隐藏停止录制按钮
  1439. this.showStopRecordingButton = false;
  1440. // 停止录制计时器
  1441. if (this.recordingTimer) {
  1442. clearInterval(this.recordingTimer);
  1443. this.recordingTimer = null;
  1444. }
  1445. // 标记录制已停止
  1446. this.isRecording = false;
  1447. // 显示上传中状态
  1448. this.showUploadStatus = true;
  1449. this.uploadStatusText = '正在处理视频...';
  1450. this.isUploading = true;
  1451. // 根据平台选择不同的停止录制方法
  1452. const systemInfo = uni.getSystemInfoSync();
  1453. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
  1454. if (isMiniProgram) {
  1455. // 小程序环境使用小程序的停止录制API
  1456. this.stopMiniProgramRecording();
  1457. } else {
  1458. // H5/App环境使用MediaRecorder API
  1459. this.stopBrowserRecording();
  1460. }
  1461. },
  1462. // 修复 stopMiniProgramRecording 方法,确保小程序环境下正确停止录制
  1463. stopMiniProgramRecording() {
  1464. console.log('停止小程序录制');
  1465. if (!this.cameraContext) {
  1466. console.error('相机上下文不存在');
  1467. this.handleRecordingError(new Error('相机上下文不存在'));
  1468. return;
  1469. }
  1470. try {
  1471. // 显示加载提示
  1472. uni.showLoading({
  1473. title: '正在处理视频...',
  1474. mask: true
  1475. });
  1476. // 停止录制
  1477. this.cameraContext.stopRecord({
  1478. success: (res) => {
  1479. console.log('停止录制成功:', res);
  1480. // 隐藏加载提示
  1481. uni.hideLoading();
  1482. // 获取视频临时路径
  1483. const tempVideoPath = res.tempVideoPath || res.tempFilePath;
  1484. if (tempVideoPath) {
  1485. console.log('获取到视频临时路径:', tempVideoPath);
  1486. // 上传视频
  1487. this.uploadRecordedVideo(tempVideoPath);
  1488. } else {
  1489. console.error('未获取到视频临时路径');
  1490. this.handleRecordingError(new Error('未获取到视频临时路径'));
  1491. }
  1492. },
  1493. fail: (err) => {
  1494. console.error('停止录制失败:', err);
  1495. uni.hideLoading();
  1496. this.handleRecordingError(err);
  1497. }
  1498. });
  1499. } catch (e) {
  1500. console.error('停止录制异常:', e);
  1501. uni.hideLoading();
  1502. this.handleRecordingError(e);
  1503. }
  1504. },
  1505. // 添加新方法:停止浏览器录制
  1506. stopBrowserRecording() {
  1507. if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
  1508. this.mediaRecorder.stop();
  1509. console.log('浏览器录制停止成功');
  1510. } else {
  1511. console.error('MediaRecorder不存在或已经停止');
  1512. this.proceedToNextQuestion();
  1513. }
  1514. },
  1515. // 修复 uploadRecordedVideo 方法,确保视频正确上传到服务器
  1516. uploadRecordedVideo(videoPath) {
  1517. console.log('开始上传录制的视频:', videoPath);
  1518. // 保存最后上传的视频路径,用于可能的重试
  1519. this.lastVideoToRetry = videoPath;
  1520. // 显示上传状态
  1521. this.showUploadStatus = true;
  1522. this.uploadStatusText = '正在上传视频...';
  1523. this.isUploading = true;
  1524. // 保存上传状态到本地存储
  1525. this.saveUploadStatus();
  1526. // 获取用户信息和租户ID
  1527. const tenant_id = uni.getStorageSync('tenant_id') || '1';
  1528. const openid = uni.getStorageSync('userInfo') ? JSON.parse(uni.getStorageSync('userInfo')).openid : '';
  1529. const application_id = uni.getStorageSync('appId') || '';
  1530. // 使用uni.uploadFile上传视频
  1531. const uploadTask = uni.uploadFile({
  1532. url: `${apiBaseUrl}/api/upload/`,
  1533. filePath: videoPath,
  1534. name: 'file',
  1535. formData: {
  1536. tenant_id: tenant_id,
  1537. openid: openid,
  1538. application_id: application_id,
  1539. biz_type: 'interview_video',
  1540. video_duration: this.recordingTimerCount || 0,
  1541. has_audio: 'true' // 明确标记包含音频
  1542. },
  1543. success: (uploadRes) => {
  1544. console.log('视频上传成功:', uploadRes);
  1545. try {
  1546. // 解析响应数据
  1547. const result = typeof uploadRes.data === 'string' ? JSON.parse(uploadRes.data) : uploadRes.data;
  1548. if ((result.success || result.code === 2000) && (result.data?.url || result.data?.permanent_link)) {
  1549. // 上传成功,获取视频URL
  1550. const videoUrl = result.data.url || result.data.permanent_link || '';
  1551. console.log('视频URL:', videoUrl);
  1552. // 更新上传状态
  1553. this.uploadStatusText = '视频处理完成,正在分析...';
  1554. // 保存上传状态
  1555. this.saveUploadStatus();
  1556. // 提交视频到AI语音交互接口
  1557. this.submitToAiVoiceInteraction(videoUrl);
  1558. } else {
  1559. console.error('上传响应格式错误:', result);
  1560. const errorMsg = result.msg || result.message || '上传响应格式错误';
  1561. this.handleUploadError(new Error(errorMsg));
  1562. }
  1563. } catch (e) {
  1564. console.error('解析上传响应失败:', e);
  1565. this.handleUploadError(e);
  1566. }
  1567. },
  1568. fail: (err) => {
  1569. console.error('视频上传失败:', err);
  1570. // 提供更友好的错误信息
  1571. let errorMessage = '网络错误,请检查网络连接';
  1572. if (err.errMsg) {
  1573. if (err.errMsg.includes('timeout')) {
  1574. errorMessage = '上传超时,请检查网络连接';
  1575. } else if (err.errMsg.includes('fail')) {
  1576. errorMessage = '上传失败: ' + err.errMsg;
  1577. }
  1578. }
  1579. this.handleUploadError(new Error(errorMessage));
  1580. },
  1581. complete: () => {
  1582. // 隐藏上传状态
  1583. this.showUploadStatus = false;
  1584. this.isUploading = false;
  1585. // 更新上传状态
  1586. this.saveUploadStatus();
  1587. }
  1588. });
  1589. // 监听上传进度
  1590. uploadTask.onProgressUpdate((res) => {
  1591. console.log('上传进度:', res.progress);
  1592. this.uploadStatusText = `正在上传视频... ${res.progress}%`;
  1593. // 如果上传速度过慢,提供提示
  1594. if (res.progress < 10 && res.totalTimeMs > 10000) {
  1595. this.uploadStatusText = `上传速度较慢,请耐心等待... ${res.progress}%`;
  1596. }
  1597. });
  1598. },
  1599. // 修改 processUploadQueue 方法,添加后台上传支持
  1600. processUploadQueue() {
  1601. // 如果队列为空,结束处理
  1602. if (this.uploadQueue.length === 0) {
  1603. this.isUploading = false;
  1604. this.showUploadStatus = false;
  1605. // 清除上传状态
  1606. try {
  1607. uni.removeStorageSync('videoUploadStatus');
  1608. } catch (e) {
  1609. console.error('清除上传状态失败:', e);
  1610. }
  1611. // 发送上传完成通知
  1612. this.notifyUploadComplete();
  1613. return;
  1614. }
  1615. // 标记为正在上传
  1616. this.isUploading = true;
  1617. this.showUploadStatus = true;
  1618. // 获取队列中的第一个任务
  1619. const task = this.uploadQueue[0];
  1620. // 更新任务状态
  1621. this.uploadStatus[task.id] = 'uploading';
  1622. this.updateUploadStatusText();
  1623. // 增加尝试次数
  1624. task.attempts++;
  1625. // 根据文件类型选择上传方法
  1626. if (typeof task.file !== 'string') {
  1627. // 浏览器环境,使用XMLHttpRequest上传
  1628. this.uploadFileWithXHR(task);
  1629. } else {
  1630. // 小程序环境,使用uni.uploadFile上传
  1631. this.uploadFileWithUni(task);
  1632. }
  1633. // 更新上传状态到本地存储
  1634. this.saveUploadStatus();
  1635. },
  1636. // 添加新方法:发送上传完成通知
  1637. notifyUploadComplete() {
  1638. // 使用uni.postMessage在页面间通信(小程序环境)
  1639. try {
  1640. uni.$emit('videoUploadComplete', {
  1641. timestamp: Date.now()
  1642. });
  1643. console.log('发送上传完成通知');
  1644. } catch (e) {
  1645. console.error('发送上传完成通知失败:', e);
  1646. }
  1647. // 如果在App环境,可以使用本地通知
  1648. const systemInfo = uni.getSystemInfoSync();
  1649. if (systemInfo.platform === 'android' || systemInfo.platform === 'ios') {
  1650. // 检查是否支持本地通知
  1651. if (plus && plus.push) {
  1652. plus.push.createMessage('视频上传完成', '您的面试视频已成功上传', {});
  1653. }
  1654. }
  1655. },
  1656. // 添加新方法:使用XMLHttpRequest上传文件
  1657. uploadFileWithXHR(task) {
  1658. // 获取用户信息
  1659. const userInfo = uni.getStorageSync('userInfo');
  1660. const openid = userInfo ? (JSON.parse(userInfo).openid || '') : '';
  1661. const tenant_id = uni.getStorageSync('tenant_id') || '1';
  1662. // 创建FormData
  1663. const formData = new FormData();
  1664. formData.append('file', task.file);
  1665. formData.append('openid', openid);
  1666. formData.append('tenant_id', tenant_id);
  1667. formData.append('application_id', uni.getStorageSync('appId'));
  1668. formData.append('question_id', task.questionId);
  1669. formData.append('video_duration', this.recordingTimerCount || 0);
  1670. formData.append('has_audio', 'true'); // 明确标记包含音频
  1671. // 创建XMLHttpRequest
  1672. const xhr = new XMLHttpRequest();
  1673. xhr.open('POST', `${apiBaseUrl}/api/upload/`, true);
  1674. xhr.timeout = 120000; // 2分钟超时
  1675. // 监听上传进度
  1676. xhr.upload.onprogress = (event) => {
  1677. if (event.lengthComputable) {
  1678. const percentComplete = Math.round((event.loaded / event.total) * 100);
  1679. this.uploadProgress[task.id] = percentComplete;
  1680. this.updateUploadStatusText();
  1681. }
  1682. };
  1683. // 监听请求完成
  1684. xhr.onload = () => {
  1685. if (xhr.status === 200) {
  1686. try {
  1687. const res = JSON.parse(xhr.responseText);
  1688. console.log('上传响应:', res);
  1689. if (res.code === 2000) {
  1690. // 获取上传后的视频URL
  1691. const videoUrl = res.data.url || res.data.photoUrl || '';
  1692. if (videoUrl) {
  1693. // 上传成功,更新状态
  1694. this.uploadStatus[task.id] = 'success';
  1695. this.updateUploadStatusText();
  1696. // 提交到面试接口
  1697. this.submitVideoToInterview(videoUrl, task);
  1698. } else {
  1699. this.handleUploadFailure(task, '视频URL获取失败');
  1700. }
  1701. } else {
  1702. this.handleUploadFailure(task, res.msg || '上传失败');
  1703. }
  1704. } catch (e) {
  1705. this.handleUploadFailure(task, '解析响应失败');
  1706. }
  1707. } else {
  1708. this.handleUploadFailure(task, 'HTTP状态: ' + xhr.status);
  1709. }
  1710. };
  1711. // 监听错误
  1712. xhr.onerror = () => {
  1713. this.handleUploadFailure(task, '网络错误');
  1714. };
  1715. // 监听超时
  1716. xhr.ontimeout = () => {
  1717. this.handleUploadFailure(task, '上传超时');
  1718. };
  1719. // 发送请求
  1720. xhr.send(formData);
  1721. },
  1722. // 添加新方法:使用uni.uploadFile上传文件
  1723. uploadFileWithUni(task) {
  1724. // 获取用户信息
  1725. const userInfo = uni.getStorageSync('userInfo');
  1726. const openid = userInfo ? (JSON.parse(userInfo).openid || '') : '';
  1727. const tenant_id = uni.getStorageSync('tenant_id') || '1';
  1728. // 创建上传任务
  1729. const uploadTask = uni.uploadFile({
  1730. url: `${apiBaseUrl}/api/upload/`,
  1731. filePath: task.file,
  1732. name: 'file',
  1733. formData: {
  1734. openid: openid,
  1735. tenant_id: tenant_id,
  1736. application_id: uni.getStorageSync('appId'),
  1737. question_id: task.questionId,
  1738. video_duration: this.recordingTimerCount || 0,
  1739. has_audio: 'true' // 明确标记包含音频
  1740. },
  1741. success: (uploadRes) => {
  1742. try {
  1743. const res = JSON.parse(uploadRes.data);
  1744. console.log('上传响应:', res);
  1745. if (res.code === 2000) {
  1746. // 获取上传后的视频URL
  1747. const videoUrl = res.data.permanent_link || res.data.url || '';
  1748. if (videoUrl) {
  1749. // 上传成功,更新状态
  1750. this.uploadStatus[task.id] = 'success';
  1751. this.updateUploadStatusText();
  1752. // 提交到面试接口
  1753. this.submitVideoToInterview(videoUrl, task);
  1754. } else {
  1755. this.handleUploadFailure(task, '视频URL获取失败');
  1756. }
  1757. } else {
  1758. this.handleUploadFailure(task, res.msg || '上传失败');
  1759. }
  1760. } catch (e) {
  1761. this.handleUploadFailure(task, '解析响应失败');
  1762. }
  1763. },
  1764. fail: (err) => {
  1765. this.handleUploadFailure(task, err.errMsg || '上传失败');
  1766. }
  1767. });
  1768. // 监听上传进度
  1769. uploadTask.onProgressUpdate((res) => {
  1770. this.uploadProgress[task.id] = res.progress;
  1771. this.updateUploadStatusText();
  1772. });
  1773. },
  1774. // 添加新方法:处理上传失败
  1775. handleUploadFailure(task, errorMsg) {
  1776. console.error('上传失败:', errorMsg);
  1777. // 更新任务状态
  1778. this.uploadStatus[task.id] = 'failed';
  1779. this.updateUploadStatusText();
  1780. // 检查是否还有重试机会
  1781. if (task.attempts < task.maxAttempts) {
  1782. console.log(`将在5秒后重试上传,当前尝试次数: ${task.attempts}/${task.maxAttempts}`);
  1783. // 5秒后重试
  1784. setTimeout(() => {
  1785. // 重置进度
  1786. this.uploadProgress[task.id] = 0;
  1787. // 重新开始上传
  1788. if (typeof task.file !== 'string') {
  1789. this.uploadFileWithXHR(task);
  1790. } else {
  1791. this.uploadFileWithUni(task);
  1792. }
  1793. }, 5000);
  1794. } else {
  1795. // 超过最大重试次数,移除任务并继续处理队列
  1796. console.log('超过最大重试次数,放弃上传');
  1797. // 显示错误提示
  1798. uni.showToast({
  1799. title: '视频上传失败,请稍后重试',
  1800. icon: 'none',
  1801. duration: 2000
  1802. });
  1803. // 从队列中移除当前任务
  1804. this.uploadQueue.shift();
  1805. // 继续处理队列中的下一个任务
  1806. this.processUploadQueue();
  1807. }
  1808. },
  1809. // 修改 submitVideoToInterview 方法
  1810. submitVideoToInterview(videoUrl, task = null) {
  1811. console.log('提交视频URL到面试接口:', videoUrl);
  1812. // 确定问题ID
  1813. let questionId;
  1814. if (task) {
  1815. questionId = task.questionId;
  1816. } else {
  1817. // 根据当前视频索引映射到正确的问题ID(兼容旧代码)
  1818. switch(this.currentVideoIndex) {
  1819. case 1:
  1820. questionId = 36;
  1821. break;
  1822. case 2:
  1823. questionId = 11;
  1824. break;
  1825. case 3:
  1826. questionId = 12;
  1827. break;
  1828. case 4:
  1829. questionId = 13;
  1830. break;
  1831. default:
  1832. questionId = 10;
  1833. }
  1834. }
  1835. // 准备请求参数
  1836. const requestData = {
  1837. application_id: uni.getStorageSync('appId'),
  1838. question_id: questionId,
  1839. video_url: videoUrl,
  1840. tenant_id: uni.getStorageSync('tenant_id') || '1',
  1841. has_audio: true // 明确标记包含音频
  1842. };
  1843. // 首先提交到面试接口
  1844. /* uni.request({
  1845. url: `${apiBaseUrl}/api/job/upload_video`,
  1846. method: 'POST',
  1847. data: requestData,
  1848. header: {
  1849. 'content-type': 'application/x-www-form-urlencoded'
  1850. },
  1851. success: (res) => {
  1852. console.log('面试接口提交成功:', res);
  1853. if (res.data.code === 0 || res.data.code === 2000) {
  1854. // 提交成功
  1855. if (task) {
  1856. // 从队列中移除当前任务
  1857. this.uploadQueue.shift();
  1858. // 继续处理队列中的下一个任务
  1859. this.processUploadQueue();
  1860. } else {
  1861. // 兼容旧代码的处理逻辑
  1862. uni.showToast({
  1863. title: '回答已提交',
  1864. icon: 'success'
  1865. });
  1866. // 保存最后上传的视频URL
  1867. this.lastUploadedVideoUrl = videoUrl;
  1868. // 隐藏重试按钮(如果之前显示了)
  1869. this.showRetryButton = false;
  1870. this.lastVideoToRetry = null;
  1871. }
  1872. // 提交到AI语音交互接口
  1873. } else {
  1874. // 提交失败
  1875. if (task) {
  1876. this.handleSubmitFailure(task, res.data.msg || '提交失败');
  1877. } else {
  1878. // 兼容旧代码的处理逻辑
  1879. uni.showToast({
  1880. title: res.data.msg || '提交失败,请重试',
  1881. icon: 'none'
  1882. });
  1883. // 保存失败的视频URL,用于重试
  1884. this.lastVideoToRetry = videoUrl;
  1885. // 显示重试按钮
  1886. this.showRetryButton = true;
  1887. }
  1888. }
  1889. },
  1890. fail: (err) => {
  1891. console.error('面试接口提交失败:', err);
  1892. if (task) {
  1893. this.handleSubmitFailure(task, err.errMsg || '网络错误');
  1894. } else {
  1895. // 兼容旧代码的处理逻辑
  1896. uni.hideLoading();
  1897. uni.showToast({
  1898. title: '网络错误,请重试',
  1899. icon: 'none'
  1900. });
  1901. // 保存失败的视频URL,用于重试
  1902. this.lastVideoToRetry = videoUrl;
  1903. // 显示重试按钮
  1904. this.showRetryButton = true;
  1905. }
  1906. }
  1907. }); */
  1908. this.submitToAiVoiceInteraction(videoUrl);
  1909. },
  1910. // 添加新方法:处理提交失败
  1911. handleSubmitFailure(task, errorMsg) {
  1912. console.error('提交失败:', errorMsg);
  1913. // 更新任务状态
  1914. this.uploadStatus[task.id] = 'failed';
  1915. this.updateUploadStatusText();
  1916. // 检查是否还有重试机会
  1917. if (task.attempts < task.maxAttempts) {
  1918. console.log(`将在5秒后重试提交,当前尝试次数: ${task.attempts}/${task.maxAttempts}`);
  1919. // 5秒后重试
  1920. setTimeout(() => {
  1921. // 重新提交
  1922. this.submitVideoToInterview(task.videoUrl, task);
  1923. }, 5000);
  1924. } else {
  1925. // 超过最大重试次数,移除任务并继续处理队列
  1926. console.log('超过最大重试次数,放弃提交');
  1927. // 显示错误提示
  1928. uni.showToast({
  1929. title: '视频提交失败,请稍后重试',
  1930. icon: 'none',
  1931. duration: 2000
  1932. });
  1933. // 从队列中移除当前任务
  1934. this.uploadQueue.shift();
  1935. // 继续处理队列中的下一个任务
  1936. this.processUploadQueue();
  1937. }
  1938. },
  1939. // 添加新方法:更新上传状态文本
  1940. updateUploadStatusText() {
  1941. if (this.uploadQueue.length === 0) {
  1942. this.uploadStatusText = '';
  1943. return;
  1944. }
  1945. const currentTask = this.uploadQueue[0];
  1946. const progress = this.uploadProgress[currentTask.id] || 0;
  1947. const status = this.uploadStatus[currentTask.id] || 'pending';
  1948. let statusText = '';
  1949. switch (status) {
  1950. case 'pending':
  1951. statusText = '等待上传';
  1952. break;
  1953. case 'uploading':
  1954. statusText = `上传中 ${progress}%`;
  1955. break;
  1956. case 'success':
  1957. statusText = '上传成功,提交中...';
  1958. break;
  1959. case 'failed':
  1960. statusText = `上传失败,${currentTask.attempts < currentTask.maxAttempts ? '即将重试' : '已放弃'}`;
  1961. break;
  1962. }
  1963. this.uploadStatusText = `问题${currentTask.questionId - 9}:${statusText}`;
  1964. // 如果队列中有多个任务,显示总数
  1965. if (this.uploadQueue.length > 1) {
  1966. this.uploadStatusText += ` (${this.uploadQueue.length}个视频待处理)`;
  1967. }
  1968. },
  1969. // 修改 proceedToNextQuestion 方法
  1970. proceedToNextQuestion() {
  1971. console.log('准备跳转到下一页面');
  1972. // 如果正在播放AI语音,不立即跳转
  1973. if (this.isPlayingAiVoice) {
  1974. console.log('AI语音正在播放,等待播放完成后再跳转');
  1975. return;
  1976. }
  1977. // 不再等待上传队列完成,直接跳转
  1978. // this.navigateToNextPage();
  1979. // 如果有未完成的上传任务,在后台继续处理
  1980. if (this.uploadQueue.length > 0) {
  1981. console.log('上传队列将在后台继续处理...');
  1982. // 保存上传状态到本地存储,以便在其他页面可以查看
  1983. this.saveUploadStatus();
  1984. }
  1985. },
  1986. // 修改 navigateToNextPage 方法
  1987. navigateToNextPage() {
  1988. console.log('执行页面跳转');
  1989. // 确保清理音频相关状态
  1990. this.isPlayingAiVoice = false;
  1991. this.currentSubtitle = '';
  1992. // 添加延迟确保状态已更新
  1993. setTimeout(() => {
  1994. uni.navigateTo({
  1995. url: '/pages/success/success',
  1996. success: () => {
  1997. console.log('页面跳转成功');
  1998. },
  1999. fail: (err) => {
  2000. console.error('页面跳转失败:', err);
  2001. uni.showToast({
  2002. title: '页面跳转失败',
  2003. icon: 'none',
  2004. duration: 2000
  2005. });
  2006. }
  2007. });
  2008. }, 100);
  2009. },
  2010. // 添加处理导航失败的方法
  2011. handleNavigationFailure() {
  2012. // 尝试跳转到其他页面
  2013. uni.navigateTo({
  2014. url: '/pages/success/success',//'/pages/posture-guide/posture-guide',
  2015. fail: (err2) => {
  2016. console.error('备用跳转也失败:', err2);
  2017. // 最后尝试返回上一页
  2018. uni.navigateBack({
  2019. delta: 1
  2020. });
  2021. }
  2022. });
  2023. },
  2024. // 修改 handleAnswerButtonClick 方法
  2025. handleAnswerButtonClick() {
  2026. // 隐藏答题按钮
  2027. this.showAnswerButton = false;
  2028. // 显示简短提示
  2029. uni.showToast({
  2030. title: '面试完成',
  2031. icon: 'success',
  2032. duration: 500 // 只显示0.5秒
  2033. });
  2034. // 如果有最后上传的视频URL,提交到AI语音交互接口
  2035. if (this.lastUploadedVideoUrl) {
  2036. this.submitToAiVoiceInteraction(this.lastUploadedVideoUrl);
  2037. } else {
  2038. // 没有视频URL,直接跳转
  2039. this.navigateToNextPage();
  2040. }
  2041. },
  2042. // 处理相机错误
  2043. handleCameraError(e) {
  2044. console.error('相机错误:', e);
  2045. // 获取平台信息
  2046. const systemInfo = uni.getSystemInfoSync();
  2047. const isIOS = systemInfo.platform === 'ios';
  2048. if (isIOS) {
  2049. console.log('iOS相机错误,尝试重新初始化');
  2050. // 显示提示
  2051. uni.showToast({
  2052. title: '相机初始化中...',
  2053. icon: 'loading',
  2054. duration: 2000
  2055. });
  2056. // 重置相机
  2057. this.resetCamera();
  2058. // 如果正在录制,停止录制
  2059. if (this.isRecording) {
  2060. this.isRecording = false;
  2061. this.showStopRecordingButton = false;
  2062. // 提供替代选项
  2063. setTimeout(() => {
  2064. this.useAlternativeRecordingMethod();
  2065. }, 1000);
  2066. }
  2067. } else {
  2068. // 显示错误提示
  2069. uni.showToast({
  2070. title: '相机初始化失败,请检查权限设置',
  2071. icon: 'none'
  2072. });
  2073. // 尝试备用选项
  2074. this.tryFallbackOptions();
  2075. }
  2076. },
  2077. // 添加新方法:尝试备用选项
  2078. tryFallbackOptions() {
  2079. // 检查环境
  2080. const systemInfo = uni.getSystemInfoSync();
  2081. // 在小程序环境中使用小程序API
  2082. if (systemInfo.uniPlatform === 'mp-weixin' || systemInfo.uniPlatform === 'mp-alipay') {
  2083. this.useMiniProgramCamera();
  2084. }
  2085. // 在H5环境中显示静态图像
  2086. else {
  2087. this.showStaticCameraPlaceholder();
  2088. }
  2089. },
  2090. // 添加新方法:使用小程序相机API
  2091. useMiniProgramCamera() {
  2092. console.log('尝试使用小程序相机组件');
  2093. // 这里需要在模板中添加小程序相机组件
  2094. // 并设置一个标志来控制显示
  2095. this.useMiniProgramCameraComponent = true;
  2096. },
  2097. // 添加新方法:显示静态图像
  2098. showStaticCameraPlaceholder() {
  2099. console.log('显示静态摄像头占位图');
  2100. // 创建一个图像元素
  2101. const img = document.createElement('img');
  2102. img.src = '/static/images/camera-placeholder.png'; // 确保有这个图片资源
  2103. img.className = 'static-camera-image';
  2104. img.style.width = '100%';
  2105. img.style.height = '100%';
  2106. img.style.objectFit = 'cover';
  2107. // 获取容器并添加图像
  2108. const container = this.$refs.userCameraVideo.parentNode;
  2109. container.appendChild(img);
  2110. },
  2111. // 处理视频时间更新事件
  2112. handleTimeUpdate(e) {
  2113. // 获取当前视频播放时间
  2114. const currentTime = e.target.currentTime;
  2115. // 如果正在录制,更新录制时间显示
  2116. if (this.isRecording && this.recordingTimerCount) {
  2117. this.recordingTimeDisplay = this.formatTime(this.recordingTimerCount);
  2118. }
  2119. // 根据当前播放的视频索引选择对应的字幕数组
  2120. let currentSubtitles;
  2121. if (this.currentVideoIndex === 0) {
  2122. currentSubtitles = this.subtitles;
  2123. } else if (this.currentVideoIndex === 1) {
  2124. currentSubtitles = this.secondVideoSubtitles;
  2125. } else if (this.currentVideoIndex === 2) {
  2126. currentSubtitles = this.thirdVideoSubtitles;
  2127. } else if (this.currentVideoIndex === 3) {
  2128. currentSubtitles = this.fourthVideoSubtitles;
  2129. } else if (this.currentVideoIndex === 4) {
  2130. currentSubtitles = this.fifthVideoSubtitles;
  2131. } else if (this.currentVideoIndex === 5) {
  2132. currentSubtitles = this.sixthVideoSubtitles;
  2133. } else {
  2134. // 如果有更多视频,可以继续添加条件
  2135. currentSubtitles = [];
  2136. }
  2137. // 查找当前时间应该显示的字幕
  2138. const subtitle = currentSubtitles.find(
  2139. sub => currentTime >= sub.startTime && currentTime < sub.endTime
  2140. );
  2141. // 更新当前字幕
  2142. this.currentSubtitle = subtitle ? subtitle.text : '';
  2143. },
  2144. // Add a new method to handle the "Start Recording" button click
  2145. handleStartRecordingClick() {
  2146. // 隐藏"开始回答"按钮
  2147. this.showStartRecordingButton = false;
  2148. // 如果倒计时正在进行,清除倒计时
  2149. this.clearCountdown();
  2150. // 开始录制
  2151. this.startRecordingAnswer();
  2152. },
  2153. // 修改 checkAudioPermission 方法,确保在录制前获取音频权限
  2154. checkAudioPermission() {
  2155. // 在小程序环境中
  2156. const systemInfo = uni.getSystemInfoSync();
  2157. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
  2158. if (isMiniProgram) {
  2159. // 小程序环境下的权限请求
  2160. uni.getSetting({
  2161. success: (res) => {
  2162. if (!res.authSetting['scope.record']) {
  2163. uni.authorize({
  2164. scope: 'scope.record',
  2165. success: () => {
  2166. console.log('录音权限已获取');
  2167. },
  2168. fail: (err) => {
  2169. console.error('录音权限获取失败:', err);
  2170. this.showPermissionDialog('录音');
  2171. }
  2172. });
  2173. }
  2174. if (!res.authSetting['scope.camera']) {
  2175. uni.authorize({
  2176. scope: 'scope.camera',
  2177. success: () => {
  2178. console.log('相机权限已获取');
  2179. },
  2180. fail: (err) => {
  2181. console.error('相机权限获取失败:', err);
  2182. this.showPermissionDialog('相机');
  2183. }
  2184. });
  2185. }
  2186. }
  2187. });
  2188. } else {
  2189. // 浏览器环境下的权限请求
  2190. // ... 保持原有代码不变
  2191. }
  2192. },
  2193. // 添加新方法:测试音频输入
  2194. testAudioInput() {
  2195. if (!this.cameraStream) {
  2196. console.warn('没有可用的媒体流,无法测试音频');
  2197. return;
  2198. }
  2199. const audioTracks = this.cameraStream.getAudioTracks();
  2200. if (audioTracks.length === 0) {
  2201. console.warn('没有检测到音频轨道,尝试重新获取');
  2202. this.tryGetAudioOnly();
  2203. return;
  2204. }
  2205. console.log('音频轨道信息:', audioTracks[0].getSettings());
  2206. // 创建音频上下文和分析器
  2207. try {
  2208. const AudioContext = window.AudioContext || window.webkitAudioContext;
  2209. if (!AudioContext) {
  2210. console.warn('浏览器不支持AudioContext');
  2211. return;
  2212. }
  2213. const audioContext = new AudioContext();
  2214. const analyser = audioContext.createAnalyser();
  2215. const microphone = audioContext.createMediaStreamSource(this.cameraStream);
  2216. microphone.connect(analyser);
  2217. // 设置分析器
  2218. analyser.fftSize = 256;
  2219. const bufferLength = analyser.frequencyBinCount;
  2220. const dataArray = new Uint8Array(bufferLength);
  2221. // 检测音频输入
  2222. let silenceCounter = 0;
  2223. const checkAudio = () => {
  2224. if (this.isRecording) return; // 如果正在录制,停止检测
  2225. analyser.getByteFrequencyData(dataArray);
  2226. // 计算平均音量
  2227. let sum = 0;
  2228. for (let i = 0; i < bufferLength; i++) {
  2229. sum += dataArray[i];
  2230. }
  2231. const average = sum / bufferLength;
  2232. if (average > 10) {
  2233. console.log('检测到音频输入,音量:', average);
  2234. silenceCounter = 0;
  2235. } else {
  2236. silenceCounter++;
  2237. if (silenceCounter > 10) {
  2238. console.warn('持续检测不到音频输入,可能麦克风未正常工作');
  2239. silenceCounter = 0;
  2240. }
  2241. }
  2242. // 继续检测
  2243. requestAnimationFrame(checkAudio);
  2244. };
  2245. // 开始检测
  2246. checkAudio();
  2247. } catch (e) {
  2248. console.error('音频测试失败:', e);
  2249. }
  2250. },
  2251. // 添加新方法:尝试单独获取音频
  2252. tryGetAudioOnly() {
  2253. navigator.mediaDevices.getUserMedia({ audio: true })
  2254. .then(audioStream => {
  2255. // 如果已有视频流,合并音频和视频轨道
  2256. if (this.cameraStream) {
  2257. const videoTrack = this.cameraStream.getVideoTracks()[0];
  2258. const audioTrack = audioStream.getAudioTracks()[0];
  2259. // 创建新的媒体流,包含视频和音频轨道
  2260. const combinedStream = new MediaStream();
  2261. if (videoTrack) combinedStream.addTrack(videoTrack);
  2262. if (audioTrack) combinedStream.addTrack(audioTrack);
  2263. // 更新摄像头流
  2264. this.cameraStream = combinedStream;
  2265. // 更新视频元素的源
  2266. const videoElement = this.$refs.userCameraVideo;
  2267. if (videoElement) {
  2268. videoElement.srcObject = combinedStream;
  2269. videoElement.muted = true; // 避免回声,但仍然录制声音
  2270. }
  2271. console.log('成功合并音频和视频轨道');
  2272. } else {
  2273. console.warn('没有视频流可合并');
  2274. }
  2275. })
  2276. .catch(err => {
  2277. console.error('单独获取音频失败:', err);
  2278. });
  2279. },
  2280. // 添加新方法:显示权限对话框
  2281. showPermissionDialog(permissionType) {
  2282. uni.showModal({
  2283. title: '需要权限',
  2284. content: `请允许使用${permissionType}权限,否则可能影响面试功能`,
  2285. confirmText: '去设置',
  2286. success: (res) => {
  2287. if (res.confirm) {
  2288. uni.openSetting({
  2289. success: (settingRes) => {
  2290. console.log('设置页面打开成功', settingRes);
  2291. }
  2292. });
  2293. }
  2294. }
  2295. });
  2296. },
  2297. // 添加重试上传方法
  2298. retryVideoUpload() {
  2299. if (this.lastVideoToRetry) {
  2300. // 隐藏重试按钮
  2301. this.showRetryButton = false;
  2302. // 显示加载提示
  2303. uni.showLoading({
  2304. title: '正在重新提交...',
  2305. mask: true
  2306. });
  2307. // 重新提交视频
  2308. this.submitVideoToInterview(this.lastVideoToRetry);
  2309. } else {
  2310. uni.showToast({
  2311. title: '没有可重试的视频',
  2312. icon: 'none'
  2313. });
  2314. }
  2315. },
  2316. // 添加一个新方法用于压缩视频
  2317. async compressVideo(videoBlob) {
  2318. // 如果视频大小小于某个阈值,直接返回原视频
  2319. if (videoBlob.size < 5 * 1024 * 1024) { // 小于5MB
  2320. return videoBlob;
  2321. }
  2322. console.log('开始压缩视频,原始大小:', videoBlob.size);
  2323. // 创建一个视频元素来加载视频
  2324. const videoElement = document.createElement('video');
  2325. videoElement.muted = true;
  2326. videoElement.autoplay = false;
  2327. // 创建一个canvas元素用于绘制视频帧
  2328. const canvas = document.createElement('canvas');
  2329. const ctx = canvas.getContext('2d');
  2330. // 设置视频源
  2331. videoElement.src = URL.createObjectURL(videoBlob);
  2332. return new Promise((resolve) => {
  2333. videoElement.onloadedmetadata = () => {
  2334. // 设置canvas尺寸为视频的一半
  2335. const width = Math.floor(videoElement.videoWidth / 2);
  2336. const height = Math.floor(videoElement.videoHeight / 2);
  2337. canvas.width = width;
  2338. canvas.height = height;
  2339. // 创建MediaRecorder来录制canvas
  2340. const stream = canvas.captureStream(15); // 15fps
  2341. // 如果原视频有音轨,添加到新流中
  2342. if (videoElement.captureStream) {
  2343. const originalStream = videoElement.captureStream();
  2344. const audioTracks = originalStream.getAudioTracks();
  2345. if (audioTracks.length > 0) {
  2346. stream.addTrack(audioTracks[0]);
  2347. }
  2348. }
  2349. // 设置较低的比特率
  2350. const options = {
  2351. mimeType: 'video/webm;codecs=vp8,opus',
  2352. audioBitsPerSecond: 64000,
  2353. videoBitsPerSecond: 800000 // 800kbps
  2354. };
  2355. const mediaRecorder = new MediaRecorder(stream, options);
  2356. const chunks = [];
  2357. mediaRecorder.ondataavailable = (e) => {
  2358. if (e.data.size > 0) {
  2359. chunks.push(e.data);
  2360. }
  2361. };
  2362. mediaRecorder.onstop = () => {
  2363. const compressedBlob = new Blob(chunks, { type: 'video/webm' });
  2364. console.log('视频压缩完成,压缩后大小:', compressedBlob.size);
  2365. resolve(compressedBlob);
  2366. };
  2367. // 开始播放视频并录制
  2368. videoElement.onplay = () => {
  2369. mediaRecorder.start(100);
  2370. // 绘制视频帧到canvas
  2371. const drawFrame = () => {
  2372. if (videoElement.paused || videoElement.ended) {
  2373. mediaRecorder.stop();
  2374. return;
  2375. }
  2376. ctx.drawImage(videoElement, 0, 0, width, height);
  2377. requestAnimationFrame(drawFrame);
  2378. };
  2379. drawFrame();
  2380. };
  2381. videoElement.play();
  2382. };
  2383. });
  2384. },
  2385. // 修改 checkIOSCameraRecordPermission 方法
  2386. checkIOSCameraRecordPermission() {
  2387. const systemInfo = uni.getSystemInfoSync();
  2388. if (systemInfo.platform !== 'ios') return;
  2389. // 在iOS上,需要同时请求相机和录音权限
  2390. uni.getSetting({
  2391. success: (res) => {
  2392. // 检查相机权限
  2393. if (!res.authSetting['scope.camera']) {
  2394. uni.authorize({
  2395. scope: 'scope.camera',
  2396. success: () => {
  2397. console.log('iOS相机权限已获取');
  2398. },
  2399. fail: (err) => {
  2400. console.error('iOS相机权限获取失败:', err);
  2401. this.showPermissionDialog('相机');
  2402. }
  2403. });
  2404. }
  2405. // 检查录音权限
  2406. if (!res.authSetting['scope.record']) {
  2407. uni.authorize({
  2408. scope: 'scope.record',
  2409. success: () => {
  2410. console.log('iOS录音权限已获取');
  2411. },
  2412. fail: (err) => {
  2413. console.error('iOS录音权限获取失败:', err);
  2414. this.showPermissionDialog('录音');
  2415. }
  2416. });
  2417. }
  2418. }
  2419. });
  2420. },
  2421. // 添加新方法:检查并修复渲染问题
  2422. checkAndFixRenderingIssues() {
  2423. // 检查全局对象,防止渲染错误
  2424. try {
  2425. // 检查是否有全局变量u
  2426. if (typeof u !== 'undefined' && u) {
  2427. // 检查currentQuestion属性
  2428. if (!u.currentQuestion) {
  2429. console.log('修复: 创建缺失的currentQuestion对象');
  2430. u.currentQuestion = {};
  2431. }
  2432. // 确保isImportant属性存在
  2433. if (u.currentQuestion && typeof u.currentQuestion.isImportant === 'undefined') {
  2434. console.log('修复: 设置缺失的isImportant属性');
  2435. u.currentQuestion.isImportant = false;
  2436. }
  2437. }
  2438. } catch (e) {
  2439. console.log('防御性检查异常:', e);
  2440. }
  2441. },
  2442. // 添加格式化时间的辅助方法
  2443. formatTime(seconds) {
  2444. if (!seconds && seconds !== 0) return '03:30'; // 默认显示03:30
  2445. const minutes = Math.floor(seconds / 60);
  2446. const remainingSeconds = seconds % 60;
  2447. return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
  2448. },
  2449. // 添加新方法:保存上传状态到本地存储
  2450. saveUploadStatus() {
  2451. const uploadStatus = {
  2452. isUploading: this.isUploading,
  2453. uploadQueue: this.uploadQueue.length,
  2454. timestamp: Date.now()
  2455. };
  2456. try {
  2457. uni.setStorageSync('videoUploadStatus', JSON.stringify(uploadStatus));
  2458. } catch (e) {
  2459. console.error('保存上传状态失败:', e);
  2460. }
  2461. },
  2462. // 修改 submitToAiVoiceInteraction 方法
  2463. submitToAiVoiceInteraction(videoUrl) {
  2464. console.log('提交视频到AI语音交互接口:', videoUrl);
  2465. // 显示加载提示
  2466. uni.showLoading({
  2467. title: '面试官正在思考...',
  2468. mask: true
  2469. });
  2470. // 获取用户信息和租户ID
  2471. const tenant_id = uni.getStorageSync('tenant_id') || '1';
  2472. const application_id = uni.getStorageSync('appId') || '98'; // 默认为98(报告)
  2473. let positionConfigId = 1;
  2474. if(JSON.parse(uni.getStorageSync('configData'))){
  2475. positionConfigId = JSON.parse(uni.getStorageSync('configData')).id;
  2476. }
  2477. // 准备请求数据
  2478. const requestData = {
  2479. voice_url: videoUrl,
  2480. tenant_id: tenant_id,
  2481. application_id: application_id,
  2482. scene_type: 'interview', // 场景类型:面试
  2483. // voice_type: 'longxiaoxia', // 角色:龙小侠
  2484. position_config_id: positionConfigId,
  2485. conversation_history: this.conversationHistory // 添加对话历史
  2486. };
  2487. // 检查环境
  2488. const systemInfo = uni.getSystemInfoSync();
  2489. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
  2490. if (isMiniProgram) {
  2491. // 小程序环境使用 uni.request
  2492. uni.request({
  2493. url: `${apiBaseUrl}/api/system/voice/mcp/interaction`, // 使用新的接口地址
  2494. method: 'POST',
  2495. data: requestData,
  2496. header: {
  2497. 'content-type': 'application/json' // 修改为JSON格式
  2498. },
  2499. success: (res) => {
  2500. if (res.statusCode === 200) {
  2501. this.handleAiInteractionResponse(res.data);
  2502. } else {
  2503. this.handleAiInteractionError(res.data);
  2504. }
  2505. },
  2506. fail: (err) => {
  2507. this.handleAiInteractionError(err);
  2508. }
  2509. });
  2510. } else {
  2511. // H5/App环境使用 XMLHttpRequest
  2512. const xhr = new XMLHttpRequest();
  2513. xhr.open('POST', `${apiBaseUrl}/api/system/voice/mcp/interaction`, true);
  2514. xhr.timeout = 60000; // 60秒超时
  2515. xhr.setRequestHeader('Content-Type', 'application/json');
  2516. xhr.onload = () => {
  2517. if (xhr.status === 200) {
  2518. try {
  2519. const response = JSON.parse(xhr.responseText);
  2520. this.handleAiInteractionResponse(response);
  2521. } catch (e) {
  2522. console.error('解析AI响应失败:', e);
  2523. this.handleAiInteractionError({ errMsg: '解析响应失败' });
  2524. }
  2525. } else {
  2526. this.handleAiInteractionError({ errMsg: 'HTTP状态: ' + xhr.status });
  2527. }
  2528. };
  2529. xhr.onerror = () => {
  2530. this.handleAiInteractionError({ errMsg: '网络错误' });
  2531. };
  2532. xhr.ontimeout = () => {
  2533. this.handleAiInteractionError({ errMsg: '请求超时' });
  2534. };
  2535. // 发送JSON格式的数据
  2536. xhr.send(JSON.stringify(requestData));
  2537. }
  2538. },
  2539. // 添加处理AI交互响应的方法
  2540. handleAiInteractionResponse(data) {
  2541. console.log('AI语音交互接口响应:', data);
  2542. // 获取系统信息
  2543. const systemInfo = uni.getSystemInfoSync();
  2544. const isIOS = systemInfo.platform === 'ios';
  2545. // 标记正在播放AI语音
  2546. this.isPlayingAiVoice = true;
  2547. // 隐藏加载提示
  2548. uni.hideLoading();
  2549. // 重置备选方法尝试标志
  2550. this.hasTriedFallbackMethod = false;
  2551. if (data && data.success) {
  2552. // 保存AI回复数据
  2553. this.aiText = data.ai_text || '';
  2554. this.transcribedText = data.transcribed_text ? data.transcribed_text.text : '';
  2555. // 记录对话历史
  2556. this.conversationHistory.push({
  2557. role: 'user',
  2558. content: this.transcribedText
  2559. });
  2560. this.conversationHistory.push({
  2561. role: 'assistant',
  2562. content: this.aiText
  2563. });
  2564. // 获取AI语音URL
  2565. const aiVoiceUrl = data.ai_voice_url || '';
  2566. if (aiVoiceUrl) {
  2567. // 构建完整的URL
  2568. this.aiVoiceUrl = aiVoiceUrl.startsWith('http')
  2569. ? aiVoiceUrl
  2570. : `${apiBaseUrl}${aiVoiceUrl}`;
  2571. console.log('AI语音URL:', this.aiVoiceUrl);
  2572. // 显示AI回复文本作为字幕
  2573. this.currentSubtitle = this.aiText;
  2574. // 检查平台
  2575. const systemInfo = uni.getSystemInfoSync();
  2576. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
  2577. // 检查音频URL是否包含不支持的格式
  2578. const isUnsupportedFormat = this.checkUnsupportedAudioFormat(this.aiVoiceUrl);
  2579. if (isUnsupportedFormat && isMiniProgram) {
  2580. console.warn('检测到小程序不支持的音频格式,直接使用文本显示');
  2581. this.displayTextResponse();
  2582. return;
  2583. }
  2584. // 根据平台选择不同的播放方法
  2585. if (isMiniProgram) {
  2586. // 小程序环境使用原生API
  2587. if (isIOS) {
  2588. this.playIOSMiniProgramAudio();
  2589. } else {
  2590. this.playMiniProgramAudio();
  2591. }
  2592. /* this.playMiniProgramAudio(); */
  2593. } else {
  2594. // H5/App环境使用通用方法
  2595. this.playAiVoice();
  2596. }
  2597. // 重要:确保在AI语音播放期间不显示继续提问按钮
  2598. this.showContinueQuestionButton = false;
  2599. this.showEndInterviewButton = false;
  2600. } else {
  2601. console.warn('未获取到AI语音URL,使用文本显示');
  2602. // 如果没有语音URL,显示文本回复
  2603. this.displayTextResponse();
  2604. }
  2605. } else {
  2606. console.error('AI语音交互失败:', data);
  2607. // AI交互失败,显示继续提问按钮
  2608. this.showContinueQuestionOptions();
  2609. // 检查是否需要自动跳转
  2610. this.checkPendingNavigation();
  2611. }
  2612. },
  2613. // 修改 handleAiInteractionError 方法,不要直接跳转,而是显示继续提问选项
  2614. handleAiInteractionError(err) {
  2615. console.error('AI语音交互请求失败:', err);
  2616. uni.hideLoading();
  2617. // 显示错误提示
  2618. uni.showToast({
  2619. title: 'AI处理失败,请重试',
  2620. icon: 'none',
  2621. duration: 2000
  2622. });
  2623. // 请求失败,显示继续提问选项,而不是直接跳转
  2624. this.showContinueQuestionOptions();
  2625. },
  2626. // 添加新方法:播放AI语音
  2627. async playAiVoice() {
  2628. console.log('开始播放AI语音:', this.aiVoiceUrl);
  2629. // 重置错误提示标记
  2630. this.hasShownTextFallbackToast = false;
  2631. // 标记正在播放AI语音
  2632. this.isPlayingAiVoice = true;
  2633. // 隐藏所有按钮
  2634. this.showContinueQuestionButton = false;
  2635. this.showEndInterviewButton = false;
  2636. // 显示AI回复文本作为字幕
  2637. this.currentSubtitle = this.aiText;
  2638. // 检查音频URL是否有效
  2639. if (!this.aiVoiceUrl || this.aiVoiceUrl.trim() === '') {
  2640. console.error('无效的音频URL,直接显示文本');
  2641. this.useTextFallbackAndNavigate();
  2642. return;
  2643. }
  2644. try {
  2645. // 获取系统信息
  2646. const systemInfo = uni.getSystemInfoSync();
  2647. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
  2648. const isIOS = systemInfo.platform === 'ios';
  2649. // 根据平台选择播放方式并等待播放完成
  2650. if (isMiniProgram) {
  2651. if (isIOS) {
  2652. await this.playIOSMiniProgramAudio();
  2653. } else {
  2654. await this.playMiniProgramAudio();
  2655. }
  2656. } else if (isIOS) {
  2657. await this.playAiVoiceForIOS();
  2658. } else {
  2659. await this.playAiVoiceForAndroid();
  2660. }
  2661. // 音频播放完成后再跳转
  2662. this.navigateToNextPage();
  2663. } catch (error) {
  2664. console.error('音频播放失败:', error);
  2665. this.useTextFallbackAndNavigate();
  2666. }
  2667. },
  2668. // 新增方法:文本回退并导航
  2669. useTextFallbackAndNavigate() {
  2670. console.log('使用文本回退并准备导航');
  2671. // 标记播放结束
  2672. this.isPlayingAiVoice = false;
  2673. // 显示友好提示
  2674. if (!this.hasShownTextFallbackToast) {
  2675. this.hasShownTextFallbackToast = true;
  2676. uni.showToast({
  2677. title: '为您显示文字回复',
  2678. icon: 'none',
  2679. duration: 2000
  2680. });
  2681. }
  2682. // 显示完整文本
  2683. this.currentSubtitle = this.aiText || '抱歉,AI回复内容加载失败';
  2684. // 给用户一定时间阅读文本后自动跳转
  2685. setTimeout(() => {
  2686. this.navigateToNextPage();
  2687. }, 5000); // 5秒后跳转
  2688. },
  2689. // 修改 handleIOSAudioPlaybackComplete 方法
  2690. handleIOSAudioPlaybackComplete() {
  2691. // 标记播放结束
  2692. this.isPlayingAiVoice = false;
  2693. // 延迟清空字幕
  2694. setTimeout(() => {
  2695. this.currentSubtitle = '';
  2696. }, 1000);
  2697. // 销毁音频播放器
  2698. if (this.aiAudioPlayer) {
  2699. try {
  2700. this.aiAudioPlayer.destroy();
  2701. } catch (e) {
  2702. console.error('销毁iOS音频播放器失败:', e);
  2703. }
  2704. this.aiAudioPlayer = null;
  2705. }
  2706. // 直接导航到下一页
  2707. this.navigateToNextPage();
  2708. },
  2709. // 修改 playMiniProgramAudio 方法
  2710. playMiniProgramAudio() {
  2711. return new Promise(async (resolve, reject) => {
  2712. try {
  2713. // 显示加载提示
  2714. uni.showLoading({
  2715. title: '音频加载中...',
  2716. mask: true
  2717. });
  2718. // 先下载音频文件
  2719. const localAudioPath = await this.preloadAudio(this.aiVoiceUrl);
  2720. // 隐藏加载提示
  2721. uni.hideLoading();
  2722. const audioContext = wx.createInnerAudioContext();
  2723. audioContext.src = localAudioPath; // 使用本地文件路径
  2724. audioContext.autoplay = true;
  2725. // 设置音频缓冲大小
  2726. audioContext.bufferSize = 4096;
  2727. let hasStarted = false;
  2728. let hasError = false;
  2729. audioContext.onPlay(() => {
  2730. console.log('AI语音开始播放');
  2731. hasStarted = true;
  2732. this.currentSubtitle = this.aiText;
  2733. });
  2734. audioContext.onEnded(() => {
  2735. console.log('AI语音播放结束');
  2736. this.isPlayingAiVoice = false;
  2737. this.currentSubtitle = '';
  2738. audioContext.destroy();
  2739. // 确保在播放完成后立即解析Promise并跳转
  2740. if (!hasError) {
  2741. console.log('准备跳转到下一页');
  2742. this.navigateToNextPage(); // 添加这行
  2743. resolve();
  2744. }
  2745. });
  2746. audioContext.onStop(() => {
  2747. console.log('AI语音播放停止');
  2748. this.isPlayingAiVoice = false;
  2749. this.currentSubtitle = '';
  2750. audioContext.destroy();
  2751. // 如果是正常停止(非错误导致),也要触发跳转
  2752. if (!hasError) {
  2753. console.log('播放停止,准备跳转到下一页');
  2754. this.navigateToNextPage(); // 添加这行
  2755. resolve();
  2756. }
  2757. });
  2758. audioContext.onError((err) => {
  2759. hasError = true;
  2760. console.error('AI语音播放错误:', err);
  2761. audioContext.destroy();
  2762. // 显示错误提示
  2763. uni.showToast({
  2764. title: '音频播放异常,将显示文字',
  2765. icon: 'none',
  2766. duration: 2000
  2767. });
  2768. // 尝试使用备选音频格式
  2769. if (this.aiVoiceUrl.endsWith('.mp3')) {
  2770. const wavUrl = this.aiVoiceUrl.replace('.mp3', '.wav');
  2771. console.log('尝试使用WAV格式:', wavUrl);
  2772. this.aiVoiceUrl = wavUrl;
  2773. this.playMiniProgramAudio()
  2774. .then(resolve)
  2775. .catch(reject);
  2776. } else {
  2777. reject(err);
  2778. }
  2779. });
  2780. // 设置超时检测
  2781. setTimeout(() => {
  2782. if (!hasStarted && !hasError) {
  2783. console.error('音频播放启动超时');
  2784. audioContext.destroy();
  2785. reject(new Error('音频播放启动超时'));
  2786. }
  2787. }, 5000);
  2788. } catch (error) {
  2789. uni.hideLoading();
  2790. console.error('音频播放初始化失败:', error);
  2791. reject(error);
  2792. }
  2793. });
  2794. },
  2795. // 新增方法:导航到下一页
  2796. navigateToNextPage() {
  2797. console.log('执行页面跳转');
  2798. // 确保清理音频相关状态
  2799. this.isPlayingAiVoice = false;
  2800. this.currentSubtitle = '';
  2801. // 添加延迟确保状态已更新
  2802. setTimeout(() => {
  2803. uni.navigateTo({
  2804. url: '/pages/success/success',
  2805. success: () => {
  2806. console.log('页面跳转成功');
  2807. },
  2808. fail: (err) => {
  2809. console.error('页面跳转失败:', err);
  2810. uni.showToast({
  2811. title: '页面跳转失败',
  2812. icon: 'none',
  2813. duration: 2000
  2814. });
  2815. }
  2816. });
  2817. }, 100);
  2818. },
  2819. // 新增方法:专门处理iOS小程序音频播放
  2820. playIOSMiniProgramAudio() {
  2821. return new Promise((resolve, reject) => {
  2822. try {
  2823. const audioContext = wx.createInnerAudioContext();
  2824. audioContext.src = this.aiVoiceUrl;
  2825. audioContext.autoplay = true;
  2826. audioContext.onPlay(() => {
  2827. console.log('iOS小程序音频开始播放');
  2828. });
  2829. audioContext.onEnded(() => {
  2830. console.log('iOS小程序音频播放完成');
  2831. audioContext.destroy();
  2832. resolve();
  2833. });
  2834. audioContext.onError((err) => {
  2835. console.error('iOS小程序音频播放错误:', err);
  2836. audioContext.destroy();
  2837. reject(err);
  2838. });
  2839. } catch (error) {
  2840. reject(error);
  2841. }
  2842. });
  2843. },
  2844. playAiVoiceForIOS() {
  2845. return new Promise((resolve, reject) => {
  2846. try {
  2847. const audioContext = new Audio();
  2848. audioContext.src = this.aiVoiceUrl;
  2849. audioContext.autoplay = true;
  2850. audioContext.addEventListener('play', () => {
  2851. console.log('iOS音频开始播放');
  2852. });
  2853. audioContext.addEventListener('ended', () => {
  2854. console.log('iOS音频播放完成');
  2855. resolve();
  2856. });
  2857. audioContext.addEventListener('error', (err) => {
  2858. console.error('iOS音频播放错误:', err);
  2859. reject(err);
  2860. });
  2861. } catch (error) {
  2862. reject(error);
  2863. }
  2864. });
  2865. },
  2866. playAiVoiceForAndroid() {
  2867. return new Promise((resolve, reject) => {
  2868. try {
  2869. const audioContext = new Audio();
  2870. audioContext.src = this.aiVoiceUrl;
  2871. audioContext.autoplay = true;
  2872. audioContext.addEventListener('play', () => {
  2873. console.log('Android音频开始播放');
  2874. });
  2875. audioContext.addEventListener('ended', () => {
  2876. console.log('Android音频播放完成');
  2877. resolve();
  2878. });
  2879. audioContext.addEventListener('error', (err) => {
  2880. console.error('Android音频播放错误:', err);
  2881. reject(err);
  2882. });
  2883. } catch (error) {
  2884. reject(error);
  2885. }
  2886. });
  2887. },
  2888. // 新增方法:iOS小程序音频预下载
  2889. preloadIOSMiniProgramAudio(audioUrl) {
  2890. return new Promise((resolve, reject) => {
  2891. console.log('开始预下载iOS小程序音频:', audioUrl);
  2892. uni.downloadFile({
  2893. url: audioUrl,
  2894. timeout: 15000, // 15秒超时
  2895. success: (res) => {
  2896. if (res.statusCode === 200) {
  2897. console.log('iOS小程序音频下载成功:', res.tempFilePath);
  2898. resolve(res.tempFilePath);
  2899. } else {
  2900. console.error('iOS小程序音频下载失败,状态码:', res.statusCode);
  2901. reject(new Error(`下载失败,状态码: ${res.statusCode}`));
  2902. }
  2903. },
  2904. fail: (err) => {
  2905. console.error('iOS小程序音频下载请求失败:', err);
  2906. reject(err);
  2907. }
  2908. });
  2909. });
  2910. },
  2911. // 新增方法:iOS小程序错误处理
  2912. handleIOSMiniProgramError(audioContext, error) {
  2913. console.error('处理iOS小程序音频错误:', error);
  2914. // 销毁音频播放器
  2915. if (audioContext) {
  2916. try {
  2917. audioContext.destroy();
  2918. } catch (e) {
  2919. console.error('销毁音频播放器失败:', e);
  2920. }
  2921. }
  2922. // 根据错误类型显示不同的提示信息
  2923. let errorMessage = '音频播放异常,显示文字';
  2924. if (error.errMsg && error.errMsg.includes('-11850')) {
  2925. console.log('iOS小程序检测到系统音频错误(-11850)');
  2926. errorMessage = '系统音频服务暂停,显示文字';
  2927. } else if (error.errCode === 10002) {
  2928. console.log('iOS小程序检测到errCode:10002,网络或资源问题');
  2929. errorMessage = '音频加载中断,显示文字';
  2930. } else if (error.errCode === 10001) {
  2931. console.log('iOS小程序检测到errCode:10001,系统错误');
  2932. errorMessage = '系统音频错误,显示文字';
  2933. } else if (error.errCode === 10003) {
  2934. console.log('iOS小程序检测到errCode:10003,文件错误');
  2935. errorMessage = '音频文件错误,显示文字';
  2936. } else if (error.errCode === 10004) {
  2937. console.log('iOS小程序检测到errCode:10004,格式不支持');
  2938. errorMessage = '音频格式不支持,显示文字';
  2939. }
  2940. // 显示用户友好的错误提示
  2941. uni.showToast({
  2942. title: errorMessage,
  2943. icon: 'none',
  2944. duration: 2000
  2945. });
  2946. // 使用文本回退
  2947. this.useIOSTextFallback();
  2948. },
  2949. // 新增方法:iOS小程序播放超时处理
  2950. handleIOSPlaybackTimeout(audioContext) {
  2951. console.log('iOS小程序音频播放超时处理');
  2952. // 销毁音频播放器
  2953. if (audioContext) {
  2954. try {
  2955. audioContext.destroy();
  2956. } catch (e) {
  2957. console.error('销毁超时音频播放器失败:', e);
  2958. }
  2959. }
  2960. // 显示超时提示
  2961. /* uni.showToast({
  2962. title: '音频加载超时,显示文字',
  2963. icon: 'none',
  2964. duration: 2000
  2965. }); */
  2966. // 使用文本回退
  2967. this.useIOSTextFallback();
  2968. },
  2969. // 新增方法:iOS小程序备选播放方法
  2970. fallbackIOSMiniProgramPlay(audioContext) {
  2971. console.log('iOS小程序使用备选播放方法');
  2972. try {
  2973. // 直接设置原始URL
  2974. audioContext.src = this.aiVoiceUrl;
  2975. // 设置较短的超时时间
  2976. const fallbackTimeout = setTimeout(() => {
  2977. if (this.isPlayingAiVoice) {
  2978. console.log('iOS小程序备选方法也超时');
  2979. clearTimeout(fallbackTimeout);
  2980. this.handleIOSPlaybackTimeout(audioContext);
  2981. }
  2982. }, 3000);
  2983. // 尝试播放
  2984. audioContext.play();
  2985. } catch (e) {
  2986. console.error('iOS小程序备选播放方法失败:', e);
  2987. this.handleIOSPlaybackTimeout(audioContext);
  2988. }
  2989. },
  2990. // 新增方法:统一的iOS音频完成处理
  2991. handleIOSAudioComplete(audioContext) {
  2992. console.log('iOS音频播放完成');
  2993. // 标记播放结束
  2994. this.isPlayingAiVoice = false;
  2995. // 延迟清空字幕,让用户有时间阅读
  2996. setTimeout(() => {
  2997. this.currentSubtitle = '';
  2998. }, 2000);
  2999. // 销毁音频播放器
  3000. if (audioContext) {
  3001. try {
  3002. audioContext.destroy();
  3003. } catch (e) {
  3004. console.error('销毁iOS音频播放器失败:', e);
  3005. }
  3006. }
  3007. // 显示继续提问选项
  3008. this.showContinueQuestionOptions();
  3009. // 检查是否需要自动跳转
  3010. this.checkPendingNavigation();
  3011. },
  3012. // 移除原来的 playMiniProgramAudioForIOS 方法,因为已经被新的 playIOSMiniProgramAudio 替代
  3013. // playMiniProgramAudioForIOS() 方法可以删除或注释掉
  3014. // 保留原有的 useIOSTextFallback 方法,但确保它能正确处理所有iOS场景
  3015. useIOSTextFallback() {
  3016. console.log('iOS使用文本回退方案');
  3017. // 确保播放状态正确
  3018. this.isPlayingAiVoice = false;
  3019. // 显示友好提示(如果还没有显示过)
  3020. if (!this.hasShownTextFallbackToast) {
  3021. this.hasShownTextFallbackToast = true;
  3022. }
  3023. // 显示完整文本和继续按钮
  3024. this.currentSubtitle = this.aiText || '抱歉,AI回复内容加载失败';
  3025. this.showNextButton = true; // 添加一个变量控制按钮显示
  3026. },
  3027. // 添加处理继续按钮点击的方法
  3028. handleNextButtonClick() {
  3029. this.showNextButton = false;
  3030. this.handleIOSAudioComplete(null);
  3031. },
  3032. // 添加新方法:iOS音频播放完成处理
  3033. handleIOSAudioPlaybackComplete() {
  3034. // 标记播放结束
  3035. this.isPlayingAiVoice = false;
  3036. // 延迟清空字幕,让用户有时间阅读
  3037. setTimeout(() => {
  3038. this.currentSubtitle = '';
  3039. }, 2000);
  3040. // 销毁音频播放器
  3041. if (this.aiAudioPlayer) {
  3042. try {
  3043. this.aiAudioPlayer.destroy();
  3044. } catch (e) {
  3045. console.error('销毁iOS音频播放器失败:', e);
  3046. }
  3047. this.aiAudioPlayer = null;
  3048. }
  3049. // 显示继续提问选项
  3050. this.showContinueQuestionOptions();
  3051. // 检查是否需要自动跳转
  3052. this.checkPendingNavigation();
  3053. },
  3054. // 添加新方法:iOS音频错误处理
  3055. handleIOSAudioError(error) {
  3056. console.error('iOS音频播放错误:', error);
  3057. // 根据错误码进行不同处理
  3058. switch (error.errCode) {
  3059. case 10001:
  3060. console.log('iOS音频系统错误,尝试重新播放');
  3061. this.retryIOSAudioPlay();
  3062. break;
  3063. case 10002:
  3064. console.log('iOS音频网络错误,使用备选方案');
  3065. this.handleIOS10002Error();
  3066. break;
  3067. case 10003:
  3068. console.log('iOS音频文件错误,使用文本回退');
  3069. this.useIOSTextFallback();
  3070. break;
  3071. case 10004:
  3072. console.log('iOS音频格式不支持,使用文本回退');
  3073. this.useIOSTextFallback();
  3074. break;
  3075. default:
  3076. console.log('iOS音频未知错误,使用文本回退');
  3077. this.useIOSTextFallback();
  3078. break;
  3079. }
  3080. },
  3081. // 添加新方法:重试iOS音频播放
  3082. retryIOSAudioPlay() {
  3083. console.log('重试iOS音频播放');
  3084. // 销毁当前播放器
  3085. if (this.aiAudioPlayer) {
  3086. try {
  3087. this.aiAudioPlayer.destroy();
  3088. } catch (e) {
  3089. console.error('销毁播放器失败:', e);
  3090. }
  3091. this.aiAudioPlayer = null;
  3092. }
  3093. // 延迟后重试
  3094. setTimeout(() => {
  3095. this.fallbackIOSAudioPlay();
  3096. }, 1000);
  3097. },
  3098. // 添加新方法:iOS备选音频播放
  3099. fallbackIOSAudioPlay() {
  3100. console.log('iOS备选音频播放方案');
  3101. try {
  3102. // 创建新的音频播放器
  3103. this.aiAudioPlayer = uni.createInnerAudioContext();
  3104. // 使用更保守的设置
  3105. this.aiAudioPlayer.autoplay = true;
  3106. this.aiAudioPlayer.obeyMuteSwitch = true; // 遵循静音开关
  3107. this.aiAudioPlayer.volume = 0.8;
  3108. // 直接使用原URL
  3109. this.aiAudioPlayer.src = this.aiVoiceUrl;
  3110. // 设置简化的事件监听
  3111. this.aiAudioPlayer.onPlay(() => {
  3112. console.log('iOS备选方案:音频开始播放');
  3113. this.currentSubtitle = this.aiText;
  3114. });
  3115. this.aiAudioPlayer.onEnded(() => {
  3116. console.log('iOS备选方案:音频播放结束');
  3117. this.handleIOSAudioPlaybackComplete();
  3118. });
  3119. this.aiAudioPlayer.onError((err) => {
  3120. console.error('iOS备选方案:音频播放错误:', err);
  3121. this.useIOSTextFallback();
  3122. });
  3123. // 设置超时,如果5秒内没有开始播放,使用文本回退
  3124. setTimeout(() => {
  3125. if (this.isPlayingAiVoice && this.aiAudioPlayer) {
  3126. console.log('iOS音频播放超时,使用文本回退');
  3127. this.useIOSTextFallback();
  3128. }
  3129. }, 5000);
  3130. } catch (e) {
  3131. console.error('iOS备选音频播放失败:', e);
  3132. this.useIOSTextFallback();
  3133. }
  3134. },
  3135. // 修改 playMiniProgramAudio 方法,添加iOS特殊处理
  3136. /* playMiniProgramAudio() {
  3137. console.log('使用小程序原生音频API播放:', this.aiVoiceUrl);
  3138. // 标记正在播放AI语音
  3139. this.isPlayingAiVoice = true;
  3140. // 确保在播放期间不显示继续提问按钮
  3141. this.showContinueQuestionButton = false;
  3142. this.showEndInterviewButton = false;
  3143. // 检查音频URL是否有效
  3144. if (!this.aiVoiceUrl || this.aiVoiceUrl.trim() === '') {
  3145. console.error('无效的音频URL');
  3146. this.handleAudioPlaybackFailure();
  3147. return;
  3148. }
  3149. // 检查平台
  3150. const systemInfo = uni.getSystemInfoSync();
  3151. const isIOS = systemInfo.platform === 'ios';
  3152. // iOS小程序特殊处理
  3153. if (isIOS) {
  3154. this.playMiniProgramAudioForIOS();
  3155. return;
  3156. }
  3157. // 非iOS平台的原有逻辑
  3158. try {
  3159. // 使用wx.createInnerAudioContext API (微信小程序)
  3160. const audioContext = wx.createInnerAudioContext();
  3161. // 设置音频属性
  3162. audioContext.autoplay = false;
  3163. audioContext.obeyMuteSwitch = false; // 忽略静音开关
  3164. // 监听播放开始事件
  3165. audioContext.onPlay(() => {
  3166. console.log('AI语音开始播放');
  3167. // 显示正在播放提示
  3168. });
  3169. // 监听播放结束事件
  3170. audioContext.onEnded(() => {
  3171. console.log('AI语音播放结束');
  3172. // 标记播放结束
  3173. this.isPlayingAiVoice = false;
  3174. // 清空字幕
  3175. this.currentSubtitle = '';
  3176. // 销毁音频播放器
  3177. audioContext.destroy();
  3178. // 播放结束后显示继续提问选项,而不是直接跳转
  3179. this.showContinueQuestionOptions();
  3180. });
  3181. // 监听播放错误事件
  3182. audioContext.onError((err) => {
  3183. console.error('AI语音播放错误:', err);
  3184. // 标记播放结束
  3185. this.isPlayingAiVoice = false;
  3186. // 清空字幕
  3187. this.currentSubtitle = '';
  3188. // 销毁音频播放器
  3189. audioContext.destroy();
  3190. // 播放错误时也显示继续提问选项
  3191. this.showContinueQuestionOptions();
  3192. });
  3193. // 设置音频源
  3194. audioContext.src = this.aiVoiceUrl;
  3195. // 添加超时处理,如果5秒内没有开始播放,则认为出错
  3196. const playTimeout = setTimeout(() => {
  3197. if (this.isPlayingAiVoice) {
  3198. console.warn('小程序音频播放超时,尝试备选方法');
  3199. this.tryMiniProgramFallbackAudioPlay();
  3200. }
  3201. }, 5000);
  3202. // 延迟一小段时间再播放,确保src已经设置完成
  3203. setTimeout(() => {
  3204. audioContext.play();
  3205. // 播放开始后清除超时
  3206. clearTimeout(playTimeout);
  3207. }, 300);
  3208. } catch (e) {
  3209. console.error('小程序播放AI语音时发生错误:', e);
  3210. // 标记播放结束
  3211. this.isPlayingAiVoice = false;
  3212. // 显示错误提示
  3213. // 使用文本显示方式作为备选方案
  3214. this.handleAudioPlaybackFailure();
  3215. }
  3216. }, */
  3217. // 添加新方法:iOS小程序音频播放
  3218. playMiniProgramAudioForIOS() {
  3219. console.log('iOS小程序环境:开始播放AI语音');
  3220. // 重置错误标记
  3221. this.hasShownTextFallbackToast = false;
  3222. try {
  3223. // 创建音频上下文
  3224. const audioContext = wx.createInnerAudioContext();
  3225. // iOS小程序特殊配置
  3226. audioContext.autoplay = false;
  3227. audioContext.obeyMuteSwitch = true; // iOS上遵循静音开关
  3228. audioContext.volume = 1.0;
  3229. // 设置错误处理
  3230. audioContext.onError((err) => {
  3231. console.error('iOS小程序音频播放错误:', err);
  3232. // 检查具体错误类型
  3233. if (err.errMsg && err.errMsg.includes('-11850')) {
  3234. console.log('iOS小程序检测到系统音频错误(-11850)');
  3235. /* uni.showToast({
  3236. title: '系统音频暂停,显示文字',
  3237. icon: 'none',
  3238. duration: 2000
  3239. }); */
  3240. } else if (err.errCode === 10002) {
  3241. console.log('iOS小程序检测到errCode:10002,网络或资源问题');
  3242. /* uni.showToast({
  3243. title: '音频加载中断,显示文字',
  3244. icon: 'none',
  3245. duration: 2000
  3246. }); */
  3247. } else {
  3248. console.log('iOS小程序其他音频错误:', err.errCode);
  3249. /* uni.showToast({
  3250. title: '音频播放异常,显示文字',
  3251. icon: 'none',
  3252. duration: 2000
  3253. }); */
  3254. }
  3255. this.useIOSMiniProgramTextFallback(audioContext);
  3256. });
  3257. // 先尝试直接播放,如果失败再下载
  3258. audioContext.src = this.aiVoiceUrl;
  3259. // 设置成功事件监听
  3260. audioContext.onPlay(() => {
  3261. console.log('iOS小程序音频开始播放');
  3262. this.currentSubtitle = this.aiText;
  3263. /* uni.showToast({
  3264. title: '正在播放AI回复',
  3265. icon: 'none',
  3266. duration: 1500
  3267. }); */
  3268. });
  3269. audioContext.onEnded(() => {
  3270. console.log('iOS小程序音频播放结束');
  3271. this.handleIOSMiniProgramAudioComplete(audioContext);
  3272. });
  3273. // 设置较短的播放超时时间
  3274. const playTimeout = setTimeout(() => {
  3275. if (this.isPlayingAiVoice) {
  3276. console.log('iOS小程序音频播放超时,切换到文本显示');
  3277. clearTimeout(playTimeout);
  3278. this.useIOSMiniProgramTextFallback(audioContext);
  3279. }
  3280. }, 3000); // 缩短到3秒
  3281. // 尝试播放
  3282. audioContext.play();
  3283. } catch (e) {
  3284. console.error('iOS小程序音频播放初始化失败:', e);
  3285. this.handleAudioPlaybackFailure();
  3286. }
  3287. },
  3288. // 添加新方法:iOS小程序音频播放完成
  3289. handleIOSMiniProgramAudioComplete(audioContext) {
  3290. this.isPlayingAiVoice = false;
  3291. setTimeout(() => {
  3292. this.currentSubtitle = '';
  3293. }, 2000);
  3294. if (audioContext) {
  3295. try {
  3296. audioContext.destroy();
  3297. } catch (e) {
  3298. console.error('销毁iOS小程序音频播放器失败:', e);
  3299. }
  3300. }
  3301. this.showContinueQuestionOptions();
  3302. this.checkPendingNavigation();
  3303. },
  3304. // 添加新方法:iOS小程序音频错误处理
  3305. handleIOSMiniProgramAudioError(audioContext, error) {
  3306. console.error('iOS小程序音频错误:', error);
  3307. // 根据错误码处理
  3308. if (error.errCode === 10002) {
  3309. this.useIOSMiniProgramTextFallback(audioContext);
  3310. } else {
  3311. // 其他错误也使用文本回退
  3312. this.useIOSMiniProgramTextFallback(audioContext);
  3313. }
  3314. },
  3315. // 添加新方法:iOS小程序文本回退
  3316. useIOSMiniProgramTextFallback(audioContext) {
  3317. console.log('iOS小程序使用文本回退方案');
  3318. // 销毁音频播放器
  3319. if (audioContext) {
  3320. try {
  3321. audioContext.destroy();
  3322. } catch (e) {
  3323. console.error('销毁音频播放器失败:', e);
  3324. }
  3325. }
  3326. // 确保播放状态正确
  3327. this.isPlayingAiVoice = false;
  3328. // 显示完整文本
  3329. this.currentSubtitle = this.aiText || '抱歉,AI回复内容加载失败';
  3330. // 根据文本长度计算阅读时间
  3331. const textLength = this.aiText ? this.aiText.length : 20;
  3332. const readingTime = Math.max(6000, Math.min(textLength * 120, 18000)); // 最少6秒,最多18秒
  3333. setTimeout(() => {
  3334. this.handleIOSMiniProgramAudioComplete(null);
  3335. }, readingTime);
  3336. },
  3337. // 添加新方法:处理音频播放错误
  3338. handleAudioPlaybackError(error) {
  3339. console.error('音频播放错误:', error);
  3340. // 尝试使用备选方法
  3341. if (!this.hasTriedFallbackMethod) {
  3342. this.hasTriedFallbackMethod = true;
  3343. this.tryFallbackAudioPlay();
  3344. return;
  3345. }
  3346. // 如果备选方法也失败,回退到文本显示
  3347. this.handleAudioPlaybackFailure();
  3348. },
  3349. // 添加新方法:尝试备选音频播放方法
  3350. tryFallbackAudioPlay() {
  3351. console.log('使用备选方法播放音频:', this.aiVoiceUrl);
  3352. // 如果当前播放器存在,先销毁
  3353. if (this.aiAudioPlayer) {
  3354. try {
  3355. this.aiAudioPlayer.destroy();
  3356. } catch (e) {
  3357. console.error('销毁音频播放器失败:', e);
  3358. }
  3359. this.aiAudioPlayer = null;
  3360. }
  3361. // 使用uni.downloadFile先下载音频文件
  3362. uni.downloadFile({
  3363. url: this.aiVoiceUrl,
  3364. success: (res) => {
  3365. if (res.statusCode === 200) {
  3366. console.log('音频文件下载成功:', res.tempFilePath);
  3367. // 使用新的音频上下文播放本地文件
  3368. const newAudioPlayer = uni.createInnerAudioContext();
  3369. this.aiAudioPlayer = newAudioPlayer;
  3370. newAudioPlayer.autoplay = true;
  3371. newAudioPlayer.src = res.tempFilePath;
  3372. // 设置事件监听
  3373. newAudioPlayer.onPlay(() => {
  3374. console.log('备选方法:音频开始播放');
  3375. });
  3376. newAudioPlayer.onEnded(() => {
  3377. console.log('备选方法:音频播放结束');
  3378. this.isPlayingAiVoice = false;
  3379. this.currentSubtitle = '';
  3380. newAudioPlayer.destroy();
  3381. this.aiAudioPlayer = null;
  3382. this.showContinueQuestionOptions();
  3383. this.checkPendingNavigation();
  3384. });
  3385. newAudioPlayer.onError((err) => {
  3386. console.error('备选方法:音频播放错误:', err);
  3387. this.isPlayingAiVoice = false;
  3388. this.currentSubtitle = '';
  3389. newAudioPlayer.destroy();
  3390. this.aiAudioPlayer = null;
  3391. // 显示错误提示
  3392. /* uni.showToast({
  3393. title: '无法播放音频,请查看文字回复',
  3394. icon: 'none',
  3395. duration: 2000
  3396. }); */
  3397. this.showContinueQuestionOptions();
  3398. this.checkPendingNavigation();
  3399. });
  3400. } else {
  3401. console.error('音频文件下载失败:', res);
  3402. this.handleAudioPlaybackFailure();
  3403. }
  3404. },
  3405. fail: (err) => {
  3406. console.error('音频文件下载请求失败:', err);
  3407. this.handleAudioPlaybackFailure();
  3408. }
  3409. });
  3410. },
  3411. // 添加新方法:处理音频播放失败的情况
  3412. handleAudioPlaybackFailure() {
  3413. // 标记播放结束
  3414. this.isPlayingAiVoice = false;
  3415. // 显示错误提示
  3416. /* uni.showToast({
  3417. title: '无法播放音频,将直接显示文字回复',
  3418. icon: 'none',
  3419. duration: 2000
  3420. }); */
  3421. // 确保字幕显示足够长的时间(10秒)让用户阅读
  3422. this.currentSubtitle = this.aiText;
  3423. // 设置定时器,10秒后清除字幕并显示继续提问选项
  3424. setTimeout(() => {
  3425. this.currentSubtitle = '';
  3426. this.showContinueQuestionOptions();
  3427. this.checkPendingNavigation();
  3428. }, 10000);
  3429. },
  3430. // 添加新方法:从视频中提取音频
  3431. async extractAudioFromVideo(videoBlob) {
  3432. console.log('开始从视频中提取音频');
  3433. return new Promise((resolve, reject) => {
  3434. try {
  3435. // 创建一个视频元素来加载视频
  3436. const videoElement = document.createElement('video');
  3437. videoElement.muted = false;
  3438. videoElement.autoplay = false;
  3439. // 创建音频上下文
  3440. const audioContext = new (window.AudioContext || window.webkitAudioContext)();
  3441. let audioDestination = null;
  3442. let mediaRecorder = null;
  3443. const audioChunks = [];
  3444. // 设置视频源
  3445. videoElement.src = URL.createObjectURL(videoBlob);
  3446. videoElement.onloadedmetadata = () => {
  3447. console.log('视频元数据已加载,视频时长:', videoElement.duration);
  3448. // 创建媒体源和目标节点
  3449. const source = audioContext.createMediaElementSource(videoElement);
  3450. audioDestination = audioContext.createMediaStreamDestination();
  3451. source.connect(audioDestination);
  3452. // 创建MediaRecorder来录制音频
  3453. mediaRecorder = new MediaRecorder(audioDestination.stream);
  3454. mediaRecorder.ondataavailable = (event) => {
  3455. if (event.data.size > 0) {
  3456. audioChunks.push(event.data);
  3457. }
  3458. };
  3459. mediaRecorder.onstop = () => {
  3460. const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
  3461. console.log('音频提取完成,大小:', audioBlob.size);
  3462. resolve(audioBlob);
  3463. };
  3464. // 开始播放视频并录制音频
  3465. videoElement.onplay = () => {
  3466. mediaRecorder.start(100);
  3467. };
  3468. videoElement.onended = () => {
  3469. mediaRecorder.stop();
  3470. audioContext.close();
  3471. };
  3472. // 开始播放
  3473. videoElement.play();
  3474. };
  3475. videoElement.onerror = (err) => {
  3476. console.error('视频加载失败:', err);
  3477. reject(new Error('视频加载失败'));
  3478. };
  3479. } catch (err) {
  3480. console.error('提取音频失败:', err);
  3481. reject(err);
  3482. }
  3483. });
  3484. },
  3485. // 添加新方法:上传音频文件
  3486. async uploadAudioFile(audioBlob, videoUrl) {
  3487. console.log('准备上传音频文件');
  3488. // 创建FormData
  3489. const formData = new FormData();
  3490. // 将Blob转换为File对象
  3491. const fileName = `audio_${Date.now()}.wav`;
  3492. const audioFile = new File([audioBlob], fileName, { type: 'audio/wav' });
  3493. // 添加文件和其他参数
  3494. formData.append('audio_file', audioFile);
  3495. formData.append('video_url', videoUrl);
  3496. formData.append('tenant_id', uni.getStorageSync('tenant_id') || '1');
  3497. formData.append('openid', uni.getStorageSync('userInfo') ? JSON.parse(uni.getStorageSync('userInfo')).openid : '');
  3498. formData.append('application_id', uni.getStorageSync('appId') || '');
  3499. return new Promise((resolve, reject) => {
  3500. // 创建XMLHttpRequest
  3501. const xhr = new XMLHttpRequest();
  3502. xhr.open('POST', `${apiBaseUrl}/api/voice_ai_interaction`, true);
  3503. xhr.timeout = 60000; // 60秒超时
  3504. xhr.onload = () => {
  3505. if (xhr.status === 200) {
  3506. try {
  3507. const response = JSON.parse(xhr.responseText);
  3508. resolve(response);
  3509. } catch (e) {
  3510. reject(new Error('解析响应失败'));
  3511. }
  3512. } else {
  3513. reject(new Error('HTTP状态: ' + xhr.status));
  3514. }
  3515. };
  3516. xhr.onerror = () => {
  3517. reject(new Error('网络错误'));
  3518. };
  3519. xhr.ontimeout = () => {
  3520. reject(new Error('请求超时'));
  3521. };
  3522. xhr.send(formData);
  3523. });
  3524. },
  3525. // 添加一个新方法:使用小程序原生音频API
  3526. /* playMiniProgramAudio() {
  3527. console.log('使用小程序原生音频API播放:', this.aiVoiceUrl);
  3528. // 标记正在播放AI语音
  3529. this.isPlayingAiVoice = true;
  3530. // 确保在播放期间不显示继续提问按钮
  3531. this.showContinueQuestionButton = false;
  3532. this.showEndInterviewButton = false;
  3533. // 检查音频URL是否有效
  3534. if (!this.aiVoiceUrl || this.aiVoiceUrl.trim() === '') {
  3535. console.error('无效的音频URL');
  3536. // 显示错误提示
  3537. // 标记播放结束
  3538. this.isPlayingAiVoice = false;
  3539. // 显示继续提问选项
  3540. this.showContinueQuestionOptions();
  3541. return;
  3542. }
  3543. try {
  3544. // 使用wx.createInnerAudioContext API (微信小程序)
  3545. const audioContext = wx.createInnerAudioContext();
  3546. // 设置音频属性
  3547. audioContext.autoplay = false;
  3548. audioContext.obeyMuteSwitch = false; // 忽略静音开关
  3549. // 监听播放开始事件
  3550. audioContext.onPlay(() => {
  3551. console.log('AI语音开始播放');
  3552. // 显示正在播放提
  3553. });
  3554. // 监听播放结束事件
  3555. audioContext.onEnded(() => {
  3556. console.log('AI语音播放结束');
  3557. // 标记播放结束
  3558. this.isPlayingAiVoice = false;
  3559. // 清空字幕
  3560. this.currentSubtitle = '';
  3561. // 销毁音频播放器
  3562. audioContext.destroy();
  3563. // 播放结束后显示继续提问选项,而不是直接跳转
  3564. this.showContinueQuestionOptions();
  3565. });
  3566. // 监听播放错误事件
  3567. audioContext.onError((err) => {
  3568. console.error('AI语音播放错误:', err);
  3569. // 标记播放结束
  3570. this.isPlayingAiVoice = false;
  3571. // 清空字幕
  3572. this.currentSubtitle = '';
  3573. // 销毁音频播放器
  3574. audioContext.destroy();
  3575. // 播放错误时也显示继续提问选项
  3576. this.showContinueQuestionOptions();
  3577. });
  3578. // 设置音频源
  3579. audioContext.src = this.aiVoiceUrl;
  3580. // 添加超时处理,如果5秒内没有开始播放,则认为出错
  3581. const playTimeout = setTimeout(() => {
  3582. if (this.isPlayingAiVoice) {
  3583. console.warn('小程序音频播放超时,尝试备选方法');
  3584. this.tryMiniProgramFallbackAudioPlay();
  3585. }
  3586. }, 5000);
  3587. // 延迟一小段时间再播放,确保src已经设置完成
  3588. setTimeout(() => {
  3589. audioContext.play();
  3590. // 播放开始后清除超时
  3591. clearTimeout(playTimeout);
  3592. }, 300);
  3593. } catch (e) {
  3594. console.error('小程序播放AI语音时发生错误:', e);
  3595. // 标记播放结束
  3596. this.isPlayingAiVoice = false;
  3597. // 显示错误提示
  3598. // 使用文本显示方式作为备选方案
  3599. this.handleAudioPlaybackFailure();
  3600. }
  3601. }, */
  3602. // 添加新方法:小程序环境的备选音频播放方法
  3603. tryMiniProgramFallbackAudioPlay() {
  3604. console.log('使用小程序备选方法播放音频:', this.aiVoiceUrl);
  3605. // 先下载音频文件到本地
  3606. uni.downloadFile({
  3607. url: this.aiVoiceUrl,
  3608. success: (res) => {
  3609. if (res.statusCode === 200) {
  3610. console.log('小程序音频文件下载成功:', res.tempFilePath);
  3611. // 使用新的音频上下文播放本地文件
  3612. const newAudioContext = wx.createInnerAudioContext();
  3613. newAudioContext.autoplay = true;
  3614. newAudioContext.src = res.tempFilePath;
  3615. // 设置事件监听
  3616. newAudioContext.onPlay(() => {
  3617. console.log('小程序备选方法:音频开始播放');
  3618. });
  3619. newAudioContext.onEnded(() => {
  3620. console.log('小程序备选方法:音频播放结束');
  3621. this.isPlayingAiVoice = false;
  3622. this.currentSubtitle = '';
  3623. newAudioContext.destroy();
  3624. this.showContinueQuestionOptions();
  3625. this.checkPendingNavigation();
  3626. });
  3627. newAudioContext.onError((err) => {
  3628. console.error('小程序备选方法:音频播放错误:', err);
  3629. this.isPlayingAiVoice = false;
  3630. this.currentSubtitle = '';
  3631. newAudioContext.destroy();
  3632. // 尝试使用系统播放器作为最后的备选方案
  3633. this.trySystemAudioPlayer();
  3634. });
  3635. } else {
  3636. console.error('小程序音频文件下载失败:', res);
  3637. this.handleAudioPlaybackFailure();
  3638. }
  3639. },
  3640. fail: (err) => {
  3641. console.error('小程序音频文件下载请求失败:', err);
  3642. this.handleAudioPlaybackFailure();
  3643. }
  3644. });
  3645. },
  3646. // 添加新方法:尝试使用系统播放器
  3647. trySystemAudioPlayer() {
  3648. console.log('尝试使用系统播放器播放音频');
  3649. // 检查平台
  3650. const systemInfo = uni.getSystemInfoSync();
  3651. if (systemInfo.platform === 'android' || systemInfo.platform === 'ios') {
  3652. // 在移动端尝试使用系统播放器
  3653. /* uni.showToast({
  3654. title: '正在使用系统播放器',
  3655. icon: 'none',
  3656. duration: 2000
  3657. }); */
  3658. // 使用uni.playVoice API (如果可用)
  3659. if (typeof uni.playVoice === 'function') {
  3660. uni.playVoice({
  3661. filePath: this.aiVoiceUrl,
  3662. success: () => {
  3663. console.log('系统播放器播放成功');
  3664. setTimeout(() => {
  3665. this.isPlayingAiVoice = false;
  3666. this.currentSubtitle = '';
  3667. this.showContinueQuestionOptions();
  3668. }, 5000); // 假设音频长度约为5秒
  3669. },
  3670. fail: (err) => {
  3671. console.error('系统播放器播放失败:', err);
  3672. this.handleAudioPlaybackFailure();
  3673. }
  3674. });
  3675. } else {
  3676. // 如果uni.playVoice不可用,尝试使用uni.openDocument
  3677. uni.openDocument({
  3678. filePath: this.aiVoiceUrl,
  3679. fileType: 'audio',
  3680. success: () => {
  3681. console.log('使用系统应用打开音频文件');
  3682. // 由于控制权交给了系统,我们需要手动处理后续流程
  3683. setTimeout(() => {
  3684. this.isPlayingAiVoice = false;
  3685. this.currentSubtitle = '';
  3686. this.showContinueQuestionOptions();
  3687. }, 8000); // 给用户足够的时间听完音频
  3688. },
  3689. fail: (err) => {
  3690. console.error('无法使用系统应用打开音频:', err);
  3691. this.handleAudioPlaybackFailure();
  3692. }
  3693. });
  3694. }
  3695. } else {
  3696. // 在其他平台上直接使用文本显示
  3697. this.handleAudioPlaybackFailure();
  3698. }
  3699. },
  3700. // 修改 showContinueQuestionOptions 方法,确保状态正确设置
  3701. showContinueQuestionOptions() {
  3702. // 如果正在播放AI语音,不执行此方法
  3703. if (this.isPlayingAiVoice) {
  3704. console.log('AI语音正在播放,暂不显示继续提问选项');
  3705. return;
  3706. }
  3707. // 增加提问轮次计数
  3708. this.questionRound++;
  3709. // 清空字幕
  3710. this.currentSubtitle = '';
  3711. // 直接跳转到下一页,不再显示继续提问按钮
  3712. console.log('准备跳转到下一页面');
  3713. // 延迟3秒后跳转,给用户一些时间查看状态
  3714. setTimeout(() => {
  3715. this.navigateToNextPage();
  3716. }, 3000);
  3717. // 确保所有录制状态被重置
  3718. this.isRecording = false;
  3719. if (this.recordingTimer) {
  3720. clearInterval(this.recordingTimer);
  3721. this.recordingTimer = null;
  3722. }
  3723. // 重置录制相关数据
  3724. this.recordedChunks = [];
  3725. this.recordingTimerCount = 0;
  3726. this.remainingTime = this.maxRecordingTime;
  3727. },
  3728. // 修复 handleContinueQuestionClick 方法,确保状态正确重置
  3729. handleContinueQuestionClick() {
  3730. // 如果AI语音仍在播放,不允许继续提问
  3731. if (this.isPlayingAiVoice) {
  3732. /* uni.showToast({
  3733. title: '请等待面试官回复完成',
  3734. icon: 'none',
  3735. duration: 2000
  3736. }); */
  3737. return;
  3738. }
  3739. // 隐藏继续提问和结束面试按钮
  3740. this.showContinueQuestionButton = false;
  3741. this.showEndInterviewButton = false;
  3742. // 重置录制相关状态
  3743. this.isRecording = false;
  3744. this.recordingTimerCount = 0;
  3745. this.remainingTime = this.maxRecordingTime;
  3746. this.recordingTimeDisplay = '00:00 / ' + this.formatTime(this.maxRecordingTime);
  3747. // 清空已录制的数据
  3748. this.recordedChunks = [];
  3749. // 如果有正在进行的录制,先停止
  3750. if (this.mediaRecorder && this.mediaRecorder.state === 'recording') {
  3751. this.mediaRecorder.stop();
  3752. }
  3753. if (this.recorder) {
  3754. try {
  3755. this.cameraContext.stopRecord();
  3756. } catch (e) {
  3757. console.error('停止录制失败:', e);
  3758. }
  3759. this.recorder = null;
  3760. }
  3761. // 延迟一小段时间再开始新的录制,确保之前的录制已完全停止
  3762. setTimeout(() => {
  3763. // 开始新一轮录制
  3764. this.startRecordingAnswer();
  3765. }, 500);
  3766. },
  3767. // 添加新方法:处理结束面试按钮点击
  3768. handleEndInterviewClick() {
  3769. // 隐藏继续提问和结束面试按钮
  3770. this.showContinueQuestionButton = false;
  3771. this.showEndInterviewButton = false;
  3772. // 显示结束提示
  3773. /* uni.showToast({
  3774. title: '面试已结束',
  3775. icon: 'success',
  3776. duration: 1500
  3777. }); */
  3778. // 执行现有的跳转逻辑
  3779. this.navigateToNextPage();
  3780. },
  3781. // 添加新方法:处理录制错误
  3782. handleRecordingError(error) {
  3783. console.error('录制错误:', error);
  3784. // 显示错误提示
  3785. /* uni.showToast({
  3786. title: '录制失败,请重试',
  3787. icon: 'none',
  3788. duration: 2000
  3789. }); */
  3790. // 重置录制状态
  3791. this.isRecording = false;
  3792. this.showStopRecordingButton = false;
  3793. // 显示重试按钮
  3794. this.showStartRecordingButton = true;
  3795. },
  3796. // 添加新方法:处理上传错误
  3797. handleUploadError(error) {
  3798. console.error('上传错误:', error);
  3799. // 显示错误提示
  3800. /* uni.showToast({
  3801. title: '上传失败,请重试',
  3802. icon: 'none',
  3803. duration: 2000
  3804. }); */
  3805. // 显示重试按钮
  3806. this.showRetryButton = true;
  3807. // 隐藏上传状态
  3808. this.showUploadStatus = false;
  3809. this.isUploading = false;
  3810. },
  3811. // 添加新方法:检查是否有待处理的自动跳转
  3812. checkPendingNavigation() {
  3813. // 确保所有处理都已完成
  3814. if (this.pendingAutoNavigation &&
  3815. !this.isPlayingAiVoice &&
  3816. !this.isUploading &&
  3817. !this.currentSubtitle) { // 确保字幕也已经清空
  3818. console.log('所有处理已完成,准备跳转');
  3819. // 重置标志
  3820. this.pendingAutoNavigation = false;
  3821. // 延迟跳转,给用户一点时间看到最终状态
  3822. setTimeout(() => {
  3823. this.navigateToNextPage();
  3824. }, 1000);
  3825. }
  3826. },
  3827. // 添加新方法:显示文本回复
  3828. displayTextResponse() {
  3829. // 标记为正在"播放"
  3830. this.isPlayingAiVoice = true;
  3831. // 显示AI回复文本
  3832. this.currentSubtitle = '';
  3833. // 计算每个字的显示时间(假设每个字需要200毫秒)
  3834. const charDisplayTime = 200;
  3835. let currentIndex = 0;
  3836. // 使用定时器逐字显示文本
  3837. const textInterval = setInterval(() => {
  3838. if (currentIndex <= this.aiText.length) {
  3839. this.currentSubtitle = this.aiText.substring(0, currentIndex);
  3840. currentIndex++;
  3841. } else {
  3842. // 文本显示完成
  3843. clearInterval(textInterval);
  3844. // 等待用户阅读完整文本
  3845. setTimeout(() => {
  3846. // 标记播放结束
  3847. this.isPlayingAiVoice = false;
  3848. // 清空字幕
  3849. this.currentSubtitle = '';
  3850. // 显示继续提问选项
  3851. this.showContinueQuestionOptions();
  3852. // 检查是否需要自动跳转
  3853. this.checkPendingNavigation();
  3854. }, 3000); // 给用户3秒时间阅读完整文本
  3855. }
  3856. }, charDisplayTime);
  3857. },
  3858. // 添加新方法:检查不支持的音频格式
  3859. checkUnsupportedAudioFormat(url) {
  3860. if (!url) return false;
  3861. // 获取URL的文件扩展名
  3862. const extension = url.split('.').pop().toLowerCase();
  3863. // 检查平台
  3864. const systemInfo = uni.getSystemInfoSync();
  3865. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
  3866. if (isMiniProgram) {
  3867. // 微信小程序支持的音频格式有限,主要是mp3和wav
  3868. // 检查是否是不支持的格式
  3869. const unsupportedFormats = ['ogg', 'flac', 'aac', 'm4a', 'opus'];
  3870. return unsupportedFormats.includes(extension);
  3871. }
  3872. return false;
  3873. },
  3874. // 修改文本回退方法
  3875. useIOSTextFallback() {
  3876. console.log('切换到文本显示模式');
  3877. this.isPlayingAiVoice = false;
  3878. if (!this.hasShownTextFallbackToast) {
  3879. this.hasShownTextFallbackToast = true;
  3880. }
  3881. // 显示AI回复文本
  3882. this.currentSubtitle = this.aiText || '抱歉,无法获取AI回复内容';
  3883. // 根据文本长度计算阅读时间
  3884. const textLength = this.aiText ? this.aiText.length : 20;
  3885. const readingTime = Math.max(8000, Math.min(textLength * 150, 20000)); // 最少8秒,最多20秒
  3886. console.log(`文本长度: ${textLength}字,预计阅读时间: ${readingTime/1000}秒`);
  3887. // 等待用户阅读完成后再跳转
  3888. setTimeout(() => {
  3889. this.navigateToNextPage();
  3890. }, readingTime);
  3891. },
  3892. // 添加音频预加载方法
  3893. preloadAudio(audioUrl) {
  3894. return new Promise((resolve, reject) => {
  3895. console.log('开始预加载音频:', audioUrl);
  3896. // 使用wx.downloadFile下载音频文件
  3897. const downloadTask = wx.downloadFile({
  3898. url: audioUrl,
  3899. success: (res) => {
  3900. if (res.statusCode === 200) {
  3901. console.log('音频文件下载成功,临时路径:', res.tempFilePath);
  3902. resolve(res.tempFilePath);
  3903. } else {
  3904. console.error('音频文件下载失败,状态码:', res.statusCode);
  3905. reject(new Error(`下载失败,状态码: ${res.statusCode}`));
  3906. }
  3907. },
  3908. fail: (error) => {
  3909. console.error('音频文件下载失败:', error);
  3910. reject(error);
  3911. }
  3912. });
  3913. // 监听下载进度
  3914. downloadTask.onProgressUpdate((res) => {
  3915. console.log('音频下载进度:', res.progress);
  3916. });
  3917. });
  3918. },
  3919. // 修改音频播放方法
  3920. playMiniProgramAudio() {
  3921. return new Promise(async (resolve, reject) => {
  3922. try {
  3923. // 显示加载提示
  3924. uni.showLoading({
  3925. title: '音频加载中...',
  3926. mask: true
  3927. });
  3928. // 先下载音频文件
  3929. const localAudioPath = await this.preloadAudio(this.aiVoiceUrl);
  3930. // 隐藏加载提示
  3931. uni.hideLoading();
  3932. const audioContext = wx.createInnerAudioContext();
  3933. audioContext.src = localAudioPath; // 使用本地文件路径
  3934. audioContext.autoplay = true;
  3935. // 设置音频缓冲大小
  3936. audioContext.bufferSize = 4096;
  3937. let hasStarted = false;
  3938. let hasError = false;
  3939. audioContext.onPlay(() => {
  3940. console.log('AI语音开始播放');
  3941. hasStarted = true;
  3942. this.currentSubtitle = this.aiText;
  3943. });
  3944. audioContext.onEnded(() => {
  3945. console.log('AI语音播放结束');
  3946. this.isPlayingAiVoice = false;
  3947. this.currentSubtitle = '';
  3948. audioContext.destroy();
  3949. // 确保在播放完成后立即解析Promise并跳转
  3950. if (!hasError) {
  3951. console.log('准备跳转到下一页');
  3952. this.navigateToNextPage(); // 添加这行
  3953. resolve();
  3954. }
  3955. });
  3956. audioContext.onStop(() => {
  3957. console.log('AI语音播放停止');
  3958. this.isPlayingAiVoice = false;
  3959. this.currentSubtitle = '';
  3960. audioContext.destroy();
  3961. // 如果是正常停止(非错误导致),也要触发跳转
  3962. if (!hasError) {
  3963. console.log('播放停止,准备跳转到下一页');
  3964. this.navigateToNextPage(); // 添加这行
  3965. resolve();
  3966. }
  3967. });
  3968. audioContext.onError((err) => {
  3969. hasError = true;
  3970. console.error('AI语音播放错误:', err);
  3971. audioContext.destroy();
  3972. // 显示错误提示
  3973. uni.showToast({
  3974. title: '音频播放异常,将显示文字',
  3975. icon: 'none',
  3976. duration: 2000
  3977. });
  3978. // 尝试使用备选音频格式
  3979. if (this.aiVoiceUrl.endsWith('.mp3')) {
  3980. const wavUrl = this.aiVoiceUrl.replace('.mp3', '.wav');
  3981. console.log('尝试使用WAV格式:', wavUrl);
  3982. this.aiVoiceUrl = wavUrl;
  3983. this.playMiniProgramAudio()
  3984. .then(resolve)
  3985. .catch(reject);
  3986. } else {
  3987. reject(err);
  3988. }
  3989. });
  3990. // 设置超时检测
  3991. setTimeout(() => {
  3992. if (!hasStarted && !hasError) {
  3993. console.error('音频播放启动超时');
  3994. audioContext.destroy();
  3995. reject(new Error('音频播放启动超时'));
  3996. }
  3997. }, 5000);
  3998. } catch (error) {
  3999. uni.hideLoading();
  4000. console.error('音频播放初始化失败:', error);
  4001. reject(error);
  4002. }
  4003. });
  4004. },
  4005. // 添加备选的音频播放方法
  4006. async playFallbackAudio() {
  4007. return new Promise((resolve, reject) => {
  4008. try {
  4009. const audio = wx.createInnerAudioContext();
  4010. // 尝试使用较低质量的音频设置
  4011. audio.volume = 1.0;
  4012. audio.playbackRate = 1.0;
  4013. audio.src = this.aiVoiceUrl;
  4014. audio.autoplay = true;
  4015. audio.onPlay(() => {
  4016. console.log('备选音频开始播放');
  4017. });
  4018. audio.onEnded(() => {
  4019. console.log('备选音频播放完成');
  4020. audio.destroy();
  4021. resolve();
  4022. });
  4023. audio.onError((err) => {
  4024. console.error('备选音频播放失败:', err);
  4025. audio.destroy();
  4026. reject(err);
  4027. });
  4028. } catch (error) {
  4029. reject(error);
  4030. }
  4031. });
  4032. },
  4033. // 修改主音频播放方法
  4034. async playAiVoice() {
  4035. console.log('开始播放AI语音:', this.aiVoiceUrl);
  4036. this.isPlayingAiVoice = true;
  4037. this.currentSubtitle = this.aiText;
  4038. try {
  4039. // 首先尝试主要播放方法
  4040. await this.playMiniProgramAudio();
  4041. console.log('音频播放完成,准备跳转');
  4042. // 确保在音频播放完成后立即跳转
  4043. this.navigateToNextPage();
  4044. } catch (error) {
  4045. console.error('主要播放方法失败,尝试备选方法:', error);
  4046. try {
  4047. // 尝试备选播放方法
  4048. await this.playFallbackAudio();
  4049. console.log('备选音频播放完成,准备跳转');
  4050. this.navigateToNextPage();
  4051. } catch (fallbackError) {
  4052. console.error('备选播放方法也失败:', fallbackError);
  4053. // 如果所有播放方法都失败,回退到文本显示
  4054. this.useTextFallbackAndNavigate();
  4055. }
  4056. }
  4057. },
  4058. // 监听字幕内容变化
  4059. handleSubtitleChange() {
  4060. this.$nextTick(() => {
  4061. const subtitleEl = document.querySelector('.subtitle-overlay');
  4062. if (subtitleEl) {
  4063. const contentHeight = subtitleEl.scrollHeight;
  4064. this.subtitleHeight = contentHeight;
  4065. // 如果内容高度超过视口高度的30%,则展开字幕
  4066. this.isSubtitleExpanded = contentHeight > window.innerHeight * 0.3;
  4067. }
  4068. });
  4069. },
  4070. },
  4071. // 添加watch来监听字幕内容变化
  4072. watch: {
  4073. currentSubtitle: {
  4074. handler(newVal) {
  4075. if (newVal) {
  4076. this.handleSubtitleChange();
  4077. } else {
  4078. this.isSubtitleExpanded = false;
  4079. }
  4080. },
  4081. immediate: true
  4082. }
  4083. }
  4084. }
  4085. </script>
  4086. <style scoped>
  4087. .identity-verify-container {
  4088. padding: 0;
  4089. max-width: 100%;
  4090. margin: 0 auto;
  4091. height: 100vh;
  4092. display: flex;
  4093. flex-direction: column;
  4094. background-color: #f5f5f5;
  4095. }
  4096. .digital-human-container {
  4097. position: relative;
  4098. width: 100%;
  4099. height: 100vh;
  4100. overflow: hidden;
  4101. background-color: #f0f0f0;
  4102. }
  4103. .digital-human-video {
  4104. width: 100%;
  4105. height: 100%;
  4106. display: flex;
  4107. justify-content: center;
  4108. align-items: center;
  4109. }
  4110. /* 添加视频蒙层样式 */
  4111. .video-overlay {
  4112. position: absolute;
  4113. top: 0;
  4114. left: 0;
  4115. width: 100%;
  4116. height: 100%;
  4117. background-color: transparent; /* 完全透明 */
  4118. z-index: 6; /* 确保在视频之上,但在按钮和字幕之下 */
  4119. pointer-events: auto; /* 允许捕获点击事件 */
  4120. }
  4121. /* 用户摄像头容器样式 */
  4122. .user-camera-container {
  4123. position: absolute;
  4124. top: 50px;
  4125. right: 5px;
  4126. width: 110px; /* 稍微增加宽度 */
  4127. height: 160px; /* 稍微增加高度 */
  4128. border-radius: 4px; /* 减小圆角 */
  4129. overflow: hidden;
  4130. box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
  4131. z-index: 20;
  4132. }
  4133. /* 用户摄像头视频样式 */
  4134. .user-camera-video {
  4135. width: 100%;
  4136. height: 100%;
  4137. object-fit: cover;
  4138. background-color: #333;
  4139. }
  4140. .video-player {
  4141. width: 100%;
  4142. height: 100%;
  4143. object-fit: cover;
  4144. outline: none; /* 移除视频获得焦点时的轮廓 */
  4145. -webkit-tap-highlight-color: transparent; /* 移除移动设备上的点击高亮 */
  4146. }
  4147. /* 隐藏视频控制条 */
  4148. video::-webkit-media-controls {
  4149. display: none !important;
  4150. }
  4151. video::-webkit-media-controls-enclosure {
  4152. display: none !important;
  4153. }
  4154. video::-webkit-media-controls-panel {
  4155. display: none !important;
  4156. }
  4157. video::-webkit-media-controls-play-button {
  4158. display: none !important;
  4159. }
  4160. video::-webkit-media-controls-timeline {
  4161. display: none !important;
  4162. }
  4163. video::-webkit-media-controls-current-time-display {
  4164. display: none !important;
  4165. }
  4166. video::-webkit-media-controls-time-remaining-display {
  4167. display: none !important;
  4168. }
  4169. video::-webkit-media-controls-mute-button {
  4170. display: none !important;
  4171. }
  4172. video::-webkit-media-controls-volume-slider {
  4173. display: none !important;
  4174. }
  4175. video::-webkit-media-controls-fullscreen-button {
  4176. display: none !important;
  4177. }
  4178. /* 修改字幕覆盖层样式,使其与图片中的样式一致 */
  4179. .subtitle-overlay {
  4180. position: absolute;
  4181. bottom: 100px; /* 初始底部距离 */
  4182. left: 5%; /* 从左侧留出5%的空间 */
  4183. width: 80%; /* 宽度设为90%,两侧各留5%实现居中 */
  4184. max-height: calc(70vh - 100px); /* 最大高度为视口高度的70%减去底部距离 */
  4185. padding: 15px 20px; /* 增加左右内边距 */
  4186. border-radius: 15px;
  4187. background-color: rgba(255, 255, 255, 0.9); /* 白色半透明背景 */
  4188. color: #333; /* 文字颜色为深色 */
  4189. text-align: left; /* 文字左对齐 */
  4190. font-size: 16px;
  4191. line-height: 1.5;
  4192. z-index: 10;
  4193. margin: 0 auto; /* 添加自动边距实现居中 */
  4194. box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 添加轻微阴影 */
  4195. display: flex;
  4196. flex-direction: column;
  4197. align-items: center;
  4198. gap: 10px;
  4199. overflow-y: auto; /* 添加垂直滚动 */
  4200. transform: translateY(0); /* 用于动画 */
  4201. transition: transform 0.3s ease, bottom 0.3s ease; /* 添加平滑过渡效果 */
  4202. }
  4203. /* 当内容高度超过一定值时,自动调整底部距离 */
  4204. .subtitle-overlay.expanded {
  4205. bottom: 50px; /* 减小底部距离 */
  4206. max-height: calc(80vh - 50px); /* 增加最大高度 */
  4207. }
  4208. /* 自定义滚动条样式 */
  4209. .subtitle-overlay::-webkit-scrollbar {
  4210. width: 4px;
  4211. }
  4212. .subtitle-overlay::-webkit-scrollbar-track {
  4213. background: rgba(0, 0, 0, 0.1);
  4214. border-radius: 2px;
  4215. }
  4216. .subtitle-overlay::-webkit-scrollbar-thumb {
  4217. background: rgba(0, 0, 0, 0.2);
  4218. border-radius: 2px;
  4219. }
  4220. .subtitle-overlay::-webkit-scrollbar-thumb:hover {
  4221. background: rgba(0, 0, 0, 0.3);
  4222. }
  4223. /* 继续按钮样式 */
  4224. .next-button {
  4225. background-color: #0039b3;
  4226. color: white;
  4227. border: none;
  4228. padding: 8px 20px;
  4229. border-radius: 20px;
  4230. cursor: pointer;
  4231. font-size: 14px;
  4232. margin-top: 10px;
  4233. transition: all 0.3s;
  4234. width: 140px;
  4235. height: 36px;
  4236. display: flex;
  4237. justify-content: center;
  4238. align-items: center;
  4239. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  4240. }
  4241. .next-button:hover {
  4242. background-color: #002b8f;
  4243. transform: translateY(-1px);
  4244. box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  4245. }
  4246. .next-button:active {
  4247. background-color: #001d66;
  4248. transform: translateY(1px);
  4249. box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  4250. }
  4251. /* 添加计时器样式,右侧显示橙色圆点和时间 */
  4252. .subtitle-overlay::after {
  4253. content: attr(data-time);
  4254. position: absolute;
  4255. right: 20px;
  4256. bottom: 15px;
  4257. color: #333;
  4258. font-size: 14px;
  4259. }
  4260. .control-panel {
  4261. padding: 15px;
  4262. display: flex;
  4263. justify-content: center;
  4264. }
  4265. .control-button {
  4266. padding: 10px 20px;
  4267. background-color: #4CAF50;
  4268. color: white;
  4269. border: none;
  4270. border-radius: 4px;
  4271. cursor: pointer;
  4272. }
  4273. .loading {
  4274. text-align: center;
  4275. margin: 20px 0;
  4276. font-size: 16px;
  4277. }
  4278. .response-container {
  4279. margin-top: 20px;
  4280. padding: 0 20px;
  4281. display: none; /* 默认隐藏调试信息 */
  4282. }
  4283. /* 当showDebugInfo为true时显示 */
  4284. .showDebugInfo .response-container {
  4285. display: block;
  4286. }
  4287. .response-item {
  4288. padding: 10px;
  4289. border: 1px solid #eee;
  4290. border-radius: 4px;
  4291. margin-bottom: 10px;
  4292. background-color: #f9f9f9;
  4293. }
  4294. .response-content {
  4295. display: flex;
  4296. flex-direction: column;
  4297. }
  4298. .answer-button-container {
  4299. position: absolute;
  4300. bottom: 50px; /* 将按钮放在底部而不是75%的位置 */
  4301. left: 50%;
  4302. transform: translateX(-50%); /* 只在X轴上平移,保持水平居中 */
  4303. z-index: 20;
  4304. }
  4305. /* 修改回答按钮样式 */
  4306. .answer-button {
  4307. width: 120px;
  4308. height: 40px; /* 改为矩形按钮 */
  4309. border-radius: 20px; /* 圆角矩形 */
  4310. background-color: #ffffff; /* 白色背景 */
  4311. color: #333; /* 深色文字 */
  4312. font-size: 16px;
  4313. border: none;
  4314. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  4315. display: flex;
  4316. justify-content: center;
  4317. align-items: center;
  4318. cursor: pointer;
  4319. animation: none; /* 移除脉动动画 */
  4320. }
  4321. .stop-recording-button-container {
  4322. position: absolute;
  4323. bottom: 50px; /* 统一与其他按钮的位置 */
  4324. left: 50%;
  4325. transform: translateX(-50%);
  4326. z-index: 20;
  4327. }
  4328. .stop-recording-button {
  4329. width: 120px;
  4330. height: 40px; /* 改为矩形按钮 */
  4331. border-radius: 20px; /* 圆角矩形 */
  4332. background-color: #0039b3; /* 白色背景 */
  4333. color: #fff; /* 深色文字 */
  4334. font-size: 16px;
  4335. border: none;
  4336. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  4337. display: flex;
  4338. justify-content: center;
  4339. align-items: center;
  4340. cursor: pointer;
  4341. animation: none; /* 移除脉动动画 */
  4342. }
  4343. .recording-indicator {
  4344. position: absolute;
  4345. top: 20px;
  4346. left: 20px;
  4347. display: flex;
  4348. align-items: center;
  4349. background-color: rgba(255, 255, 255, 0.9); /* 改为白色半透明背景 */
  4350. padding: 5px 10px;
  4351. border-radius: 15px;
  4352. z-index: 20;
  4353. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  4354. }
  4355. .recording-dot {
  4356. width: 12px;
  4357. height: 12px;
  4358. background-color: #ff6b00; /* 改为橙色,与图片中的颜色一致 */
  4359. border-radius: 50%;
  4360. margin-right: 8px;
  4361. animation: blink 1s infinite;
  4362. }
  4363. .recording-text {
  4364. color: #333; /* 改为深色文字 */
  4365. font-size: 14px;
  4366. }
  4367. .timer-text {
  4368. color: #333; /* 改为深色文字 */
  4369. font-size: 14px;
  4370. margin-left: 8px;
  4371. }
  4372. .start-recording-button-container {
  4373. position: absolute;
  4374. bottom: 50px; /* 统一与其他按钮的位置 */
  4375. left: 50%;
  4376. transform: translateX(-50%);
  4377. z-index: 101;
  4378. }
  4379. .start-recording-button {
  4380. width: 120px;
  4381. height: 40px; /* 改为矩形按钮 */
  4382. border-radius: 20px; /* 圆角矩形 */
  4383. background-color: #ffffff; /* 白色背景 */
  4384. color: #333; /* 深色文字 */
  4385. font-size: 16px;
  4386. border: none;
  4387. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  4388. display: flex;
  4389. justify-content: center;
  4390. align-items: center;
  4391. cursor: pointer;
  4392. animation: none; /* 移除脉动动画 */
  4393. }
  4394. .retry-button-container {
  4395. position: absolute;
  4396. bottom: 30px; /* 统一与其他按钮的位置 */
  4397. left: 50%;
  4398. transform: translateX(-50%);
  4399. z-index: 20;
  4400. }
  4401. .retry-button {
  4402. padding: 10px 20px;
  4403. background-color: #ffffff; /* 白色背景 */
  4404. color: #333; /* 深色文字 */
  4405. font-size: 16px;
  4406. border: none;
  4407. border-radius: 20px; /* 圆角矩形 */
  4408. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  4409. cursor: pointer;
  4410. }
  4411. .retry-button:hover {
  4412. background-color: #2980b9;
  4413. }
  4414. /* 录制时长显示 */
  4415. .recording-timer {
  4416. position: absolute;
  4417. top: 20px;
  4418. left: 130px; /* 放在录制指示器旁边 */
  4419. background-color: rgba(0, 0, 0, 0.6);
  4420. padding: 5px 10px;
  4421. border-radius: 15px;
  4422. z-index: 20;
  4423. display: flex;
  4424. flex-direction: column;
  4425. }
  4426. .timer-text {
  4427. color: #000;
  4428. font-size: 14px;
  4429. font-family: monospace; /* 使用等宽字体,使时间显示更稳定 */
  4430. }
  4431. .remaining-time {
  4432. color: white;
  4433. font-size: 12px;
  4434. margin-top: 2px;
  4435. }
  4436. .remaining-time.warning {
  4437. color: #ff6b6b; /* 剩余时间少时显示红色 */
  4438. animation: blink 1s infinite; /* 使用闪烁动画提醒用户 */
  4439. }
  4440. /* 添加上传状态指示器 */
  4441. .upload-status-indicator {
  4442. position: absolute;
  4443. top: 20px;
  4444. left: 130px; /* 放在录制指示器旁边 */
  4445. background-color: rgba(0, 0, 0, 0.6);
  4446. padding: 5px 10px;
  4447. border-radius: 15px;
  4448. z-index: 20;
  4449. }
  4450. .upload-status-content {
  4451. display: flex;
  4452. align-items: center;
  4453. }
  4454. .upload-status-icon {
  4455. width: 12px;
  4456. height: 12px;
  4457. border-radius: 50%;
  4458. margin-right: 8px;
  4459. }
  4460. .upload-status-text {
  4461. color: white;
  4462. font-size: 14px;
  4463. }
  4464. .uploading {
  4465. background-color: #e74c3c;
  4466. }
  4467. /* 添加倒计时蒙层样式 */
  4468. .countdown-overlay {
  4469. position: fixed;
  4470. top: 0;
  4471. left: 0;
  4472. width: 100%;
  4473. height: 100%;
  4474. background-color: rgba(0, 0, 0, 0.7);
  4475. z-index: 100;
  4476. display: flex;
  4477. justify-content: center;
  4478. align-items: center;
  4479. }
  4480. .countdown-content {
  4481. display: flex;
  4482. flex-direction: column;
  4483. align-items: center;
  4484. }
  4485. .countdown-number {
  4486. font-size: 80px;
  4487. color: #ffffff;
  4488. font-weight: bold;
  4489. margin-bottom: 20px;
  4490. }
  4491. .countdown-text {
  4492. font-size: 24px;
  4493. color: #ffffff;
  4494. }
  4495. /* 添加GIF播放器样式 */
  4496. .gif-player {
  4497. width: 100%;
  4498. height: 100%;
  4499. object-fit: cover;
  4500. position: absolute;
  4501. top: 0;
  4502. left: 0;
  4503. z-index: 5; /* 确保GIF在视频上方但在字幕和按钮下方 */
  4504. }
  4505. /* AI语音播放蒙层样式 */
  4506. .ai-voice-overlay {
  4507. position: fixed;
  4508. top: 0;
  4509. left: 0;
  4510. width: 100%;
  4511. height: 100%;
  4512. background-color: rgba(0, 0, 0, 0.8); /* 0.8的透明度 */
  4513. z-index: 99; /* 确保在其他元素之上,但在倒计时蒙层之下 */
  4514. display: flex;
  4515. justify-content: center;
  4516. align-items: center;
  4517. }
  4518. .ai-voice-content {
  4519. display: flex;
  4520. flex-direction: column;
  4521. align-items: center;
  4522. color: #ffffff;
  4523. }
  4524. .ai-voice-icon {
  4525. width: 40px;
  4526. height: 40px;
  4527. border-radius: 50%;
  4528. background-color: #ffffff;
  4529. margin-bottom: 15px;
  4530. position: relative;
  4531. animation: pulse 1.5s infinite;
  4532. }
  4533. .ai-voice-icon::before {
  4534. content: '';
  4535. position: absolute;
  4536. top: 50%;
  4537. left: 50%;
  4538. transform: translate(-50%, -50%);
  4539. width: 20px;
  4540. height: 20px;
  4541. background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23333"><path d="M12 15c1.66 0 3-1.34 3-3V6c0-1.66-1.34-3-3-3S9 4.34 9 6v6c0 1.66 1.34 3 3 3zm-1-9c0-.55.45-1 1-1s1 .45 1 1v6c0 .55-.45 1-1 1s-1-.45-1-1V6z"/><path d="M17 11c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z"/></svg>');
  4542. background-repeat: no-repeat;
  4543. background-position: center;
  4544. }
  4545. .ai-voice-text {
  4546. font-size: 18px;
  4547. color: #ffffff;
  4548. }
  4549. @keyframes pulse {
  4550. 0% {
  4551. transform: scale(1);
  4552. opacity: 1;
  4553. }
  4554. 50% {
  4555. transform: scale(1.1);
  4556. opacity: 0.8;
  4557. }
  4558. 100% {
  4559. transform: scale(1);
  4560. opacity: 1;
  4561. }
  4562. }
  4563. /* 继续提问按钮样式 */
  4564. .continue-question-container {
  4565. position: absolute;
  4566. bottom: 100px; /* 位置高于结束面试按钮 */
  4567. left: 50%;
  4568. transform: translateX(-50%);
  4569. z-index: 20;
  4570. }
  4571. .continue-question-button {
  4572. width: 120px;
  4573. height: 40px;
  4574. border-radius: 20px;
  4575. background-color: #ffffff;
  4576. color: #333;
  4577. font-size: 16px;
  4578. border: none;
  4579. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  4580. display: flex;
  4581. justify-content: center;
  4582. align-items: center;
  4583. cursor: pointer;
  4584. }
  4585. /* 结束面试按钮样式 */
  4586. .end-interview-container {
  4587. position: absolute;
  4588. bottom: 50px;
  4589. left: 50%;
  4590. transform: translateX(-50%);
  4591. z-index: 20;
  4592. }
  4593. .end-interview-button {
  4594. width: 120px;
  4595. height: 40px;
  4596. border-radius: 20px;
  4597. background-color: #e74c3c; /* 红色背景 */
  4598. color: #ffffff; /* 白色文字 */
  4599. font-size: 16px;
  4600. border: none;
  4601. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  4602. display: flex;
  4603. justify-content: center;
  4604. align-items: center;
  4605. cursor: pointer;
  4606. }
  4607. /* 提问轮次指示器样式 */
  4608. .question-round-indicator {
  4609. position: absolute;
  4610. top: 20px;
  4611. right: 120px; /* 位置在用户摄像头左侧 */
  4612. background-color: rgba(255, 255, 255, 0.9);
  4613. padding: 5px 10px;
  4614. border-radius: 15px;
  4615. z-index: 20;
  4616. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  4617. }
  4618. .round-text {
  4619. color: #333;
  4620. font-size: 14px;
  4621. }
  4622. </style>