interview-question.vue 172 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533
  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.reLaunch({
  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.reLaunch({
  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.resetAudioState();
  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. this.audioPlaybackTimer = setTimeout(() => {
  2651. console.log('音频播放超时,使用备选方案');
  2652. if (this.isPlayingAiVoice) {
  2653. this.handlePlaybackTimeout();
  2654. }
  2655. }, 30000); // 30秒超时
  2656. // 根据平台选择播放方式
  2657. if (isMiniProgram) {
  2658. if (isIOS) {
  2659. await this.playIOSMiniProgramAudio();
  2660. } else {
  2661. await this.playMiniProgramAudio();
  2662. }
  2663. } else if (isIOS) {
  2664. await this.playAiVoiceForIOS();
  2665. } else {
  2666. await this.playAiVoiceForAndroid();
  2667. }
  2668. // 音频播放完成后,标记需要自动跳转
  2669. this.pendingAutoNavigation = true;
  2670. } catch (error) {
  2671. console.error('音频播放失败:', error);
  2672. this.handlePlaybackError(error);
  2673. }
  2674. },
  2675. // 添加新方法:处理播放超时
  2676. handlePlaybackTimeout() {
  2677. console.log('处理音频播放超时');
  2678. // 重置状态
  2679. this.resetAudioState();
  2680. // 显示提示
  2681. uni.showToast({
  2682. title: '音频播放超时,将显示文字回复',
  2683. icon: 'none',
  2684. duration: 2000
  2685. });
  2686. // 使用文本回退
  2687. this.useTextFallbackAndNavigate();
  2688. },
  2689. // 添加新方法:处理播放错误
  2690. handlePlaybackError(error) {
  2691. console.error('处理音频播放错误:', error);
  2692. // 重置状态
  2693. this.resetAudioState();
  2694. // 如果是iOS设备,尝试使用备选播放方法
  2695. const isIOS = uni.getSystemInfoSync().platform === 'ios';
  2696. if (isIOS && !this.hasTriedFallbackMethod) {
  2697. this.hasTriedFallbackMethod = true;
  2698. console.log('iOS设备尝试使用备选播放方法');
  2699. this.fallbackIOSAudioPlay();
  2700. return;
  2701. }
  2702. // 显示错误提示
  2703. uni.showToast({
  2704. title: '音频播放失败,将显示文字回复',
  2705. icon: 'none',
  2706. duration: 2000
  2707. });
  2708. // 使用文本回退
  2709. this.useTextFallbackAndNavigate();
  2710. },
  2711. // 新增方法:文本回退并导航
  2712. useTextFallbackAndNavigate() {
  2713. console.log('使用文本回退并准备导航');
  2714. // 标记播放结束
  2715. this.isPlayingAiVoice = false;
  2716. // 显示友好提示
  2717. if (!this.hasShownTextFallbackToast) {
  2718. this.hasShownTextFallbackToast = true;
  2719. uni.showToast({
  2720. title: '为您显示文字回复',
  2721. icon: 'none',
  2722. duration: 2000
  2723. });
  2724. }
  2725. // 显示完整文本
  2726. this.currentSubtitle = this.aiText || '抱歉,AI回复内容加载失败';
  2727. // 给用户一定时间阅读文本后自动跳转
  2728. setTimeout(() => {
  2729. this.navigateToNextPage();
  2730. }, 5000); // 5秒后跳转
  2731. },
  2732. // 修改 handleIOSAudioPlaybackComplete 方法
  2733. handleIOSAudioPlaybackComplete() {
  2734. // 标记播放结束
  2735. this.isPlayingAiVoice = false;
  2736. // 延迟清空字幕
  2737. setTimeout(() => {
  2738. this.currentSubtitle = '';
  2739. }, 1000);
  2740. // 销毁音频播放器
  2741. if (this.aiAudioPlayer) {
  2742. try {
  2743. this.aiAudioPlayer.destroy();
  2744. } catch (e) {
  2745. console.error('销毁iOS音频播放器失败:', e);
  2746. }
  2747. this.aiAudioPlayer = null;
  2748. }
  2749. // 直接导航到下一页
  2750. this.navigateToNextPage();
  2751. },
  2752. // 修改 playMiniProgramAudio 方法
  2753. playMiniProgramAudio() {
  2754. return new Promise(async (resolve, reject) => {
  2755. try {
  2756. // 显示加载提示
  2757. uni.showLoading({
  2758. title: '音频加载中...',
  2759. mask: true
  2760. });
  2761. // 先下载音频文件
  2762. const localAudioPath = await this.preloadAudio(this.aiVoiceUrl);
  2763. // 隐藏加载提示
  2764. uni.hideLoading();
  2765. const audioContext = wx.createInnerAudioContext();
  2766. audioContext.src = localAudioPath; // 使用本地文件路径
  2767. audioContext.autoplay = true;
  2768. // 设置音频缓冲大小
  2769. audioContext.bufferSize = 4096;
  2770. let hasStarted = false;
  2771. let hasError = false;
  2772. audioContext.onPlay(() => {
  2773. console.log('AI语音开始播放');
  2774. hasStarted = true;
  2775. this.currentSubtitle = this.aiText;
  2776. });
  2777. audioContext.onEnded(() => {
  2778. console.log('AI语音播放结束');
  2779. this.isPlayingAiVoice = false;
  2780. this.currentSubtitle = '';
  2781. audioContext.destroy();
  2782. // 确保在播放完成后立即解析Promise并跳转
  2783. if (!hasError) {
  2784. console.log('准备跳转到下一页');
  2785. this.navigateToNextPage(); // 添加这行
  2786. resolve();
  2787. }
  2788. });
  2789. audioContext.onStop(() => {
  2790. console.log('AI语音播放停止');
  2791. this.isPlayingAiVoice = false;
  2792. this.currentSubtitle = '';
  2793. audioContext.destroy();
  2794. // 如果是正常停止(非错误导致),也要触发跳转
  2795. if (!hasError) {
  2796. console.log('播放停止,准备跳转到下一页');
  2797. this.navigateToNextPage(); // 添加这行
  2798. resolve();
  2799. }
  2800. });
  2801. audioContext.onError((err) => {
  2802. hasError = true;
  2803. console.error('AI语音播放错误:', err);
  2804. audioContext.destroy();
  2805. // 显示错误提示
  2806. uni.showToast({
  2807. title: '音频播放异常,将显示文字',
  2808. icon: 'none',
  2809. duration: 2000
  2810. });
  2811. // 尝试使用备选音频格式
  2812. if (this.aiVoiceUrl.endsWith('.mp3')) {
  2813. const wavUrl = this.aiVoiceUrl.replace('.mp3', '.wav');
  2814. console.log('尝试使用WAV格式:', wavUrl);
  2815. this.aiVoiceUrl = wavUrl;
  2816. this.playMiniProgramAudio()
  2817. .then(resolve)
  2818. .catch(reject);
  2819. } else {
  2820. reject(err);
  2821. }
  2822. });
  2823. // 设置超时检测
  2824. setTimeout(() => {
  2825. if (!hasStarted && !hasError) {
  2826. console.error('音频播放启动超时');
  2827. audioContext.destroy();
  2828. reject(new Error('音频播放启动超时'));
  2829. }
  2830. }, 5000);
  2831. } catch (error) {
  2832. uni.hideLoading();
  2833. console.error('音频播放初始化失败:', error);
  2834. reject(error);
  2835. }
  2836. });
  2837. },
  2838. // 新增方法:导航到下一页
  2839. navigateToNextPage() {
  2840. console.log('执行页面跳转');
  2841. // 确保清理音频相关状态
  2842. this.isPlayingAiVoice = false;
  2843. this.currentSubtitle = '';
  2844. // 添加延迟确保状态已更新
  2845. setTimeout(() => {
  2846. uni.reLaunch({
  2847. url: '/pages/success/success',
  2848. success: () => {
  2849. console.log('页面跳转成功');
  2850. },
  2851. fail: (err) => {
  2852. console.error('页面跳转失败:', err);
  2853. uni.showToast({
  2854. title: '页面跳转失败',
  2855. icon: 'none',
  2856. duration: 2000
  2857. });
  2858. }
  2859. });
  2860. }, 100);
  2861. },
  2862. // 新增方法:专门处理iOS小程序音频播放
  2863. playIOSMiniProgramAudio() {
  2864. return new Promise((resolve, reject) => {
  2865. try {
  2866. const audioContext = wx.createInnerAudioContext();
  2867. audioContext.src = this.aiVoiceUrl;
  2868. audioContext.autoplay = true;
  2869. audioContext.onPlay(() => {
  2870. console.log('iOS小程序音频开始播放');
  2871. });
  2872. audioContext.onEnded(() => {
  2873. console.log('iOS小程序音频播放完成');
  2874. audioContext.destroy();
  2875. resolve();
  2876. });
  2877. audioContext.onError((err) => {
  2878. console.error('iOS小程序音频播放错误:', err);
  2879. audioContext.destroy();
  2880. reject(err);
  2881. });
  2882. } catch (error) {
  2883. reject(error);
  2884. }
  2885. });
  2886. },
  2887. playAiVoiceForIOS() {
  2888. return new Promise((resolve, reject) => {
  2889. try {
  2890. const audioContext = new Audio();
  2891. audioContext.src = this.aiVoiceUrl;
  2892. audioContext.autoplay = true;
  2893. audioContext.addEventListener('play', () => {
  2894. console.log('iOS音频开始播放');
  2895. });
  2896. audioContext.addEventListener('ended', () => {
  2897. console.log('iOS音频播放完成');
  2898. resolve();
  2899. });
  2900. audioContext.addEventListener('error', (err) => {
  2901. console.error('iOS音频播放错误:', err);
  2902. reject(err);
  2903. });
  2904. } catch (error) {
  2905. reject(error);
  2906. }
  2907. });
  2908. },
  2909. playAiVoiceForAndroid() {
  2910. return new Promise((resolve, reject) => {
  2911. try {
  2912. const audioContext = new Audio();
  2913. audioContext.src = this.aiVoiceUrl;
  2914. audioContext.autoplay = true;
  2915. audioContext.addEventListener('play', () => {
  2916. console.log('Android音频开始播放');
  2917. });
  2918. audioContext.addEventListener('ended', () => {
  2919. console.log('Android音频播放完成');
  2920. resolve();
  2921. });
  2922. audioContext.addEventListener('error', (err) => {
  2923. console.error('Android音频播放错误:', err);
  2924. reject(err);
  2925. });
  2926. } catch (error) {
  2927. reject(error);
  2928. }
  2929. });
  2930. },
  2931. // 新增方法:iOS小程序音频预下载
  2932. preloadIOSMiniProgramAudio(audioUrl) {
  2933. return new Promise((resolve, reject) => {
  2934. console.log('开始预下载iOS小程序音频:', audioUrl);
  2935. uni.downloadFile({
  2936. url: audioUrl,
  2937. timeout: 15000, // 15秒超时
  2938. success: (res) => {
  2939. if (res.statusCode === 200) {
  2940. console.log('iOS小程序音频下载成功:', res.tempFilePath);
  2941. resolve(res.tempFilePath);
  2942. } else {
  2943. console.error('iOS小程序音频下载失败,状态码:', res.statusCode);
  2944. reject(new Error(`下载失败,状态码: ${res.statusCode}`));
  2945. }
  2946. },
  2947. fail: (err) => {
  2948. console.error('iOS小程序音频下载请求失败:', err);
  2949. reject(err);
  2950. }
  2951. });
  2952. });
  2953. },
  2954. // 新增方法:iOS小程序错误处理
  2955. handleIOSMiniProgramError(audioContext, error) {
  2956. console.error('处理iOS小程序音频错误:', error);
  2957. // 销毁音频播放器
  2958. if (audioContext) {
  2959. try {
  2960. audioContext.destroy();
  2961. } catch (e) {
  2962. console.error('销毁音频播放器失败:', e);
  2963. }
  2964. }
  2965. // 根据错误类型显示不同的提示信息
  2966. let errorMessage = '音频播放异常,显示文字';
  2967. if (error.errMsg && error.errMsg.includes('-11850')) {
  2968. console.log('iOS小程序检测到系统音频错误(-11850)');
  2969. errorMessage = '系统音频服务暂停,显示文字';
  2970. } else if (error.errCode === 10002) {
  2971. console.log('iOS小程序检测到errCode:10002,网络或资源问题');
  2972. errorMessage = '音频加载中断,显示文字';
  2973. } else if (error.errCode === 10001) {
  2974. console.log('iOS小程序检测到errCode:10001,系统错误');
  2975. errorMessage = '系统音频错误,显示文字';
  2976. } else if (error.errCode === 10003) {
  2977. console.log('iOS小程序检测到errCode:10003,文件错误');
  2978. errorMessage = '音频文件错误,显示文字';
  2979. } else if (error.errCode === 10004) {
  2980. console.log('iOS小程序检测到errCode:10004,格式不支持');
  2981. errorMessage = '音频格式不支持,显示文字';
  2982. }
  2983. // 显示用户友好的错误提示
  2984. uni.showToast({
  2985. title: errorMessage,
  2986. icon: 'none',
  2987. duration: 2000
  2988. });
  2989. // 使用文本回退
  2990. this.useIOSTextFallback();
  2991. },
  2992. // 新增方法:iOS小程序播放超时处理
  2993. handleIOSPlaybackTimeout(audioContext) {
  2994. console.log('iOS小程序音频播放超时处理');
  2995. // 销毁音频播放器
  2996. if (audioContext) {
  2997. try {
  2998. audioContext.destroy();
  2999. } catch (e) {
  3000. console.error('销毁超时音频播放器失败:', e);
  3001. }
  3002. }
  3003. // 显示超时提示
  3004. /* uni.showToast({
  3005. title: '音频加载超时,显示文字',
  3006. icon: 'none',
  3007. duration: 2000
  3008. }); */
  3009. // 使用文本回退
  3010. this.useIOSTextFallback();
  3011. },
  3012. // 新增方法:iOS小程序备选播放方法
  3013. fallbackIOSMiniProgramPlay(audioContext) {
  3014. console.log('iOS小程序使用备选播放方法');
  3015. try {
  3016. // 直接设置原始URL
  3017. audioContext.src = this.aiVoiceUrl;
  3018. // 设置较短的超时时间
  3019. const fallbackTimeout = setTimeout(() => {
  3020. if (this.isPlayingAiVoice) {
  3021. console.log('iOS小程序备选方法也超时');
  3022. clearTimeout(fallbackTimeout);
  3023. this.handleIOSPlaybackTimeout(audioContext);
  3024. }
  3025. }, 3000);
  3026. // 尝试播放
  3027. audioContext.play();
  3028. } catch (e) {
  3029. console.error('iOS小程序备选播放方法失败:', e);
  3030. this.handleIOSPlaybackTimeout(audioContext);
  3031. }
  3032. },
  3033. // 新增方法:统一的iOS音频完成处理
  3034. handleIOSAudioComplete(audioContext) {
  3035. console.log('iOS音频播放完成');
  3036. // 标记播放结束
  3037. this.isPlayingAiVoice = false;
  3038. // 延迟清空字幕,让用户有时间阅读
  3039. setTimeout(() => {
  3040. this.currentSubtitle = '';
  3041. }, 2000);
  3042. // 销毁音频播放器
  3043. if (audioContext) {
  3044. try {
  3045. audioContext.destroy();
  3046. } catch (e) {
  3047. console.error('销毁iOS音频播放器失败:', e);
  3048. }
  3049. }
  3050. // 显示继续提问选项
  3051. this.showContinueQuestionOptions();
  3052. // 检查是否需要自动跳转
  3053. this.checkPendingNavigation();
  3054. },
  3055. // 移除原来的 playMiniProgramAudioForIOS 方法,因为已经被新的 playIOSMiniProgramAudio 替代
  3056. // playMiniProgramAudioForIOS() 方法可以删除或注释掉
  3057. // 保留原有的 useIOSTextFallback 方法,但确保它能正确处理所有iOS场景
  3058. useIOSTextFallback() {
  3059. console.log('iOS使用文本回退方案');
  3060. // 确保播放状态正确
  3061. this.isPlayingAiVoice = false;
  3062. // 显示友好提示(如果还没有显示过)
  3063. if (!this.hasShownTextFallbackToast) {
  3064. this.hasShownTextFallbackToast = true;
  3065. }
  3066. // 显示完整文本和继续按钮
  3067. this.currentSubtitle = this.aiText || '抱歉,AI回复内容加载失败';
  3068. this.showNextButton = true; // 添加一个变量控制按钮显示
  3069. },
  3070. // 添加处理继续按钮点击的方法
  3071. handleNextButtonClick() {
  3072. this.showNextButton = false;
  3073. this.handleIOSAudioComplete(null);
  3074. },
  3075. // 添加新方法:iOS音频播放完成处理
  3076. handleIOSAudioPlaybackComplete() {
  3077. console.log('iOS音频播放完成');
  3078. // 标记播放结束
  3079. this.isPlayingAiVoice = false;
  3080. // 确保在主线程中执行UI更新
  3081. uni.hideLoading();
  3082. // 延迟清空字幕,让用户有时间阅读
  3083. setTimeout(() => {
  3084. this.currentSubtitle = '';
  3085. }, 2000);
  3086. // 销毁音频播放器
  3087. if (this.aiAudioPlayer) {
  3088. try {
  3089. this.aiAudioPlayer.destroy();
  3090. } catch (e) {
  3091. console.error('销毁iOS音频播放器失败:', e);
  3092. }
  3093. this.aiAudioPlayer = null;
  3094. }
  3095. // 确保状态重置
  3096. this.resetAudioState();
  3097. // 检查是否需要自动跳转
  3098. if (this.pendingAutoNavigation) {
  3099. console.log('执行待处理的自动跳转');
  3100. this.navigateToNextPage();
  3101. } else {
  3102. // 如果没有待处理的跳转,显示继续提问选项
  3103. this.showContinueQuestionOptions();
  3104. }
  3105. },
  3106. // 添加新方法:重置音频状态
  3107. resetAudioState() {
  3108. // 重置所有音频相关状态
  3109. this.isPlayingAiVoice = false;
  3110. this.hasTriedFallbackMethod = false;
  3111. this.hasShownTextFallbackToast = false;
  3112. // 确保音频播放器被正确销毁
  3113. if (this.aiAudioPlayer) {
  3114. try {
  3115. this.aiAudioPlayer.destroy();
  3116. } catch (e) {
  3117. console.error('销毁音频播放器失败:', e);
  3118. }
  3119. this.aiAudioPlayer = null;
  3120. }
  3121. // 清除任何可能的计时器
  3122. if (this.audioPlaybackTimer) {
  3123. clearTimeout(this.audioPlaybackTimer);
  3124. this.audioPlaybackTimer = null;
  3125. }
  3126. },
  3127. // 添加新方法:iOS音频错误处理
  3128. handleIOSAudioError(error) {
  3129. console.error('iOS音频播放错误:', error);
  3130. // 根据错误码进行不同处理
  3131. switch (error.errCode) {
  3132. case 10001:
  3133. console.log('iOS音频系统错误,尝试重新播放');
  3134. this.retryIOSAudioPlay();
  3135. break;
  3136. case 10002:
  3137. console.log('iOS音频网络错误,使用备选方案');
  3138. this.handleIOS10002Error();
  3139. break;
  3140. case 10003:
  3141. console.log('iOS音频文件错误,使用文本回退');
  3142. this.useIOSTextFallback();
  3143. break;
  3144. case 10004:
  3145. console.log('iOS音频格式不支持,使用文本回退');
  3146. this.useIOSTextFallback();
  3147. break;
  3148. default:
  3149. console.log('iOS音频未知错误,使用文本回退');
  3150. this.useIOSTextFallback();
  3151. break;
  3152. }
  3153. },
  3154. // 添加新方法:重试iOS音频播放
  3155. retryIOSAudioPlay() {
  3156. console.log('重试iOS音频播放');
  3157. // 销毁当前播放器
  3158. if (this.aiAudioPlayer) {
  3159. try {
  3160. this.aiAudioPlayer.destroy();
  3161. } catch (e) {
  3162. console.error('销毁播放器失败:', e);
  3163. }
  3164. this.aiAudioPlayer = null;
  3165. }
  3166. // 延迟后重试
  3167. setTimeout(() => {
  3168. this.fallbackIOSAudioPlay();
  3169. }, 1000);
  3170. },
  3171. // 添加新方法:iOS专用音频播放
  3172. async playAiVoiceForIOS() {
  3173. console.log('使用iOS专用音频播放方法');
  3174. return new Promise((resolve, reject) => {
  3175. try {
  3176. // 创建新的音频播放器
  3177. this.aiAudioPlayer = uni.createInnerAudioContext();
  3178. // 配置播放器
  3179. this.aiAudioPlayer.autoplay = true;
  3180. this.aiAudioPlayer.obeyMuteSwitch = false; // 不遵循静音开关,确保播放
  3181. this.aiAudioPlayer.volume = 1.0;
  3182. // 设置音频源
  3183. this.aiAudioPlayer.src = this.aiVoiceUrl;
  3184. // 监听事件
  3185. this.aiAudioPlayer.onPlay(() => {
  3186. console.log('iOS音频开始播放');
  3187. this.currentSubtitle = this.aiText;
  3188. });
  3189. this.aiAudioPlayer.onEnded(() => {
  3190. console.log('iOS音频播放完成');
  3191. this.handleIOSAudioPlaybackComplete();
  3192. resolve();
  3193. });
  3194. this.aiAudioPlayer.onError((err) => {
  3195. console.error('iOS音频播放错误:', err);
  3196. reject(err);
  3197. });
  3198. this.aiAudioPlayer.onWaiting(() => {
  3199. console.log('iOS音频加载中...');
  3200. });
  3201. this.aiAudioPlayer.onCanplay(() => {
  3202. console.log('iOS音频准备就绪');
  3203. });
  3204. } catch (error) {
  3205. console.error('创建iOS音频播放器失败:', error);
  3206. reject(error);
  3207. }
  3208. });
  3209. },
  3210. // 添加新方法:iOS备选音频播放
  3211. fallbackIOSAudioPlay() {
  3212. console.log('iOS备选音频播放方案');
  3213. try {
  3214. // 创建新的音频播放器
  3215. this.aiAudioPlayer = uni.createInnerAudioContext();
  3216. // 使用更保守的设置
  3217. this.aiAudioPlayer.autoplay = true;
  3218. this.aiAudioPlayer.obeyMuteSwitch = true; // 遵循静音开关
  3219. this.aiAudioPlayer.volume = 0.8;
  3220. // 直接使用原URL
  3221. this.aiAudioPlayer.src = this.aiVoiceUrl;
  3222. // 设置简化的事件监听
  3223. this.aiAudioPlayer.onPlay(() => {
  3224. console.log('iOS备选方案:音频开始播放');
  3225. this.currentSubtitle = this.aiText;
  3226. });
  3227. this.aiAudioPlayer.onEnded(() => {
  3228. console.log('iOS备选方案:音频播放结束');
  3229. this.handleIOSAudioPlaybackComplete();
  3230. });
  3231. this.aiAudioPlayer.onError((err) => {
  3232. console.error('iOS备选方案:音频播放错误:', err);
  3233. this.useIOSTextFallback();
  3234. });
  3235. // 设置超时,如果5秒内没有开始播放,使用文本回退
  3236. setTimeout(() => {
  3237. if (this.isPlayingAiVoice && this.aiAudioPlayer) {
  3238. console.log('iOS音频播放超时,使用文本回退');
  3239. this.useIOSTextFallback();
  3240. }
  3241. }, 5000);
  3242. } catch (e) {
  3243. console.error('iOS备选音频播放失败:', e);
  3244. this.useIOSTextFallback();
  3245. }
  3246. },
  3247. // 修改 playMiniProgramAudio 方法,添加iOS特殊处理
  3248. /* playMiniProgramAudio() {
  3249. console.log('使用小程序原生音频API播放:', this.aiVoiceUrl);
  3250. // 标记正在播放AI语音
  3251. this.isPlayingAiVoice = true;
  3252. // 确保在播放期间不显示继续提问按钮
  3253. this.showContinueQuestionButton = false;
  3254. this.showEndInterviewButton = false;
  3255. // 检查音频URL是否有效
  3256. if (!this.aiVoiceUrl || this.aiVoiceUrl.trim() === '') {
  3257. console.error('无效的音频URL');
  3258. this.handleAudioPlaybackFailure();
  3259. return;
  3260. }
  3261. // 检查平台
  3262. const systemInfo = uni.getSystemInfoSync();
  3263. const isIOS = systemInfo.platform === 'ios';
  3264. // iOS小程序特殊处理
  3265. if (isIOS) {
  3266. this.playMiniProgramAudioForIOS();
  3267. return;
  3268. }
  3269. // 非iOS平台的原有逻辑
  3270. try {
  3271. // 使用wx.createInnerAudioContext API (微信小程序)
  3272. const audioContext = wx.createInnerAudioContext();
  3273. // 设置音频属性
  3274. audioContext.autoplay = false;
  3275. audioContext.obeyMuteSwitch = false; // 忽略静音开关
  3276. // 监听播放开始事件
  3277. audioContext.onPlay(() => {
  3278. console.log('AI语音开始播放');
  3279. // 显示正在播放提示
  3280. });
  3281. // 监听播放结束事件
  3282. audioContext.onEnded(() => {
  3283. console.log('AI语音播放结束');
  3284. // 标记播放结束
  3285. this.isPlayingAiVoice = false;
  3286. // 清空字幕
  3287. this.currentSubtitle = '';
  3288. // 销毁音频播放器
  3289. audioContext.destroy();
  3290. // 播放结束后显示继续提问选项,而不是直接跳转
  3291. this.showContinueQuestionOptions();
  3292. });
  3293. // 监听播放错误事件
  3294. audioContext.onError((err) => {
  3295. console.error('AI语音播放错误:', err);
  3296. // 标记播放结束
  3297. this.isPlayingAiVoice = false;
  3298. // 清空字幕
  3299. this.currentSubtitle = '';
  3300. // 销毁音频播放器
  3301. audioContext.destroy();
  3302. // 播放错误时也显示继续提问选项
  3303. this.showContinueQuestionOptions();
  3304. });
  3305. // 设置音频源
  3306. audioContext.src = this.aiVoiceUrl;
  3307. // 添加超时处理,如果5秒内没有开始播放,则认为出错
  3308. const playTimeout = setTimeout(() => {
  3309. if (this.isPlayingAiVoice) {
  3310. console.warn('小程序音频播放超时,尝试备选方法');
  3311. this.tryMiniProgramFallbackAudioPlay();
  3312. }
  3313. }, 5000);
  3314. // 延迟一小段时间再播放,确保src已经设置完成
  3315. setTimeout(() => {
  3316. audioContext.play();
  3317. // 播放开始后清除超时
  3318. clearTimeout(playTimeout);
  3319. }, 300);
  3320. } catch (e) {
  3321. console.error('小程序播放AI语音时发生错误:', e);
  3322. // 标记播放结束
  3323. this.isPlayingAiVoice = false;
  3324. // 显示错误提示
  3325. // 使用文本显示方式作为备选方案
  3326. this.handleAudioPlaybackFailure();
  3327. }
  3328. }, */
  3329. // 添加新方法:iOS小程序音频播放
  3330. playMiniProgramAudioForIOS() {
  3331. console.log('iOS小程序环境:开始播放AI语音');
  3332. // 重置错误标记
  3333. this.hasShownTextFallbackToast = false;
  3334. try {
  3335. // 创建音频上下文
  3336. const audioContext = wx.createInnerAudioContext();
  3337. // iOS小程序特殊配置
  3338. audioContext.autoplay = false;
  3339. audioContext.obeyMuteSwitch = true; // iOS上遵循静音开关
  3340. audioContext.volume = 1.0;
  3341. // 设置错误处理
  3342. audioContext.onError((err) => {
  3343. console.error('iOS小程序音频播放错误:', err);
  3344. // 检查具体错误类型
  3345. if (err.errMsg && err.errMsg.includes('-11850')) {
  3346. console.log('iOS小程序检测到系统音频错误(-11850)');
  3347. /* uni.showToast({
  3348. title: '系统音频暂停,显示文字',
  3349. icon: 'none',
  3350. duration: 2000
  3351. }); */
  3352. } else if (err.errCode === 10002) {
  3353. console.log('iOS小程序检测到errCode:10002,网络或资源问题');
  3354. /* uni.showToast({
  3355. title: '音频加载中断,显示文字',
  3356. icon: 'none',
  3357. duration: 2000
  3358. }); */
  3359. } else {
  3360. console.log('iOS小程序其他音频错误:', err.errCode);
  3361. /* uni.showToast({
  3362. title: '音频播放异常,显示文字',
  3363. icon: 'none',
  3364. duration: 2000
  3365. }); */
  3366. }
  3367. this.useIOSMiniProgramTextFallback(audioContext);
  3368. });
  3369. // 先尝试直接播放,如果失败再下载
  3370. audioContext.src = this.aiVoiceUrl;
  3371. // 设置成功事件监听
  3372. audioContext.onPlay(() => {
  3373. console.log('iOS小程序音频开始播放');
  3374. this.currentSubtitle = this.aiText;
  3375. /* uni.showToast({
  3376. title: '正在播放AI回复',
  3377. icon: 'none',
  3378. duration: 1500
  3379. }); */
  3380. });
  3381. audioContext.onEnded(() => {
  3382. console.log('iOS小程序音频播放结束');
  3383. this.handleIOSMiniProgramAudioComplete(audioContext);
  3384. });
  3385. // 设置较短的播放超时时间
  3386. const playTimeout = setTimeout(() => {
  3387. if (this.isPlayingAiVoice) {
  3388. console.log('iOS小程序音频播放超时,切换到文本显示');
  3389. clearTimeout(playTimeout);
  3390. this.useIOSMiniProgramTextFallback(audioContext);
  3391. }
  3392. }, 3000); // 缩短到3秒
  3393. // 尝试播放
  3394. audioContext.play();
  3395. } catch (e) {
  3396. console.error('iOS小程序音频播放初始化失败:', e);
  3397. this.handleAudioPlaybackFailure();
  3398. }
  3399. },
  3400. // 添加新方法:iOS小程序音频播放完成
  3401. handleIOSMiniProgramAudioComplete(audioContext) {
  3402. this.isPlayingAiVoice = false;
  3403. setTimeout(() => {
  3404. this.currentSubtitle = '';
  3405. }, 2000);
  3406. if (audioContext) {
  3407. try {
  3408. audioContext.destroy();
  3409. } catch (e) {
  3410. console.error('销毁iOS小程序音频播放器失败:', e);
  3411. }
  3412. }
  3413. this.showContinueQuestionOptions();
  3414. this.checkPendingNavigation();
  3415. },
  3416. // 添加新方法:iOS小程序音频错误处理
  3417. handleIOSMiniProgramAudioError(audioContext, error) {
  3418. console.error('iOS小程序音频错误:', error);
  3419. // 根据错误码处理
  3420. if (error.errCode === 10002) {
  3421. this.useIOSMiniProgramTextFallback(audioContext);
  3422. } else {
  3423. // 其他错误也使用文本回退
  3424. this.useIOSMiniProgramTextFallback(audioContext);
  3425. }
  3426. },
  3427. // 添加新方法:iOS小程序文本回退
  3428. useIOSMiniProgramTextFallback(audioContext) {
  3429. console.log('iOS小程序使用文本回退方案');
  3430. // 销毁音频播放器
  3431. if (audioContext) {
  3432. try {
  3433. audioContext.destroy();
  3434. } catch (e) {
  3435. console.error('销毁音频播放器失败:', e);
  3436. }
  3437. }
  3438. // 确保播放状态正确
  3439. this.isPlayingAiVoice = false;
  3440. // 显示完整文本
  3441. this.currentSubtitle = this.aiText || '抱歉,AI回复内容加载失败';
  3442. // 根据文本长度计算阅读时间
  3443. const textLength = this.aiText ? this.aiText.length : 20;
  3444. const readingTime = Math.max(6000, Math.min(textLength * 120, 18000)); // 最少6秒,最多18秒
  3445. setTimeout(() => {
  3446. this.handleIOSMiniProgramAudioComplete(null);
  3447. }, readingTime);
  3448. },
  3449. // 添加新方法:处理音频播放错误
  3450. handleAudioPlaybackError(error) {
  3451. console.error('音频播放错误:', error);
  3452. // 尝试使用备选方法
  3453. if (!this.hasTriedFallbackMethod) {
  3454. this.hasTriedFallbackMethod = true;
  3455. this.tryFallbackAudioPlay();
  3456. return;
  3457. }
  3458. // 如果备选方法也失败,回退到文本显示
  3459. this.handleAudioPlaybackFailure();
  3460. },
  3461. // 添加新方法:尝试备选音频播放方法
  3462. tryFallbackAudioPlay() {
  3463. console.log('使用备选方法播放音频:', this.aiVoiceUrl);
  3464. // 如果当前播放器存在,先销毁
  3465. if (this.aiAudioPlayer) {
  3466. try {
  3467. this.aiAudioPlayer.destroy();
  3468. } catch (e) {
  3469. console.error('销毁音频播放器失败:', e);
  3470. }
  3471. this.aiAudioPlayer = null;
  3472. }
  3473. // 使用uni.downloadFile先下载音频文件
  3474. uni.downloadFile({
  3475. url: this.aiVoiceUrl,
  3476. success: (res) => {
  3477. if (res.statusCode === 200) {
  3478. console.log('音频文件下载成功:', res.tempFilePath);
  3479. // 使用新的音频上下文播放本地文件
  3480. const newAudioPlayer = uni.createInnerAudioContext();
  3481. this.aiAudioPlayer = newAudioPlayer;
  3482. newAudioPlayer.autoplay = true;
  3483. newAudioPlayer.src = res.tempFilePath;
  3484. // 设置事件监听
  3485. newAudioPlayer.onPlay(() => {
  3486. console.log('备选方法:音频开始播放');
  3487. });
  3488. newAudioPlayer.onEnded(() => {
  3489. console.log('备选方法:音频播放结束');
  3490. this.isPlayingAiVoice = false;
  3491. this.currentSubtitle = '';
  3492. newAudioPlayer.destroy();
  3493. this.aiAudioPlayer = null;
  3494. this.showContinueQuestionOptions();
  3495. this.checkPendingNavigation();
  3496. });
  3497. newAudioPlayer.onError((err) => {
  3498. console.error('备选方法:音频播放错误:', err);
  3499. this.isPlayingAiVoice = false;
  3500. this.currentSubtitle = '';
  3501. newAudioPlayer.destroy();
  3502. this.aiAudioPlayer = null;
  3503. // 显示错误提示
  3504. /* uni.showToast({
  3505. title: '无法播放音频,请查看文字回复',
  3506. icon: 'none',
  3507. duration: 2000
  3508. }); */
  3509. this.showContinueQuestionOptions();
  3510. this.checkPendingNavigation();
  3511. });
  3512. } else {
  3513. console.error('音频文件下载失败:', res);
  3514. this.handleAudioPlaybackFailure();
  3515. }
  3516. },
  3517. fail: (err) => {
  3518. console.error('音频文件下载请求失败:', err);
  3519. this.handleAudioPlaybackFailure();
  3520. }
  3521. });
  3522. },
  3523. // 添加新方法:处理音频播放失败的情况
  3524. handleAudioPlaybackFailure() {
  3525. // 标记播放结束
  3526. this.isPlayingAiVoice = false;
  3527. // 显示错误提示
  3528. /* uni.showToast({
  3529. title: '无法播放音频,将直接显示文字回复',
  3530. icon: 'none',
  3531. duration: 2000
  3532. }); */
  3533. // 确保字幕显示足够长的时间(10秒)让用户阅读
  3534. this.currentSubtitle = this.aiText;
  3535. // 设置定时器,10秒后清除字幕并显示继续提问选项
  3536. setTimeout(() => {
  3537. this.currentSubtitle = '';
  3538. this.showContinueQuestionOptions();
  3539. this.checkPendingNavigation();
  3540. }, 10000);
  3541. },
  3542. // 添加新方法:从视频中提取音频
  3543. async extractAudioFromVideo(videoBlob) {
  3544. console.log('开始从视频中提取音频');
  3545. return new Promise((resolve, reject) => {
  3546. try {
  3547. // 创建一个视频元素来加载视频
  3548. const videoElement = document.createElement('video');
  3549. videoElement.muted = false;
  3550. videoElement.autoplay = false;
  3551. // 创建音频上下文
  3552. const audioContext = new (window.AudioContext || window.webkitAudioContext)();
  3553. let audioDestination = null;
  3554. let mediaRecorder = null;
  3555. const audioChunks = [];
  3556. // 设置视频源
  3557. videoElement.src = URL.createObjectURL(videoBlob);
  3558. videoElement.onloadedmetadata = () => {
  3559. console.log('视频元数据已加载,视频时长:', videoElement.duration);
  3560. // 创建媒体源和目标节点
  3561. const source = audioContext.createMediaElementSource(videoElement);
  3562. audioDestination = audioContext.createMediaStreamDestination();
  3563. source.connect(audioDestination);
  3564. // 创建MediaRecorder来录制音频
  3565. mediaRecorder = new MediaRecorder(audioDestination.stream);
  3566. mediaRecorder.ondataavailable = (event) => {
  3567. if (event.data.size > 0) {
  3568. audioChunks.push(event.data);
  3569. }
  3570. };
  3571. mediaRecorder.onstop = () => {
  3572. const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
  3573. console.log('音频提取完成,大小:', audioBlob.size);
  3574. resolve(audioBlob);
  3575. };
  3576. // 开始播放视频并录制音频
  3577. videoElement.onplay = () => {
  3578. mediaRecorder.start(100);
  3579. };
  3580. videoElement.onended = () => {
  3581. mediaRecorder.stop();
  3582. audioContext.close();
  3583. };
  3584. // 开始播放
  3585. videoElement.play();
  3586. };
  3587. videoElement.onerror = (err) => {
  3588. console.error('视频加载失败:', err);
  3589. reject(new Error('视频加载失败'));
  3590. };
  3591. } catch (err) {
  3592. console.error('提取音频失败:', err);
  3593. reject(err);
  3594. }
  3595. });
  3596. },
  3597. // 添加新方法:上传音频文件
  3598. async uploadAudioFile(audioBlob, videoUrl) {
  3599. console.log('准备上传音频文件');
  3600. // 创建FormData
  3601. const formData = new FormData();
  3602. // 将Blob转换为File对象
  3603. const fileName = `audio_${Date.now()}.wav`;
  3604. const audioFile = new File([audioBlob], fileName, { type: 'audio/wav' });
  3605. // 添加文件和其他参数
  3606. formData.append('audio_file', audioFile);
  3607. formData.append('video_url', videoUrl);
  3608. formData.append('tenant_id', uni.getStorageSync('tenant_id') || '1');
  3609. formData.append('openid', uni.getStorageSync('userInfo') ? JSON.parse(uni.getStorageSync('userInfo')).openid : '');
  3610. formData.append('application_id', uni.getStorageSync('appId') || '');
  3611. return new Promise((resolve, reject) => {
  3612. // 创建XMLHttpRequest
  3613. const xhr = new XMLHttpRequest();
  3614. xhr.open('POST', `${apiBaseUrl}/api/voice_ai_interaction`, true);
  3615. xhr.timeout = 60000; // 60秒超时
  3616. xhr.onload = () => {
  3617. if (xhr.status === 200) {
  3618. try {
  3619. const response = JSON.parse(xhr.responseText);
  3620. resolve(response);
  3621. } catch (e) {
  3622. reject(new Error('解析响应失败'));
  3623. }
  3624. } else {
  3625. reject(new Error('HTTP状态: ' + xhr.status));
  3626. }
  3627. };
  3628. xhr.onerror = () => {
  3629. reject(new Error('网络错误'));
  3630. };
  3631. xhr.ontimeout = () => {
  3632. reject(new Error('请求超时'));
  3633. };
  3634. xhr.send(formData);
  3635. });
  3636. },
  3637. // 添加一个新方法:使用小程序原生音频API
  3638. /* playMiniProgramAudio() {
  3639. console.log('使用小程序原生音频API播放:', this.aiVoiceUrl);
  3640. // 标记正在播放AI语音
  3641. this.isPlayingAiVoice = true;
  3642. // 确保在播放期间不显示继续提问按钮
  3643. this.showContinueQuestionButton = false;
  3644. this.showEndInterviewButton = false;
  3645. // 检查音频URL是否有效
  3646. if (!this.aiVoiceUrl || this.aiVoiceUrl.trim() === '') {
  3647. console.error('无效的音频URL');
  3648. // 显示错误提示
  3649. // 标记播放结束
  3650. this.isPlayingAiVoice = false;
  3651. // 显示继续提问选项
  3652. this.showContinueQuestionOptions();
  3653. return;
  3654. }
  3655. try {
  3656. // 使用wx.createInnerAudioContext API (微信小程序)
  3657. const audioContext = wx.createInnerAudioContext();
  3658. // 设置音频属性
  3659. audioContext.autoplay = false;
  3660. audioContext.obeyMuteSwitch = false; // 忽略静音开关
  3661. // 监听播放开始事件
  3662. audioContext.onPlay(() => {
  3663. console.log('AI语音开始播放');
  3664. // 显示正在播放提
  3665. });
  3666. // 监听播放结束事件
  3667. audioContext.onEnded(() => {
  3668. console.log('AI语音播放结束');
  3669. // 标记播放结束
  3670. this.isPlayingAiVoice = false;
  3671. // 清空字幕
  3672. this.currentSubtitle = '';
  3673. // 销毁音频播放器
  3674. audioContext.destroy();
  3675. // 播放结束后显示继续提问选项,而不是直接跳转
  3676. this.showContinueQuestionOptions();
  3677. });
  3678. // 监听播放错误事件
  3679. audioContext.onError((err) => {
  3680. console.error('AI语音播放错误:', err);
  3681. // 标记播放结束
  3682. this.isPlayingAiVoice = false;
  3683. // 清空字幕
  3684. this.currentSubtitle = '';
  3685. // 销毁音频播放器
  3686. audioContext.destroy();
  3687. // 播放错误时也显示继续提问选项
  3688. this.showContinueQuestionOptions();
  3689. });
  3690. // 设置音频源
  3691. audioContext.src = this.aiVoiceUrl;
  3692. // 添加超时处理,如果5秒内没有开始播放,则认为出错
  3693. const playTimeout = setTimeout(() => {
  3694. if (this.isPlayingAiVoice) {
  3695. console.warn('小程序音频播放超时,尝试备选方法');
  3696. this.tryMiniProgramFallbackAudioPlay();
  3697. }
  3698. }, 5000);
  3699. // 延迟一小段时间再播放,确保src已经设置完成
  3700. setTimeout(() => {
  3701. audioContext.play();
  3702. // 播放开始后清除超时
  3703. clearTimeout(playTimeout);
  3704. }, 300);
  3705. } catch (e) {
  3706. console.error('小程序播放AI语音时发生错误:', e);
  3707. // 标记播放结束
  3708. this.isPlayingAiVoice = false;
  3709. // 显示错误提示
  3710. // 使用文本显示方式作为备选方案
  3711. this.handleAudioPlaybackFailure();
  3712. }
  3713. }, */
  3714. // 添加新方法:小程序环境的备选音频播放方法
  3715. tryMiniProgramFallbackAudioPlay() {
  3716. console.log('使用小程序备选方法播放音频:', this.aiVoiceUrl);
  3717. // 先下载音频文件到本地
  3718. uni.downloadFile({
  3719. url: this.aiVoiceUrl,
  3720. success: (res) => {
  3721. if (res.statusCode === 200) {
  3722. console.log('小程序音频文件下载成功:', res.tempFilePath);
  3723. // 使用新的音频上下文播放本地文件
  3724. const newAudioContext = wx.createInnerAudioContext();
  3725. newAudioContext.autoplay = true;
  3726. newAudioContext.src = res.tempFilePath;
  3727. // 设置事件监听
  3728. newAudioContext.onPlay(() => {
  3729. console.log('小程序备选方法:音频开始播放');
  3730. });
  3731. newAudioContext.onEnded(() => {
  3732. console.log('小程序备选方法:音频播放结束');
  3733. this.isPlayingAiVoice = false;
  3734. this.currentSubtitle = '';
  3735. newAudioContext.destroy();
  3736. this.showContinueQuestionOptions();
  3737. this.checkPendingNavigation();
  3738. });
  3739. newAudioContext.onError((err) => {
  3740. console.error('小程序备选方法:音频播放错误:', err);
  3741. this.isPlayingAiVoice = false;
  3742. this.currentSubtitle = '';
  3743. newAudioContext.destroy();
  3744. // 尝试使用系统播放器作为最后的备选方案
  3745. this.trySystemAudioPlayer();
  3746. });
  3747. } else {
  3748. console.error('小程序音频文件下载失败:', res);
  3749. this.handleAudioPlaybackFailure();
  3750. }
  3751. },
  3752. fail: (err) => {
  3753. console.error('小程序音频文件下载请求失败:', err);
  3754. this.handleAudioPlaybackFailure();
  3755. }
  3756. });
  3757. },
  3758. // 添加新方法:尝试使用系统播放器
  3759. trySystemAudioPlayer() {
  3760. console.log('尝试使用系统播放器播放音频');
  3761. // 检查平台
  3762. const systemInfo = uni.getSystemInfoSync();
  3763. if (systemInfo.platform === 'android' || systemInfo.platform === 'ios') {
  3764. // 在移动端尝试使用系统播放器
  3765. /* uni.showToast({
  3766. title: '正在使用系统播放器',
  3767. icon: 'none',
  3768. duration: 2000
  3769. }); */
  3770. // 使用uni.playVoice API (如果可用)
  3771. if (typeof uni.playVoice === 'function') {
  3772. uni.playVoice({
  3773. filePath: this.aiVoiceUrl,
  3774. success: () => {
  3775. console.log('系统播放器播放成功');
  3776. setTimeout(() => {
  3777. this.isPlayingAiVoice = false;
  3778. this.currentSubtitle = '';
  3779. this.showContinueQuestionOptions();
  3780. }, 5000); // 假设音频长度约为5秒
  3781. },
  3782. fail: (err) => {
  3783. console.error('系统播放器播放失败:', err);
  3784. this.handleAudioPlaybackFailure();
  3785. }
  3786. });
  3787. } else {
  3788. // 如果uni.playVoice不可用,尝试使用uni.openDocument
  3789. uni.openDocument({
  3790. filePath: this.aiVoiceUrl,
  3791. fileType: 'audio',
  3792. success: () => {
  3793. console.log('使用系统应用打开音频文件');
  3794. // 由于控制权交给了系统,我们需要手动处理后续流程
  3795. setTimeout(() => {
  3796. this.isPlayingAiVoice = false;
  3797. this.currentSubtitle = '';
  3798. this.showContinueQuestionOptions();
  3799. }, 8000); // 给用户足够的时间听完音频
  3800. },
  3801. fail: (err) => {
  3802. console.error('无法使用系统应用打开音频:', err);
  3803. this.handleAudioPlaybackFailure();
  3804. }
  3805. });
  3806. }
  3807. } else {
  3808. // 在其他平台上直接使用文本显示
  3809. this.handleAudioPlaybackFailure();
  3810. }
  3811. },
  3812. // 修改 showContinueQuestionOptions 方法,确保状态正确设置
  3813. showContinueQuestionOptions() {
  3814. // 如果正在播放AI语音,不执行此方法
  3815. if (this.isPlayingAiVoice) {
  3816. console.log('AI语音正在播放,暂不显示继续提问选项');
  3817. return;
  3818. }
  3819. // 增加提问轮次计数
  3820. this.questionRound++;
  3821. // 清空字幕
  3822. this.currentSubtitle = '';
  3823. // 直接跳转到下一页,不再显示继续提问按钮
  3824. console.log('准备跳转到下一页面');
  3825. // 延迟3秒后跳转,给用户一些时间查看状态
  3826. setTimeout(() => {
  3827. this.navigateToNextPage();
  3828. }, 3000);
  3829. // 确保所有录制状态被重置
  3830. this.isRecording = false;
  3831. if (this.recordingTimer) {
  3832. clearInterval(this.recordingTimer);
  3833. this.recordingTimer = null;
  3834. }
  3835. // 重置录制相关数据
  3836. this.recordedChunks = [];
  3837. this.recordingTimerCount = 0;
  3838. this.remainingTime = this.maxRecordingTime;
  3839. },
  3840. // 修复 handleContinueQuestionClick 方法,确保状态正确重置
  3841. handleContinueQuestionClick() {
  3842. // 如果AI语音仍在播放,不允许继续提问
  3843. if (this.isPlayingAiVoice) {
  3844. /* uni.showToast({
  3845. title: '请等待面试官回复完成',
  3846. icon: 'none',
  3847. duration: 2000
  3848. }); */
  3849. return;
  3850. }
  3851. // 隐藏继续提问和结束面试按钮
  3852. this.showContinueQuestionButton = false;
  3853. this.showEndInterviewButton = false;
  3854. // 重置录制相关状态
  3855. this.isRecording = false;
  3856. this.recordingTimerCount = 0;
  3857. this.remainingTime = this.maxRecordingTime;
  3858. this.recordingTimeDisplay = '00:00 / ' + this.formatTime(this.maxRecordingTime);
  3859. // 清空已录制的数据
  3860. this.recordedChunks = [];
  3861. // 如果有正在进行的录制,先停止
  3862. if (this.mediaRecorder && this.mediaRecorder.state === 'recording') {
  3863. this.mediaRecorder.stop();
  3864. }
  3865. if (this.recorder) {
  3866. try {
  3867. this.cameraContext.stopRecord();
  3868. } catch (e) {
  3869. console.error('停止录制失败:', e);
  3870. }
  3871. this.recorder = null;
  3872. }
  3873. // 延迟一小段时间再开始新的录制,确保之前的录制已完全停止
  3874. setTimeout(() => {
  3875. // 开始新一轮录制
  3876. this.startRecordingAnswer();
  3877. }, 500);
  3878. },
  3879. // 添加新方法:处理结束面试按钮点击
  3880. handleEndInterviewClick() {
  3881. // 隐藏继续提问和结束面试按钮
  3882. this.showContinueQuestionButton = false;
  3883. this.showEndInterviewButton = false;
  3884. // 显示结束提示
  3885. /* uni.showToast({
  3886. title: '面试已结束',
  3887. icon: 'success',
  3888. duration: 1500
  3889. }); */
  3890. // 执行现有的跳转逻辑
  3891. this.navigateToNextPage();
  3892. },
  3893. // 添加新方法:处理录制错误
  3894. handleRecordingError(error) {
  3895. console.error('录制错误:', error);
  3896. // 显示错误提示
  3897. /* uni.showToast({
  3898. title: '录制失败,请重试',
  3899. icon: 'none',
  3900. duration: 2000
  3901. }); */
  3902. // 重置录制状态
  3903. this.isRecording = false;
  3904. this.showStopRecordingButton = false;
  3905. // 显示重试按钮
  3906. this.showStartRecordingButton = true;
  3907. },
  3908. // 添加新方法:处理上传错误
  3909. handleUploadError(error) {
  3910. console.error('上传错误:', error);
  3911. // 显示错误提示
  3912. /* uni.showToast({
  3913. title: '上传失败,请重试',
  3914. icon: 'none',
  3915. duration: 2000
  3916. }); */
  3917. // 显示重试按钮
  3918. this.showRetryButton = true;
  3919. // 隐藏上传状态
  3920. this.showUploadStatus = false;
  3921. this.isUploading = false;
  3922. },
  3923. // 添加新方法:检查是否有待处理的自动跳转
  3924. checkPendingNavigation() {
  3925. // 确保所有处理都已完成
  3926. if (this.pendingAutoNavigation &&
  3927. !this.isPlayingAiVoice &&
  3928. !this.isUploading &&
  3929. !this.currentSubtitle) { // 确保字幕也已经清空
  3930. console.log('所有处理已完成,准备跳转');
  3931. // 重置标志
  3932. this.pendingAutoNavigation = false;
  3933. // 延迟跳转,给用户一点时间看到最终状态
  3934. setTimeout(() => {
  3935. this.navigateToNextPage();
  3936. }, 1000);
  3937. }
  3938. },
  3939. // 添加新方法:显示文本回复
  3940. displayTextResponse() {
  3941. // 标记为正在"播放"
  3942. this.isPlayingAiVoice = true;
  3943. // 显示AI回复文本
  3944. this.currentSubtitle = '';
  3945. // 计算每个字的显示时间(假设每个字需要200毫秒)
  3946. const charDisplayTime = 200;
  3947. let currentIndex = 0;
  3948. // 使用定时器逐字显示文本
  3949. const textInterval = setInterval(() => {
  3950. if (currentIndex <= this.aiText.length) {
  3951. this.currentSubtitle = this.aiText.substring(0, currentIndex);
  3952. currentIndex++;
  3953. } else {
  3954. // 文本显示完成
  3955. clearInterval(textInterval);
  3956. // 等待用户阅读完整文本
  3957. setTimeout(() => {
  3958. // 标记播放结束
  3959. this.isPlayingAiVoice = false;
  3960. // 清空字幕
  3961. this.currentSubtitle = '';
  3962. // 显示继续提问选项
  3963. this.showContinueQuestionOptions();
  3964. // 检查是否需要自动跳转
  3965. this.checkPendingNavigation();
  3966. }, 3000); // 给用户3秒时间阅读完整文本
  3967. }
  3968. }, charDisplayTime);
  3969. },
  3970. // 添加新方法:检查不支持的音频格式
  3971. checkUnsupportedAudioFormat(url) {
  3972. if (!url) return false;
  3973. // 获取URL的文件扩展名
  3974. const extension = url.split('.').pop().toLowerCase();
  3975. // 检查平台
  3976. const systemInfo = uni.getSystemInfoSync();
  3977. const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
  3978. if (isMiniProgram) {
  3979. // 微信小程序支持的音频格式有限,主要是mp3和wav
  3980. // 检查是否是不支持的格式
  3981. const unsupportedFormats = ['ogg', 'flac', 'aac', 'm4a', 'opus'];
  3982. return unsupportedFormats.includes(extension);
  3983. }
  3984. return false;
  3985. },
  3986. // 修改文本回退方法
  3987. useIOSTextFallback() {
  3988. console.log('切换到文本显示模式');
  3989. this.isPlayingAiVoice = false;
  3990. if (!this.hasShownTextFallbackToast) {
  3991. this.hasShownTextFallbackToast = true;
  3992. }
  3993. // 显示AI回复文本
  3994. this.currentSubtitle = this.aiText || '抱歉,无法获取AI回复内容';
  3995. // 根据文本长度计算阅读时间
  3996. const textLength = this.aiText ? this.aiText.length : 20;
  3997. const readingTime = Math.max(8000, Math.min(textLength * 150, 20000)); // 最少8秒,最多20秒
  3998. console.log(`文本长度: ${textLength}字,预计阅读时间: ${readingTime/1000}秒`);
  3999. // 等待用户阅读完成后再跳转
  4000. setTimeout(() => {
  4001. this.navigateToNextPage();
  4002. }, readingTime);
  4003. },
  4004. // 添加音频预加载方法
  4005. preloadAudio(audioUrl) {
  4006. return new Promise((resolve, reject) => {
  4007. console.log('开始预加载音频:', audioUrl);
  4008. // 使用wx.downloadFile下载音频文件
  4009. const downloadTask = wx.downloadFile({
  4010. url: audioUrl,
  4011. success: (res) => {
  4012. if (res.statusCode === 200) {
  4013. console.log('音频文件下载成功,临时路径:', res.tempFilePath);
  4014. resolve(res.tempFilePath);
  4015. } else {
  4016. console.error('音频文件下载失败,状态码:', res.statusCode);
  4017. reject(new Error(`下载失败,状态码: ${res.statusCode}`));
  4018. }
  4019. },
  4020. fail: (error) => {
  4021. console.error('音频文件下载失败:', error);
  4022. reject(error);
  4023. }
  4024. });
  4025. // 监听下载进度
  4026. downloadTask.onProgressUpdate((res) => {
  4027. console.log('音频下载进度:', res.progress);
  4028. });
  4029. });
  4030. },
  4031. // 修改音频播放方法
  4032. playMiniProgramAudio() {
  4033. return new Promise(async (resolve, reject) => {
  4034. try {
  4035. // 显示加载提示
  4036. uni.showLoading({
  4037. title: '音频加载中...',
  4038. mask: true
  4039. });
  4040. // 先下载音频文件
  4041. const localAudioPath = await this.preloadAudio(this.aiVoiceUrl);
  4042. // 隐藏加载提示
  4043. uni.hideLoading();
  4044. const audioContext = wx.createInnerAudioContext();
  4045. audioContext.src = localAudioPath; // 使用本地文件路径
  4046. audioContext.autoplay = true;
  4047. // 设置音频缓冲大小
  4048. audioContext.bufferSize = 4096;
  4049. let hasStarted = false;
  4050. let hasError = false;
  4051. audioContext.onPlay(() => {
  4052. console.log('AI语音开始播放');
  4053. hasStarted = true;
  4054. this.currentSubtitle = this.aiText;
  4055. });
  4056. audioContext.onEnded(() => {
  4057. console.log('AI语音播放结束');
  4058. this.isPlayingAiVoice = false;
  4059. this.currentSubtitle = '';
  4060. audioContext.destroy();
  4061. // 确保在播放完成后立即解析Promise并跳转
  4062. if (!hasError) {
  4063. console.log('准备跳转到下一页');
  4064. this.navigateToNextPage(); // 添加这行
  4065. resolve();
  4066. }
  4067. });
  4068. audioContext.onStop(() => {
  4069. console.log('AI语音播放停止');
  4070. this.isPlayingAiVoice = false;
  4071. this.currentSubtitle = '';
  4072. audioContext.destroy();
  4073. // 如果是正常停止(非错误导致),也要触发跳转
  4074. if (!hasError) {
  4075. console.log('播放停止,准备跳转到下一页');
  4076. this.navigateToNextPage(); // 添加这行
  4077. resolve();
  4078. }
  4079. });
  4080. audioContext.onError((err) => {
  4081. hasError = true;
  4082. console.error('AI语音播放错误:', err);
  4083. audioContext.destroy();
  4084. // 显示错误提示
  4085. uni.showToast({
  4086. title: '音频播放异常,将显示文字',
  4087. icon: 'none',
  4088. duration: 2000
  4089. });
  4090. // 尝试使用备选音频格式
  4091. if (this.aiVoiceUrl.endsWith('.mp3')) {
  4092. const wavUrl = this.aiVoiceUrl.replace('.mp3', '.wav');
  4093. console.log('尝试使用WAV格式:', wavUrl);
  4094. this.aiVoiceUrl = wavUrl;
  4095. this.playMiniProgramAudio()
  4096. .then(resolve)
  4097. .catch(reject);
  4098. } else {
  4099. reject(err);
  4100. }
  4101. });
  4102. // 设置超时检测
  4103. setTimeout(() => {
  4104. if (!hasStarted && !hasError) {
  4105. console.error('音频播放启动超时');
  4106. audioContext.destroy();
  4107. reject(new Error('音频播放启动超时'));
  4108. }
  4109. }, 5000);
  4110. } catch (error) {
  4111. uni.hideLoading();
  4112. console.error('音频播放初始化失败:', error);
  4113. reject(error);
  4114. }
  4115. });
  4116. },
  4117. // 添加备选的音频播放方法
  4118. async playFallbackAudio() {
  4119. return new Promise((resolve, reject) => {
  4120. try {
  4121. const audio = wx.createInnerAudioContext();
  4122. // 尝试使用较低质量的音频设置
  4123. audio.volume = 1.0;
  4124. audio.playbackRate = 1.0;
  4125. audio.src = this.aiVoiceUrl;
  4126. audio.autoplay = true;
  4127. audio.onPlay(() => {
  4128. console.log('备选音频开始播放');
  4129. });
  4130. audio.onEnded(() => {
  4131. console.log('备选音频播放完成');
  4132. audio.destroy();
  4133. resolve();
  4134. });
  4135. audio.onError((err) => {
  4136. console.error('备选音频播放失败:', err);
  4137. audio.destroy();
  4138. reject(err);
  4139. });
  4140. } catch (error) {
  4141. reject(error);
  4142. }
  4143. });
  4144. },
  4145. // 修改主音频播放方法
  4146. async playAiVoice() {
  4147. console.log('开始播放AI语音:', this.aiVoiceUrl);
  4148. this.isPlayingAiVoice = true;
  4149. this.currentSubtitle = this.aiText;
  4150. try {
  4151. // 首先尝试主要播放方法
  4152. await this.playMiniProgramAudio();
  4153. console.log('音频播放完成,准备跳转');
  4154. // 确保在音频播放完成后立即跳转
  4155. this.navigateToNextPage();
  4156. } catch (error) {
  4157. console.error('主要播放方法失败,尝试备选方法:', error);
  4158. try {
  4159. // 尝试备选播放方法
  4160. await this.playFallbackAudio();
  4161. console.log('备选音频播放完成,准备跳转');
  4162. this.navigateToNextPage();
  4163. } catch (fallbackError) {
  4164. console.error('备选播放方法也失败:', fallbackError);
  4165. // 如果所有播放方法都失败,回退到文本显示
  4166. this.useTextFallbackAndNavigate();
  4167. }
  4168. }
  4169. },
  4170. // 监听字幕内容变化
  4171. handleSubtitleChange() {
  4172. this.$nextTick(() => {
  4173. const subtitleEl = document.querySelector('.subtitle-overlay');
  4174. if (subtitleEl) {
  4175. const contentHeight = subtitleEl.scrollHeight;
  4176. this.subtitleHeight = contentHeight;
  4177. // 如果内容高度超过视口高度的30%,则展开字幕
  4178. this.isSubtitleExpanded = contentHeight > window.innerHeight * 0.3;
  4179. }
  4180. });
  4181. },
  4182. },
  4183. // 添加watch来监听字幕内容变化
  4184. watch: {
  4185. currentSubtitle: {
  4186. handler(newVal) {
  4187. if (newVal) {
  4188. this.handleSubtitleChange();
  4189. } else {
  4190. this.isSubtitleExpanded = false;
  4191. }
  4192. },
  4193. immediate: true
  4194. }
  4195. }
  4196. }
  4197. </script>
  4198. <style scoped>
  4199. .identity-verify-container {
  4200. padding: 0;
  4201. max-width: 100%;
  4202. margin: 0 auto;
  4203. height: 100vh;
  4204. display: flex;
  4205. flex-direction: column;
  4206. background-color: #f5f5f5;
  4207. }
  4208. .digital-human-container {
  4209. position: relative;
  4210. width: 100%;
  4211. height: 100vh;
  4212. overflow: hidden;
  4213. background-color: #f0f0f0;
  4214. }
  4215. .digital-human-video {
  4216. width: 100%;
  4217. height: 100%;
  4218. display: flex;
  4219. justify-content: center;
  4220. align-items: center;
  4221. }
  4222. /* 添加视频蒙层样式 */
  4223. .video-overlay {
  4224. position: absolute;
  4225. top: 0;
  4226. left: 0;
  4227. width: 100%;
  4228. height: 100%;
  4229. background-color: transparent; /* 完全透明 */
  4230. z-index: 6; /* 确保在视频之上,但在按钮和字幕之下 */
  4231. pointer-events: auto; /* 允许捕获点击事件 */
  4232. }
  4233. /* 用户摄像头容器样式 */
  4234. .user-camera-container {
  4235. position: absolute;
  4236. top: 50px;
  4237. right: 5px;
  4238. width: 110px; /* 稍微增加宽度 */
  4239. height: 160px; /* 稍微增加高度 */
  4240. border-radius: 4px; /* 减小圆角 */
  4241. overflow: hidden;
  4242. box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
  4243. z-index: 20;
  4244. }
  4245. /* 用户摄像头视频样式 */
  4246. .user-camera-video {
  4247. width: 100%;
  4248. height: 100%;
  4249. object-fit: cover;
  4250. background-color: #333;
  4251. }
  4252. .video-player {
  4253. width: 100%;
  4254. height: 100%;
  4255. object-fit: cover;
  4256. outline: none; /* 移除视频获得焦点时的轮廓 */
  4257. -webkit-tap-highlight-color: transparent; /* 移除移动设备上的点击高亮 */
  4258. }
  4259. /* 隐藏视频控制条 */
  4260. video::-webkit-media-controls {
  4261. display: none !important;
  4262. }
  4263. video::-webkit-media-controls-enclosure {
  4264. display: none !important;
  4265. }
  4266. video::-webkit-media-controls-panel {
  4267. display: none !important;
  4268. }
  4269. video::-webkit-media-controls-play-button {
  4270. display: none !important;
  4271. }
  4272. video::-webkit-media-controls-timeline {
  4273. display: none !important;
  4274. }
  4275. video::-webkit-media-controls-current-time-display {
  4276. display: none !important;
  4277. }
  4278. video::-webkit-media-controls-time-remaining-display {
  4279. display: none !important;
  4280. }
  4281. video::-webkit-media-controls-mute-button {
  4282. display: none !important;
  4283. }
  4284. video::-webkit-media-controls-volume-slider {
  4285. display: none !important;
  4286. }
  4287. video::-webkit-media-controls-fullscreen-button {
  4288. display: none !important;
  4289. }
  4290. /* 修改字幕覆盖层样式,使其与图片中的样式一致 */
  4291. .subtitle-overlay {
  4292. position: absolute;
  4293. bottom: 100px; /* 初始底部距离 */
  4294. left: 5%; /* 从左侧留出5%的空间 */
  4295. width: 80%; /* 宽度设为90%,两侧各留5%实现居中 */
  4296. max-height: calc(70vh - 100px); /* 最大高度为视口高度的70%减去底部距离 */
  4297. padding: 15px 20px; /* 增加左右内边距 */
  4298. border-radius: 15px;
  4299. background-color: rgba(255, 255, 255, 0.9); /* 白色半透明背景 */
  4300. color: #333; /* 文字颜色为深色 */
  4301. text-align: left; /* 文字左对齐 */
  4302. font-size: 16px;
  4303. line-height: 1.5;
  4304. z-index: 10;
  4305. margin: 0 auto; /* 添加自动边距实现居中 */
  4306. box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 添加轻微阴影 */
  4307. display: flex;
  4308. flex-direction: column;
  4309. align-items: center;
  4310. gap: 10px;
  4311. overflow-y: auto; /* 添加垂直滚动 */
  4312. transform: translateY(0); /* 用于动画 */
  4313. transition: transform 0.3s ease, bottom 0.3s ease; /* 添加平滑过渡效果 */
  4314. }
  4315. /* 当内容高度超过一定值时,自动调整底部距离 */
  4316. .subtitle-overlay.expanded {
  4317. bottom: 50px; /* 减小底部距离 */
  4318. max-height: calc(80vh - 50px); /* 增加最大高度 */
  4319. }
  4320. /* 自定义滚动条样式 */
  4321. .subtitle-overlay::-webkit-scrollbar {
  4322. width: 4px;
  4323. }
  4324. .subtitle-overlay::-webkit-scrollbar-track {
  4325. background: rgba(0, 0, 0, 0.1);
  4326. border-radius: 2px;
  4327. }
  4328. .subtitle-overlay::-webkit-scrollbar-thumb {
  4329. background: rgba(0, 0, 0, 0.2);
  4330. border-radius: 2px;
  4331. }
  4332. .subtitle-overlay::-webkit-scrollbar-thumb:hover {
  4333. background: rgba(0, 0, 0, 0.3);
  4334. }
  4335. /* 继续按钮样式 */
  4336. .next-button {
  4337. background-color: #0039b3;
  4338. color: white;
  4339. border: none;
  4340. padding: 8px 20px;
  4341. border-radius: 20px;
  4342. cursor: pointer;
  4343. font-size: 14px;
  4344. margin-top: 10px;
  4345. transition: all 0.3s;
  4346. width: 140px;
  4347. height: 36px;
  4348. display: flex;
  4349. justify-content: center;
  4350. align-items: center;
  4351. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  4352. }
  4353. .next-button:hover {
  4354. background-color: #002b8f;
  4355. transform: translateY(-1px);
  4356. box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  4357. }
  4358. .next-button:active {
  4359. background-color: #001d66;
  4360. transform: translateY(1px);
  4361. box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  4362. }
  4363. /* 添加计时器样式,右侧显示橙色圆点和时间 */
  4364. .subtitle-overlay::after {
  4365. content: attr(data-time);
  4366. position: absolute;
  4367. right: 20px;
  4368. bottom: 15px;
  4369. color: #333;
  4370. font-size: 14px;
  4371. }
  4372. .control-panel {
  4373. padding: 15px;
  4374. display: flex;
  4375. justify-content: center;
  4376. }
  4377. .control-button {
  4378. padding: 10px 20px;
  4379. background-color: #4CAF50;
  4380. color: white;
  4381. border: none;
  4382. border-radius: 4px;
  4383. cursor: pointer;
  4384. }
  4385. .loading {
  4386. text-align: center;
  4387. margin: 20px 0;
  4388. font-size: 16px;
  4389. }
  4390. .response-container {
  4391. margin-top: 20px;
  4392. padding: 0 20px;
  4393. display: none; /* 默认隐藏调试信息 */
  4394. }
  4395. /* 当showDebugInfo为true时显示 */
  4396. .showDebugInfo .response-container {
  4397. display: block;
  4398. }
  4399. .response-item {
  4400. padding: 10px;
  4401. border: 1px solid #eee;
  4402. border-radius: 4px;
  4403. margin-bottom: 10px;
  4404. background-color: #f9f9f9;
  4405. }
  4406. .response-content {
  4407. display: flex;
  4408. flex-direction: column;
  4409. }
  4410. .answer-button-container {
  4411. position: absolute;
  4412. bottom: 50px; /* 将按钮放在底部而不是75%的位置 */
  4413. left: 50%;
  4414. transform: translateX(-50%); /* 只在X轴上平移,保持水平居中 */
  4415. z-index: 20;
  4416. }
  4417. /* 修改回答按钮样式 */
  4418. .answer-button {
  4419. width: 120px;
  4420. height: 40px; /* 改为矩形按钮 */
  4421. border-radius: 20px; /* 圆角矩形 */
  4422. background-color: #ffffff; /* 白色背景 */
  4423. color: #333; /* 深色文字 */
  4424. font-size: 16px;
  4425. border: none;
  4426. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  4427. display: flex;
  4428. justify-content: center;
  4429. align-items: center;
  4430. cursor: pointer;
  4431. animation: none; /* 移除脉动动画 */
  4432. }
  4433. .stop-recording-button-container {
  4434. position: absolute;
  4435. bottom: 50px; /* 统一与其他按钮的位置 */
  4436. left: 50%;
  4437. transform: translateX(-50%);
  4438. z-index: 20;
  4439. }
  4440. .stop-recording-button {
  4441. width: 120px;
  4442. height: 40px; /* 改为矩形按钮 */
  4443. border-radius: 20px; /* 圆角矩形 */
  4444. background-color: #0039b3; /* 白色背景 */
  4445. color: #fff; /* 深色文字 */
  4446. font-size: 16px;
  4447. border: none;
  4448. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  4449. display: flex;
  4450. justify-content: center;
  4451. align-items: center;
  4452. cursor: pointer;
  4453. animation: none; /* 移除脉动动画 */
  4454. }
  4455. .recording-indicator {
  4456. position: absolute;
  4457. top: 20px;
  4458. left: 20px;
  4459. display: flex;
  4460. align-items: center;
  4461. background-color: rgba(255, 255, 255, 0.9); /* 改为白色半透明背景 */
  4462. padding: 5px 10px;
  4463. border-radius: 15px;
  4464. z-index: 20;
  4465. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  4466. }
  4467. .recording-dot {
  4468. width: 12px;
  4469. height: 12px;
  4470. background-color: #ff6b00; /* 改为橙色,与图片中的颜色一致 */
  4471. border-radius: 50%;
  4472. margin-right: 8px;
  4473. animation: blink 1s infinite;
  4474. }
  4475. .recording-text {
  4476. color: #333; /* 改为深色文字 */
  4477. font-size: 14px;
  4478. }
  4479. .timer-text {
  4480. color: #333; /* 改为深色文字 */
  4481. font-size: 14px;
  4482. margin-left: 8px;
  4483. }
  4484. .start-recording-button-container {
  4485. position: absolute;
  4486. bottom: 50px; /* 统一与其他按钮的位置 */
  4487. left: 50%;
  4488. transform: translateX(-50%);
  4489. z-index: 101;
  4490. }
  4491. .start-recording-button {
  4492. width: 120px;
  4493. height: 40px; /* 改为矩形按钮 */
  4494. border-radius: 20px; /* 圆角矩形 */
  4495. background-color: #ffffff; /* 白色背景 */
  4496. color: #333; /* 深色文字 */
  4497. font-size: 16px;
  4498. border: none;
  4499. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  4500. display: flex;
  4501. justify-content: center;
  4502. align-items: center;
  4503. cursor: pointer;
  4504. animation: none; /* 移除脉动动画 */
  4505. }
  4506. .retry-button-container {
  4507. position: absolute;
  4508. bottom: 30px; /* 统一与其他按钮的位置 */
  4509. left: 50%;
  4510. transform: translateX(-50%);
  4511. z-index: 20;
  4512. }
  4513. .retry-button {
  4514. padding: 10px 20px;
  4515. background-color: #ffffff; /* 白色背景 */
  4516. color: #333; /* 深色文字 */
  4517. font-size: 16px;
  4518. border: none;
  4519. border-radius: 20px; /* 圆角矩形 */
  4520. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  4521. cursor: pointer;
  4522. }
  4523. .retry-button:hover {
  4524. background-color: #2980b9;
  4525. }
  4526. /* 录制时长显示 */
  4527. .recording-timer {
  4528. position: absolute;
  4529. top: 20px;
  4530. left: 130px; /* 放在录制指示器旁边 */
  4531. background-color: rgba(0, 0, 0, 0.6);
  4532. padding: 5px 10px;
  4533. border-radius: 15px;
  4534. z-index: 20;
  4535. display: flex;
  4536. flex-direction: column;
  4537. }
  4538. .timer-text {
  4539. color: #000;
  4540. font-size: 14px;
  4541. font-family: monospace; /* 使用等宽字体,使时间显示更稳定 */
  4542. }
  4543. .remaining-time {
  4544. color: white;
  4545. font-size: 12px;
  4546. margin-top: 2px;
  4547. }
  4548. .remaining-time.warning {
  4549. color: #ff6b6b; /* 剩余时间少时显示红色 */
  4550. animation: blink 1s infinite; /* 使用闪烁动画提醒用户 */
  4551. }
  4552. /* 添加上传状态指示器 */
  4553. .upload-status-indicator {
  4554. position: absolute;
  4555. top: 20px;
  4556. left: 130px; /* 放在录制指示器旁边 */
  4557. background-color: rgba(0, 0, 0, 0.6);
  4558. padding: 5px 10px;
  4559. border-radius: 15px;
  4560. z-index: 20;
  4561. }
  4562. .upload-status-content {
  4563. display: flex;
  4564. align-items: center;
  4565. }
  4566. .upload-status-icon {
  4567. width: 12px;
  4568. height: 12px;
  4569. border-radius: 50%;
  4570. margin-right: 8px;
  4571. }
  4572. .upload-status-text {
  4573. color: white;
  4574. font-size: 14px;
  4575. }
  4576. .uploading {
  4577. background-color: #e74c3c;
  4578. }
  4579. /* 添加倒计时蒙层样式 */
  4580. .countdown-overlay {
  4581. position: fixed;
  4582. top: 0;
  4583. left: 0;
  4584. width: 100%;
  4585. height: 100%;
  4586. background-color: rgba(0, 0, 0, 0.7);
  4587. z-index: 100;
  4588. display: flex;
  4589. justify-content: center;
  4590. align-items: center;
  4591. }
  4592. .countdown-content {
  4593. display: flex;
  4594. flex-direction: column;
  4595. align-items: center;
  4596. }
  4597. .countdown-number {
  4598. font-size: 80px;
  4599. color: #ffffff;
  4600. font-weight: bold;
  4601. margin-bottom: 20px;
  4602. }
  4603. .countdown-text {
  4604. font-size: 24px;
  4605. color: #ffffff;
  4606. }
  4607. /* 添加GIF播放器样式 */
  4608. .gif-player {
  4609. width: 100%;
  4610. height: 100%;
  4611. object-fit: cover;
  4612. position: absolute;
  4613. top: 0;
  4614. left: 0;
  4615. z-index: 5; /* 确保GIF在视频上方但在字幕和按钮下方 */
  4616. }
  4617. /* AI语音播放蒙层样式 */
  4618. .ai-voice-overlay {
  4619. position: fixed;
  4620. top: 0;
  4621. left: 0;
  4622. width: 100%;
  4623. height: 100%;
  4624. background-color: rgba(0, 0, 0, 0.8); /* 0.8的透明度 */
  4625. z-index: 99; /* 确保在其他元素之上,但在倒计时蒙层之下 */
  4626. display: flex;
  4627. justify-content: center;
  4628. align-items: center;
  4629. }
  4630. .ai-voice-content {
  4631. display: flex;
  4632. flex-direction: column;
  4633. align-items: center;
  4634. color: #ffffff;
  4635. }
  4636. .ai-voice-icon {
  4637. width: 40px;
  4638. height: 40px;
  4639. border-radius: 50%;
  4640. background-color: #ffffff;
  4641. margin-bottom: 15px;
  4642. position: relative;
  4643. animation: pulse 1.5s infinite;
  4644. }
  4645. .ai-voice-icon::before {
  4646. content: '';
  4647. position: absolute;
  4648. top: 50%;
  4649. left: 50%;
  4650. transform: translate(-50%, -50%);
  4651. width: 20px;
  4652. height: 20px;
  4653. 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>');
  4654. background-repeat: no-repeat;
  4655. background-position: center;
  4656. }
  4657. .ai-voice-text {
  4658. font-size: 18px;
  4659. color: #ffffff;
  4660. }
  4661. @keyframes pulse {
  4662. 0% {
  4663. transform: scale(1);
  4664. opacity: 1;
  4665. }
  4666. 50% {
  4667. transform: scale(1.1);
  4668. opacity: 0.8;
  4669. }
  4670. 100% {
  4671. transform: scale(1);
  4672. opacity: 1;
  4673. }
  4674. }
  4675. /* 继续提问按钮样式 */
  4676. .continue-question-container {
  4677. position: absolute;
  4678. bottom: 100px; /* 位置高于结束面试按钮 */
  4679. left: 50%;
  4680. transform: translateX(-50%);
  4681. z-index: 20;
  4682. }
  4683. .continue-question-button {
  4684. width: 120px;
  4685. height: 40px;
  4686. border-radius: 20px;
  4687. background-color: #ffffff;
  4688. color: #333;
  4689. font-size: 16px;
  4690. border: none;
  4691. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  4692. display: flex;
  4693. justify-content: center;
  4694. align-items: center;
  4695. cursor: pointer;
  4696. }
  4697. /* 结束面试按钮样式 */
  4698. .end-interview-container {
  4699. position: absolute;
  4700. bottom: 50px;
  4701. left: 50%;
  4702. transform: translateX(-50%);
  4703. z-index: 20;
  4704. }
  4705. .end-interview-button {
  4706. width: 120px;
  4707. height: 40px;
  4708. border-radius: 20px;
  4709. background-color: #e74c3c; /* 红色背景 */
  4710. color: #ffffff; /* 白色文字 */
  4711. font-size: 16px;
  4712. border: none;
  4713. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  4714. display: flex;
  4715. justify-content: center;
  4716. align-items: center;
  4717. cursor: pointer;
  4718. }
  4719. /* 提问轮次指示器样式 */
  4720. .question-round-indicator {
  4721. position: absolute;
  4722. top: 20px;
  4723. right: 120px; /* 位置在用户摄像头左侧 */
  4724. background-color: rgba(255, 255, 255, 0.9);
  4725. padding: 5px 10px;
  4726. border-radius: 15px;
  4727. z-index: 20;
  4728. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  4729. }
  4730. .round-text {
  4731. color: #333;
  4732. font-size: 14px;
  4733. }
  4734. </style>