LocalMusic.ets 393 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612
  1. import TitleBar from './TitleBar'
  2. import { curves, display, PiPWindow, promptAction, router, SymbolGlyphModifier, window } from '@kit.ArkUI';
  3. import { VideoItem } from '../viewmodel/VideoItem';
  4. import {
  5. AppUtil,
  6. ArrayUtil,
  7. Base64Util,
  8. DateUtil,
  9. DeviceUtil,
  10. DisplayUtil,
  11. FileUtil,
  12. ImageUtil,
  13. LogUtil,
  14. MD5,
  15. PreferencesUtil,
  16. RandomUtil,
  17. StrUtil,
  18. ToastUtil
  19. } from '@pura/harmony-utils';
  20. import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  21. import { CommonConstants } from '../common/constants/CommonConstants';
  22. import Logger from '../common/util/Logger';
  23. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  24. import { Utility } from '../common/util/Utility';
  25. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  26. import commonEventManager from '@ohos.commonEventManager';
  27. import { BubbleBean } from '../viewmodel/BubbleBean';
  28. import { PopupPosition, XPopup } from '@chinalike/popup';
  29. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  30. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  31. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  32. import { MessageEvents, util, worker, ErrorEvent } from '@kit.ArkTS';
  33. import { Verify } from './Verify';
  34. import { RotatingCover } from './RotatingCover';
  35. import { PlayConstants } from '../common/constants/PlayConstants';
  36. import { effectKit } from '@kit.ArkGraphics2D';
  37. import { ColorConversion } from '../common/util/ColorConversion';
  38. import { LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  39. import { AvSessionController } from '../controller/AvSessionController';
  40. import { AvSessionWidgetListener } from '../common/widget/AvSessionWidgetListener';
  41. import { WidgetData, PlayProgress, PlayState, SongInfo, PlaylistState, PlayerStateBroadcastData } from '../common/widget/WidgetTypes';
  42. import {
  43. WIDGET_CONTROL_EVENT,
  44. WIDGET_REQUEST_STATE_EVENT,
  45. PLAYER_STATE_CHANGED_EVENT,
  46. PLAYER_SONG_CHANGED_EVENT,
  47. PLAYER_PROGRESS_CHANGED_EVENT
  48. } from '../common/widget/WidgetEventConstants';
  49. import {
  50. // DeviceChangeReason,
  51. IjkMediaPlayer,
  52. InterruptEvent,
  53. InterruptHintType,
  54. LogUtils,
  55. OnBufferingUpdateListener,
  56. OnCompletionListener,
  57. OnErrorListener,
  58. OnInfoListener,
  59. OnPreparedListener,
  60. OnSeekCompleteListener,
  61. OnTimedTextListener,
  62. OnVideoSizeChangedListener
  63. } from '@ohos/ijkplayer';
  64. import { PlayStatus } from '../common/PlayStatus';
  65. import fs from '@ohos.file.fs';
  66. import { image } from '@kit.ImageKit';
  67. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  68. import * as chardet from '@changwei/chardet';
  69. import { UniversalDetector } from '@ohos/juniversalchardet';
  70. import { SettingPage } from '../pages/SettingPage';
  71. import { secondToTime } from '../common/util/CommUtils';
  72. import { CommonConstants2 } from '../common/util/CommonConstants2';
  73. import { hilog } from '@kit.PerformanceAnalysisKit';
  74. import { LazyDataSource } from '../common/util/LazyDataSource';
  75. import MediaTable from '../common/util/MediaTable';
  76. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  77. import ImageUtils from '../common/util/ImageUtils';
  78. import { ringtone } from '@kit.RingtoneKit';
  79. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  80. import { resourceManager } from '@kit.LocalizationKit';
  81. import { deviceInfo } from '@kit.BasicServicesKit';
  82. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  83. import { LrcParser } from '@sgaolei/lrc_parser';
  84. import app from '@system.app';
  85. import { TextNodeController } from './PipLyricTextBuilder';
  86. import { IndexerView } from './IndexerView';
  87. import { KeyCode } from '@kit.InputKit';
  88. import { KnockController } from '../controller/KnockController';
  89. import { WidgetCommand, EventData, WidgetControlParams } from '../common/widget/WidgetTypes';
  90. // import { FFmpeg, FFProgressMessageParser } from '@sj/ffmpeg';
  91. const TAG = 'LocalMusic';
  92. const DEFAULT_INDEX =
  93. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  94. 'X', 'Y', 'Z']
  95. //排序类型
  96. function getTypeOrder(type: number) {
  97. switch (type) {
  98. case CommonConstants.TYPE_IS_DIR:
  99. return 1; // First
  100. case CommonConstants.TYPE_IS_CSJAD:
  101. return 2; // Middle
  102. case CommonConstants.TYPE_LOCAL:
  103. return 3; // Last
  104. default:
  105. return 4; // Unknown types, if any, go last
  106. }
  107. }
  108. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  109. // 定义接口
  110. interface HiCarAspectRatio {
  111. ratio: number;
  112. name: string;
  113. }
  114. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  115. const ITEM_HEIGHT: number = 58; // 列表项中高度
  116. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  117. //功能强大的音乐播放器
  118. @Preview
  119. @Component
  120. export struct LocalMusic {
  121. @State opacityValueImage: number = 1;
  122. @State tipPopup:boolean = false
  123. @Consume mType: number;
  124. @StorageProp('themeColor') themeColor: string =
  125. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  126. themeMode: number = 0;
  127. @State titleName: string = '首页'
  128. @State textStr: string = ''
  129. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  130. // private download_path: string = '';
  131. @Consume rootPath: string //音频根目录
  132. @Consume currentPath: string
  133. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  134. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  135. @State lockPath: string = ''
  136. @State favPath: string = ''
  137. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  138. @State historyPath: string = ''
  139. @State historyList: Array<VideoItem> = []
  140. @Consume isHistory: boolean
  141. static readonly HISTORY_MUSIC: string = 'music_historyList';
  142. private table: MediaTable = new MediaTable(getContext(this))
  143. @State isZero: boolean = false
  144. @State fileList: Array<string> = []
  145. @State dirList: Array<VideoItem> = []
  146. @Consume videoLocalList: Array<VideoItem>
  147. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  148. @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  149. @State artistList: Array<VideoItem> = []; //艺术家文件
  150. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  151. @State albumList: Array<VideoItem> = []; //专辑文件
  152. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  153. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  154. @State imageOpacities: number[] = [];
  155. @Consume isCanBack: boolean
  156. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  157. @State showSingleLyric: boolean = false
  158. @State sortType: number = 4 //默认排序方式
  159. @State isShowSimi: boolean = false //是否显示私密音频
  160. @State isShowFAV: boolean = true //是否显示我的收藏
  161. @State isShowTitleBar: boolean = true //是否显示分类导航条
  162. @State isShowAllBar: boolean = true //是否显示播放全部条
  163. @State isShowHistory: boolean = true //是否显示最近播放
  164. @State isCustomizeBg: boolean = false //自定义背景界面
  165. @State isGridMusic: boolean = false //是否网格布局
  166. @State isCircleBtn: boolean = false //是否圆形播放按钮
  167. @State twoFingerType: number = 3 //双支放大缩小的类型
  168. @State isScrollHide: boolean = false //是否滚动隐藏
  169. private widgetEventSubscriber: commonEventManager.CommonEventSubscriber | null = null; // 卡片事件订阅者
  170. private lastProgressBroadcastTime: number = 0; // 上次进度广播时间
  171. private readonly PROGRESS_BROADCAST_INTERVAL: number = 1000; // 进度广播间隔(1秒)
  172. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  173. @State isStartAutoPlay: boolean = false //启动后自动播放
  174. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  175. @State isShowHeader: boolean = true
  176. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  177. @State isShowSingleLineLyric: boolean = false //是否显示播放页返回键
  178. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  179. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  180. @State isSwipe: boolean = false //listItem的左滑开关
  181. @State openSkipSongAnimate: boolean = true//切歌动画效果
  182. @State customizeBgPath: string | undefined = '';
  183. @State isDarkMode: boolean = false
  184. @State lyricTextWeight: number = 400
  185. @State lyricTextWeightPip: number = 400
  186. @State currentSwiperIndex: number = 0
  187. @State blurValue: number = 0 //背景模糊
  188. @State bgBrightness: number = 0 //背景亮度
  189. private listScroller: ListScroller = new ListScroller()
  190. private playListScroller: Scroller = new Scroller()
  191. @StorageProp('isLandscape') isLandscape: boolean = false;
  192. @StorageProp('topRectHeight') topRectHeight: number = px2vp(AppUtil.getStatusBarHeight());
  193. @StorageProp('windowWidth') windowWidth: number = 0;
  194. @StorageProp('windowHeight') windowHeight: number = 0;
  195. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  196. private UNKONWN:string = '';
  197. private listArea: Area = {
  198. width: 0,
  199. height: 0,
  200. position: {},
  201. globalPosition: {}
  202. }
  203. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  204. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  205. onColorModeChange() {
  206. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  207. if (this.isCustomizeBg) {
  208. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  209. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  210. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  211. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  212. } else {
  213. if (!this.isDarkMode) {
  214. this.titleBarModel.setTitleBarBackground(this.themeColor)
  215. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  216. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  217. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  218. } else {
  219. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  220. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  221. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  222. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  223. }
  224. }
  225. }
  226. onModeChange() {
  227. this.isFavMusic = false
  228. if (this.modeType === 2 || this.modeType === 3) {
  229. this.titleBarModel.setRightIcon(null)
  230. } else {
  231. this.titleBarModel.setRightIcon(($r('app.media.add')))
  232. }
  233. LogUtil.info('onecold onModeChange = ' + this.modeType)
  234. switch (this.modeType) {
  235. case 0:
  236. this.getSortedFiles(this.currentPath)
  237. break
  238. case 1:
  239. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  240. this.updateListData(this.mediaKuList)
  241. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  242. break
  243. case 2:
  244. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  245. this.updateListData(this.artistList)
  246. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  247. break
  248. case 3:
  249. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  250. this.updateListData(this.albumList)
  251. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  252. break
  253. }
  254. }
  255. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  256. // @StorageLink('isPlay') isPlay: boolean = false;
  257. @StorageLink('isShowPlay') isShowPlay: boolean = false;
  258. @StorageLink('songList') songList: Array<VideoItem> = [];
  259. @State translateY: number = 0;
  260. @State isShowSheet: boolean = false;
  261. @State isShowSheetView: boolean = false;
  262. @State isShowTimeCloseView: boolean = false;
  263. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  264. @StorageLink('currIndex') curIndex: number = 0;
  265. @Consume isShowDrawer: boolean;
  266. @Consume offsetX: number;
  267. @State isFac: boolean = false;
  268. @State favList: Array<VideoItem> = []
  269. @Consume isFavMusic: boolean
  270. @State isClickedPLayAll: boolean = false;
  271. private scrollerForlist: ListScroller = new ListScroller();
  272. private knockController: KnockController | undefined = undefined;
  273. imagesF: ImageFrameInfo[] = [
  274. { src: $r("app.media.app_loading0") },
  275. { src: $r("app.media.app_loading1") },
  276. { src: $r("app.media.app_loading2") },
  277. { src: $r("app.media.app_loading3") },
  278. ]
  279. @State animationState: AnimationStatus = AnimationStatus.Initial
  280. // 缓存机制
  281. private cache: Map<string, Array<VideoItem>> = new Map();
  282. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  283. // 持久化缓存
  284. private async saveCacheToStorage() {
  285. const cacheArray = Array.from(this.cache.entries());
  286. const stringCacheArray = Array.from(this.stringCache.entries());
  287. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  288. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  289. }
  290. // 载入缓存
  291. private async loadCacheFromStorage() {
  292. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  293. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  294. if (cacheString) {
  295. const cacheArray: [string, Array<VideoItem>][] = JSON.parse(cacheString);
  296. this.cache = new Map(cacheArray);
  297. }
  298. if (stringCacheString) {
  299. const stringCacheArray: [string, string][] = JSON.parse(stringCacheString);
  300. this.stringCache = new Map(stringCacheArray);
  301. }
  302. }
  303. // 查找缓存
  304. private findCache(key: string): Array<VideoItem> | undefined {
  305. return this.cache.get(key);
  306. }
  307. // 查找字符串缓存
  308. private findStringCache(key: string): string | undefined {
  309. return this.stringCache.get(key);
  310. }
  311. // 添加缓存
  312. private addCache(key: string, value: Array<VideoItem>) {
  313. this.cache.set(key, value);
  314. }
  315. // 添加字符串缓存
  316. private addStringCache(key: string, value: string) {
  317. this.stringCache.set(key, value);
  318. }
  319. // 删除缓存
  320. private deleteCache(key: string) {
  321. this.cache.delete(key);
  322. this.saveCacheToStorage()
  323. }
  324. // 删除字符串缓存
  325. private deleteStringCache(key: string) {
  326. this.stringCache.delete(key);
  327. }
  328. // 多选机制
  329. @State selectedFiles: Array<VideoItem> = [];
  330. @State isMultiSelect: boolean = false;
  331. @State isAllSelected: boolean = false;
  332. @State appName: string = ''
  333. @State isHasDir: boolean = false
  334. @State packName: string = ''
  335. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  336. @State titleBarModel: TitleBar.Model = new TitleBar.Model()
  337. .setTitleTextStyle(FontStyle.Normal)
  338. .setTitleBarStyle(TitleBar.BarStyle.TRANSPARENT)
  339. .setLeftIcon($r('app.media.menu'))
  340. .setLeftIconWidth(26)
  341. .setLeftIconHeight(26)
  342. .setTitleName('首页')
  343. .setTitleFontSize(18)
  344. .setTitleFontColor(Color.White)
  345. .setTitleBarBackground(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  346. .setTitleBarBottomLineColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  347. .setLeftTitleStateNormalStyleColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  348. .setRightIcon($r('app.media.add'))
  349. .setOnRightClickListener(() => {
  350. this.showSheelDialog()
  351. })
  352. // .setOnTitleClickListener(() => {
  353. // this.showPupDialog()
  354. // })
  355. .setOnLeftClickListener(() => {
  356. this.doSwipBack()
  357. })
  358. doSwipBack() {
  359. if (this.modeType !== 0 && this.isCanBack) {
  360. this.onModeChange()
  361. this.isCanBack = false
  362. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  363. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  364. setTimeout(() => {
  365. if (this.modeType == 2) {
  366. if (this.isGridMusic) {
  367. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  368. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  369. } else {
  370. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  371. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  372. }
  373. } else if (this.modeType == 3) {
  374. if (this.isGridMusic) {
  375. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  376. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  377. } else {
  378. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  379. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  380. }
  381. }
  382. }, 200)
  383. return
  384. }
  385. if (this.isHistory || this.isFavMusic) {
  386. this.isHistory = false
  387. this.getSortedFiles(this.currentPath)
  388. return
  389. }
  390. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  391. animateTo({ duration: 555 }, () => {
  392. // 动画闭包内控制Image组件的出现和消失
  393. this.isShowDrawer = !this.isShowDrawer
  394. this.offsetX = 0
  395. })
  396. return
  397. }
  398. //返回上一级歌单的滚动位置
  399. setTimeout(() => {
  400. if (this.modeType == 0) {
  401. if (this.isGridMusic) {
  402. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  403. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  404. } else {
  405. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  406. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  407. }
  408. }
  409. }, 300)
  410. this.currentPath = Utility.getParentDirectory(this.currentPath)
  411. Logger.info('this.currentPath2 = ' + this.currentPath)
  412. this.getSortedFiles(this.currentPath)
  413. }
  414. // 组件生命周期
  415. aboutToAppear() {
  416. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  417. this.tipPopup = !this.tipPopup
  418. PreferencesUtil.putSync('isFirstTiped',false)
  419. }
  420. this.initSetting()
  421. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  422. this.topRectHeight = px2vp(AppUtil.getStatusBarHeight());
  423. Utility.getAppName(getContext(this)).then((appName: string) => {
  424. this.appName = appName
  425. })
  426. this.packName = AppUtil.getBundleName()
  427. this.loadCacheFromStorage(); // 加载缓存
  428. this.mkDownLoadDir()
  429. let eventMusic: emitter.InnerEvent = { eventId: 2 }
  430. // 监听广播事件(打开其他应用处理)
  431. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  432. this.saveVideoDatas([eventData.data?.message], true)
  433. });
  434. //侧滑广播接收时间
  435. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: 888 }
  436. // 监听广播事件(打开其他应用处理)
  437. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  438. animateTo({ duration: 555 }, () => {
  439. this.doSwipBack()
  440. })
  441. });
  442. //ScanFilePage广播接收时间
  443. let eventScanUpdate: emitter.InnerEvent = { eventId: 101 }
  444. // 监听ScanFilePage广播事件(更新数据库)
  445. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  446. this.doUpdateData()
  447. });
  448. let eventSetting: emitter.InnerEvent = { eventId: 333 }
  449. // 监听广播事件(通用设置配置更新)
  450. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  451. this.doChangeSetting()
  452. });
  453. let event: Callback<InterruptEvent> = (event) => {
  454. LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  455. this.savePlaybackPosition()
  456. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  457. this.pause();
  458. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  459. this.startPlayOrResumePlay();
  460. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  461. this.stop();
  462. }
  463. }
  464. this.mIjkMediaPlayer.on('audioInterrupt', event);
  465. // 音频设备断连回调处理
  466. // let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  467. // LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  468. // if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  469. // this.pause();
  470. // }
  471. // }
  472. // this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  473. this.makeWorker()
  474. // 初始化卡片事件监听器
  475. this.initWidgetEventListener();
  476. // 延迟广播初始状态到卡片(在songList初始化之后)
  477. setTimeout(() => {
  478. this.broadcastPlayerState();
  479. LogUtils.getInstance().LOGI(`Delayed state broadcast: songList.length=${this.songList.length}, curIndex=${this.curIndex}`);
  480. }, 2000);
  481. // 定期广播状态更新,确保卡片状态同步
  482. setInterval(() => {
  483. LogUtils.getInstance().LOGI('Periodic widget state broadcast');
  484. this.broadcastPlayerState();
  485. }, 10000); // 每10秒广播一次状态
  486. //折叠屏的屏幕显示模式变化
  487. display.on('foldDisplayModeChange', (data) => {
  488. this.doChangeBarHeight()
  489. });
  490. display.on('foldStatusChange', (data) => {
  491. Logger.info('onecold foldStatusChange ')
  492. });
  493. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  494. // 读取 themeMode 并同步 currentColorMode
  495. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  496. this.applyThemeMode(this.themeMode)
  497. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  498. AppStorage.setOrCreate('themeColor', themeColor);
  499. this.themeColor = themeColor;
  500. this.doChangeSetting()
  501. // 安全地注册窗口大小变化监听器
  502. if (this.windowClass) {
  503. this.windowClass.on('windowSizeChange', (size) => {
  504. LogUtil.info('onecold windowSizeChange')
  505. this.doChangeBarHeight()
  506. let viewWidth = px2vp(size.width);
  507. let viewHeight = px2vp(size.height);
  508. if(this.isPhoneLan()){
  509. this.is_auto_hide_progress = false
  510. setTimeout(() => {
  511. this.is_auto_hide_progress = true
  512. }, 6000)
  513. }else{
  514. this.startAutoHide()
  515. }
  516. });
  517. }
  518. this.eventHub.on('onStateChange', (fg: boolean) => {
  519. if (fg && this.curState === 'STARTED') {
  520. this.stopPip();
  521. }
  522. });
  523. }
  524. startAutoHide() {
  525. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  526. console.info('onecold startAutoHide')
  527. this.is_auto_hide_progress = false
  528. setTimeout(() => {
  529. this.is_auto_hide_progress = true
  530. }, 6000)
  531. }
  532. }
  533. applyThemeMode(mode: number) {
  534. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  535. if (mode === 1) {
  536. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  537. } else if (mode === 2) {
  538. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  539. }
  540. AppStorage.setOrCreate('currentColorMode', colorMode)
  541. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  542. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  543. AppStorage.setOrCreate('themeMode', mode)
  544. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  545. // 只有强制浅色/深色时才主动设置
  546. const context = getContext(this) as common.UIAbilityContext
  547. context.getApplicationContext().setColorMode(colorMode)
  548. }
  549. initSetting() {
  550. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  551. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  552. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  553. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, true)
  554. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  555. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  556. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  557. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  558. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  559. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  560. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  561. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  562. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  563. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 3)
  564. this.isCoverTop = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP, false)
  565. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  566. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  567. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  568. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  569. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  570. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  571. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  572. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  573. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  574. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  575. //如果是hicar连接状态,这些都是false
  576. if(this.isHiCarStatus){
  577. this.isShowTitleBar = false//不显示导航栏
  578. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//大屏幕不可以Grid
  579. {
  580. this.isShowHeader = false//二级菜单不显示头部
  581. this.isGridMusic= false//用list不用网格
  582. this.isCoverTopBig = false
  583. }
  584. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  585. }
  586. if (this.isSavePlayMode) {
  587. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  588. }
  589. if (this.isCustomizeBg) {
  590. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  591. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  592. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  593. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  594. } else {
  595. if (!this.isDarkMode) {
  596. this.titleBarModel.setTitleBarBackground(this.themeColor)
  597. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  598. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  599. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  600. } else {
  601. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  602. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  603. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  604. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  605. }
  606. }
  607. }
  608. doChangeSetting() {
  609. this.initSetting()
  610. this.deleteCache(this.currentPath)
  611. if (this.modeType === 0) {
  612. this.getSortedFiles(this.currentPath)
  613. }
  614. }
  615. doChangeBarHeight() {
  616. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  617. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  618. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  619. this.setBarHeightNormal()
  620. }
  621. }
  622. onPageShow() {
  623. this.knockController?.immersiveListening();
  624. app.setImageCacheCount(100);
  625. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  626. app.setImageRawDataCacheSize(104857600);
  627. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  628. }
  629. //开启线程查看各个数据库
  630. makeWorker() {
  631. setTimeout(() => {
  632. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  633. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  634. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  635. // workerInstance.postMessage({
  636. // code: 1,
  637. // data1: this.context,
  638. // data2: this.rootPath,
  639. // data3: this.lockPath,
  640. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  641. // });
  642. PreferencesUtil.putSync('isFirstApp', false)
  643. } else {
  644. workerInstance.postMessage({ code: 2, data: this.context });
  645. workerInstance.postMessage({ code: 3, data: this.context });
  646. workerInstance.postMessage({ code: 4, data: this.context });
  647. this.getHistoryList(false)
  648. }
  649. }, 1000)
  650. workerInstance.onmessage = (e: MessageEvents): void => {
  651. switch (e.data.code) {
  652. case 101: //第一次扫描文件夹入库
  653. ToastUtil.showToast('刷新同步数据库成功!')
  654. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  655. this.doUpdateData()
  656. break;
  657. case 102: //查询媒体库列表
  658. this.mediaKuList = e.data.data
  659. Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
  660. Utility.doSortListAscending(this.mediaKuList)
  661. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  662. if (this.modeType === 1) {
  663. this.updateListData(this.mediaKuList)
  664. }
  665. break;
  666. case 103: //收到查询艺术家列表
  667. this.artistMap = e.data.data1;
  668. this.artistList = e.data.data2;
  669. break;
  670. case 104: //收到查询专辑列表
  671. this.albumMap = e.data.data1;
  672. this.albumList = e.data.data2
  673. //查询完毕在启动是否自动播放
  674. if (this.isStartAutoPlay) {
  675. this.startPlayOrResumePlay()
  676. }
  677. break;
  678. }
  679. };
  680. // 在调用terminate后,执行onexit
  681. workerInstance.onexit = (code) => {
  682. console.log("main thread terminate");
  683. }
  684. //若Worker处于已销毁或正在销毁等非运行状态时,调用其功能接口,会抛出相应的错误。
  685. // 使用Worker模块时,需要在主线程中注册onerror接口,否则当worker线程出现异常时会发生jscrash问题。
  686. workerInstance.onerror = (err: ErrorEvent) => {
  687. console.log("onerror" + err.message);
  688. }
  689. // let context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
  690. //碰一碰分享的监听
  691. this.knockController = KnockController.getInstance(this.context);
  692. this.knockController?.immersiveListening();
  693. }
  694. onPageHide(): void {
  695. this.knockController?.immersiveDisableListening();
  696. }
  697. @State isFirstStartPlay: boolean = false
  698. //获取download_path
  699. async mkDownLoadDir() {
  700. const documentViewPicker = new picker.DocumentViewPicker()
  701. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  702. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  703. // this.rootPath = this.download_path
  704. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  705. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  706. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  707. Logger.info('onecold rootPath = ' + this.rootPath)
  708. Logger.info('onecold lockPath = ' + this.lockPath)
  709. if (!FileUtil.accessSync(this.lockPath)) {
  710. FileUtil.mkdirSync(this.lockPath)
  711. }
  712. if (!FileUtil.accessSync(this.favPath)) {
  713. FileUtil.mkdirSync(this.favPath)
  714. }
  715. if (!FileUtil.accessSync(this.historyPath)) {
  716. FileUtil.mkdirSync(this.historyPath)
  717. }
  718. this.getSortedFiles(this.rootPath).then(() => {
  719. this.isFavMusic = false
  720. //穿山甲
  721. // this.loadBannerAd(CSJUtil.getBannerID())
  722. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  723. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  724. if (ArrayUtil.isEmpty(this.songList)) {
  725. this.songList = this.getCurFileList()
  726. } else {
  727. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  728. }
  729. if (ArrayUtil.isNotEmpty(this.songList)) {
  730. this.isFirstStartPlay = true
  731. this.sonDataSource.pushArrayData(this.songList)
  732. if (this.currentSong === undefined) {
  733. this.isFirstStartPlay = false
  734. this.currentSong = this.songList[0]
  735. }
  736. this.videoUrl = this.currentSong.filePath
  737. this.name = this.currentSong.name
  738. this.cover = this.currentSong.pixelMapPath
  739. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  740. // 立即广播初始状态到卡片,确保hasNext和hasPrevious正确
  741. setTimeout(() => {
  742. this.broadcastPlayerState();
  743. LogUtils.getInstance().LOGI(`Initial state broadcasted: songList.length=${this.songList.length}, curIndex=${this.curIndex}`);
  744. }, 100);
  745. // 多次广播确保卡片接收到状态
  746. setTimeout(() => {
  747. this.broadcastPlayerState();
  748. LogUtils.getInstance().LOGI(`Second state broadcast: ensuring widget sync`);
  749. }, 1000);
  750. setTimeout(() => {
  751. this.broadcastPlayerState();
  752. LogUtils.getInstance().LOGI(`Third state broadcast: final sync attempt`);
  753. }, 3000);
  754. } else {
  755. this.name = '空空如也'
  756. // 即使没有歌曲也要广播状态
  757. setTimeout(() => {
  758. this.broadcastPlayerState();
  759. }, 100);
  760. }
  761. })
  762. this.getFavList(false)
  763. }
  764. getFavList(isFavRefresh: boolean) {
  765. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  766. this.favList = result
  767. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  768. this.videoLocalList = this.favList
  769. this.updateListData(this.videoLocalList)
  770. }
  771. })
  772. }
  773. getHistoryList(isRefresh: boolean) {
  774. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  775. this.historyList = result
  776. // for (let i = 0; i < this.historyList.length; i++) {
  777. //
  778. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  779. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  780. // }
  781. if (isRefresh) {
  782. this.videoLocalList = this.historyList
  783. this.updateListData(this.videoLocalList, true)
  784. }
  785. })
  786. }
  787. // 组件消失生命周期
  788. aboutToDisappear() {
  789. console.info('LifeCycleComponent aboutToDisappear');
  790. this.knockController?.immersiveDisableListening();
  791. this.curIndex = 0
  792. emitter.off(2);
  793. emitter.off(101);
  794. emitter.off(888);
  795. emitter.off(333);
  796. this.mDestroyPage = true;
  797. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  798. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  799. this.stop();
  800. }
  801. this.mIjkMediaPlayer.off('audioInterrupt');
  802. if (workerInstance) {
  803. workerInstance.terminate();
  804. }
  805. this.stopPip();
  806. this.destroyPipController();
  807. // 清理卡片事件监听器
  808. if (this.widgetEventSubscriber) {
  809. try {
  810. commonEventManager.unsubscribe(this.widgetEventSubscriber, (err: BusinessError | undefined) => {
  811. if (err) {
  812. LogUtils.getInstance().error(`Failed to unsubscribe widget events: ${JSON.stringify(err)}`);
  813. } else {
  814. LogUtils.getInstance().LOGI('Widget event listener unsubscribed successfully');
  815. }
  816. });
  817. } catch (error) {
  818. LogUtils.getInstance().error(`Error during widget event cleanup: ${error}`);
  819. }
  820. }
  821. // 清理AvSession卡片监听器
  822. try {
  823. this.avSessionWidgetListener.destroy();
  824. LogUtils.getInstance().LOGI('AvSession widget listener destroyed successfully');
  825. } catch (error) {
  826. LogUtils.getInstance().error(`Error during AvSession widget listener cleanup: ${error}`);
  827. }
  828. }
  829. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean) {
  830. this.isFavMusic = false
  831. if (isWorkerPost) {
  832. workerInstance.postMessage({ code: 2, data: this.context }); //刷新媒体库列表
  833. }
  834. if (this.modeType !== 0) {
  835. return
  836. }
  837. this.isCanBack = false
  838. this.currentPath = curPath
  839. this.titleBarModel.setTitleName(Utility.getFileDirName(this.currentPath, this.rootPath))
  840. if (curPath === this.rootPath) {
  841. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  842. } else {
  843. this.currentTitleName = Utility.getFileDirName(this.currentPath, this.rootPath)
  844. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  845. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  846. }
  847. }
  848. // Get the current file list and calculate its hash
  849. this.fileList = FileUtil.listFileSync(curPath);
  850. const currentHash = simpleHash(this.fileList);
  851. // Check cache
  852. const cachedValue = this.findCache(curPath);
  853. Logger.info('onecold cachedValue = ' + cachedValue)
  854. const cachedHash = this.findStringCache(curPath + '_hash');
  855. const cachedDirList = this.findCache(curPath + "_dirList");
  856. if (cachedValue !== undefined) {
  857. // this.videoLocalList = cachedValue;
  858. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  859. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  860. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  861. }
  862. this.updateListData(cachedValue)
  863. }
  864. if (cachedDirList !== undefined) {
  865. this.dirList = cachedDirList
  866. }
  867. //通过当前hash值和缓存hash判断list有没有变化
  868. if (cachedValue && cachedHash === currentHash) {
  869. return;
  870. }
  871. this.fileList = FileUtil.listFileSync(curPath)
  872. let directories: Array<VideoItem> = [];
  873. let files: Array<VideoItem> = [];
  874. for (let i = 0; i < this.fileList.length; i++) {
  875. console.info(`The name of file: ${this.fileList[i]}`);
  876. let path = curPath + '/' + this.fileList[i]
  877. if (FileUtil.isDirectory(path)) {
  878. let item: VideoItem =
  879. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  880. '')
  881. if (this.isShowDir(item.name)) {
  882. directories.push(item);
  883. }
  884. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  885. // Utility.doSortListAscending(directories)
  886. } else {
  887. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  888. let item: VideoItem =
  889. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  890. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  891. files.push(item);
  892. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  893. // this.doSortListAscending(files)
  894. }
  895. }
  896. }
  897. }
  898. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  899. if (this.currentPath !== this.lockPath) {
  900. files = result;
  901. }
  902. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  903. Utility.doSortListAscending(files)
  904. if (this.currentPath === this.rootPath) {
  905. this.dirList = directories
  906. this.addCache(curPath + "_dirList", this.dirList);
  907. }
  908. //插入广告先注释掉
  909. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  910. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  911. // directories.push(adItem)
  912. // }
  913. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  914. this.videoLocalList = directories.concat(files);
  915. this.updateListData(this.videoLocalList)
  916. if (ArrayUtil.isNotEmpty(files)) {
  917. if (this.currentPath != this.rootPath) {
  918. if (files) {
  919. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  920. }
  921. }
  922. // 缓存结果
  923. this.addCache(curPath, this.videoLocalList);
  924. await this.saveCacheToStorage(); // 保存缓存至本地存储
  925. this.addStringCache(curPath + '_hash', currentHash);
  926. }
  927. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  928. // for (let i = 0; i < this.videoLocalList.length; i++) {
  929. //
  930. // console.info(`onecold gengxin 1: ${this.videoLocalList[i].pixelMapPath}`);
  931. //
  932. // }
  933. // this.setButtonStatus()
  934. if (isOpen) {
  935. if (destPath === undefined) {
  936. // 处理 destPath 为 undefined 的情况
  937. return
  938. }
  939. if (destPath.endsWith('.lrc')) {
  940. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  941. if (StrUtil.isNotEmpty(this.videoUrl)) {
  942. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  943. this.initLyric(lyricPath);
  944. }
  945. return
  946. }
  947. let item2 = new VideoItem(Utility.getMediaNameByUri(destPath), destPath, destPath, 0, 0, '')
  948. this.doPlay(item2)
  949. this.isShowPlay = true
  950. }
  951. });
  952. }
  953. //扫描文件夹入库
  954. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  955. const files = FileUtil.listFileSync(curPath);
  956. let mediaItems: VideoItem[] = [];
  957. Logger.info('onecold scanDirectory start ')
  958. for (const file of files) {
  959. const fPath = `${curPath}/${file}`;
  960. if (fPath === this.lockPath) {
  961. Logger.info(`Skipping locked path: ${fPath}`);
  962. continue;
  963. }
  964. if (FileUtil.isDirectory(fPath)) {
  965. // Recursively scan subdirectories
  966. const subDirItems = await this.scanDirectory(fPath);
  967. mediaItems = mediaItems.concat(subDirItems);
  968. } else {
  969. Logger.info('onecold scanDirectory filePath = ' + fPath)
  970. // Process media files
  971. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  972. let mediaItem: VideoItem =
  973. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, true);
  974. mediaItems.push(mediaItem);
  975. this.table.insert(mediaItem, (id: number) => {
  976. });
  977. }
  978. }
  979. }
  980. return mediaItems;
  981. }
  982. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  983. animateTo({ duration: 888 }, () => {
  984. this.opacityItem = 0;
  985. });
  986. setTimeout(() => {
  987. this.videoLocalList = mList;
  988. if (!noSort) {
  989. if (this.modeType === 0 || this.modeType === 1) {
  990. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  991. this.doSortType(this.sortType)
  992. }
  993. }
  994. this.dataSource.pushArrayData(this.videoLocalList)
  995. animateTo({ duration: 888 }, () => {
  996. this.opacityItem = 1;
  997. });
  998. this.setButtonStatus()
  999. }, 200);
  1000. }
  1001. //排序模式和多选模式
  1002. showPupDialog() {
  1003. if (this.modeType === 2 || this.modeType === 3) {
  1004. this.titleBarModel.setRightIcon(null)
  1005. } else {
  1006. this.titleBarModel.setRightIcon(($r('app.media.add')))
  1007. }
  1008. let dataBean = new BubbleBean()
  1009. dataBean.data = ["首页", "媒体库", "艺术家", "专辑", "同步数据"]
  1010. dataBean.color = this.themeColor
  1011. dataBean.modeType = this.modeType
  1012. dataBean.imageRes =
  1013. [$r('app.media.home_press'), $r('app.media.kp_music'), $r('app.media.music_menu'), $r('app.media.llq'),
  1014. $r('app.media.refresh')]
  1015. let pup: XPopup;
  1016. if (this.isDarkMode) {
  1017. pup = XPopup.Builder()
  1018. .setPopupPosition(PopupPosition.BOTTOM)
  1019. .atView('pup_positon_music')
  1020. .setBackgroundColor(Color.Black)
  1021. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  1022. .show()
  1023. } else {
  1024. pup = XPopup.Builder()
  1025. .setPopupPosition(PopupPosition.BOTTOM)
  1026. .atView('pup_positon_music')
  1027. .setBackgroundColor(Color.White)
  1028. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  1029. .show()
  1030. }
  1031. dataBean.onItemClick = (i) => {
  1032. XPopup.dismissTop()
  1033. switch (i) {
  1034. case 0: //首页
  1035. this.modeType = 0
  1036. this.getSortedFiles(this.currentPath)
  1037. break
  1038. case 1:
  1039. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1040. this.modeType = 1
  1041. this.updateListData(this.mediaKuList)
  1042. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  1043. break
  1044. case 2:
  1045. this.modeType = 2
  1046. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1047. this.updateListData(this.artistList)
  1048. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  1049. break
  1050. case 3:
  1051. this.modeType = 3
  1052. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1053. this.updateListData(this.albumList)
  1054. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  1055. break
  1056. case 4: //同步数据
  1057. this.asyncCurrentPathData()
  1058. break
  1059. }
  1060. }
  1061. }
  1062. getCurFileList(): Array<VideoItem> {
  1063. let files: Array<VideoItem> = [];
  1064. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1065. for (let i = 0; i < this.videoLocalList.length; i++) {
  1066. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  1067. files.push(this.videoLocalList[i]);
  1068. }
  1069. }
  1070. }
  1071. return files
  1072. }
  1073. setButtonStatus() {
  1074. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1075. this.isZero = false
  1076. } else {
  1077. this.isZero = true
  1078. }
  1079. if (this.currentPath !== this.rootPath &&
  1080. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  1081. this.isHasDir = true //不为空,说明有子文件夹
  1082. } else {
  1083. this.isHasDir = false
  1084. }
  1085. }
  1086. showRankDialog() {
  1087. if (this.modeType === 2 || this.modeType === 3) {
  1088. //动作面板
  1089. DialogHelper.showBottomSheetDialog({
  1090. title: "请选择排序模式",
  1091. maskColor: Color.Transparent,
  1092. // sheets: ["按名称升序", "按名称降序"],
  1093. sheets: [
  1094. { value: '按名称升序', fontColor: $r('app.color.text_color') },
  1095. { value: '按名称降序', fontColor: $r('app.color.text_color') },
  1096. ],
  1097. backgroundColor: $r('app.color.bg_card'),
  1098. height: '30%',
  1099. transition: AnimationHelper.transitionInDown(555),
  1100. onAction: (index) => {
  1101. switch (index) {
  1102. case 0:
  1103. Utility.doSortListAscending(this.videoLocalList)
  1104. break;
  1105. case 1:
  1106. Utility.doSortListDescending(this.videoLocalList)
  1107. break;
  1108. }
  1109. this.updateListData(this.videoLocalList)
  1110. }
  1111. })
  1112. return
  1113. }
  1114. //动作面板
  1115. DialogHelper.showBottomSheetDialog({
  1116. title: "请选择排序模式",
  1117. maskColor: Color.Transparent,
  1118. height: '75%',
  1119. // sheets: ["按艺术家升序", "按艺术家降序", "按专辑升序", "按专辑降序", "按名称升序", "按名称降序", "按添加时间升序","按添加时间降序"],
  1120. sheets: [
  1121. { value: "按艺术家升序", fontColor: $r('app.color.text_color') },
  1122. { value: "按艺术家降序", fontColor: $r('app.color.text_color') },
  1123. { value: "按专辑升序", fontColor: $r('app.color.text_color') },
  1124. { value: "按专辑降序", fontColor: $r('app.color.text_color') },
  1125. { value: "按名称升序", fontColor: $r('app.color.text_color') },
  1126. { value: "按名称降序", fontColor: $r('app.color.text_color') },
  1127. { value: "按添加时间升序", fontColor: $r('app.color.text_color') },
  1128. { value: "按添加时间降序", fontColor: $r('app.color.text_color') },
  1129. ],
  1130. backgroundColor: $r('app.color.bg_card'),
  1131. transition: AnimationHelper.transitionInDown(555),
  1132. onAction: (index) => {
  1133. this.doSortType(index)
  1134. PreferencesUtil.put(SettingPage.SORT_TYPE, index)
  1135. this.updateListData(this.videoLocalList, true)
  1136. }
  1137. })
  1138. }
  1139. doSortType(index: number) {
  1140. switch (index) {
  1141. case 0:
  1142. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1143. // 类型排序优先级
  1144. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1145. if (typeOrder !== 0) {
  1146. return typeOrder;
  1147. }
  1148. // 处理艺术家可能为undefined的字符串比较
  1149. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1150. const artistB = b.artist?.trim() || '';
  1151. return artistA.localeCompare(artistB);
  1152. });
  1153. break;
  1154. case 1:
  1155. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1156. // 类型排序优先级
  1157. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1158. if (typeOrder !== 0) {
  1159. return typeOrder;
  1160. }
  1161. // 处理艺术家可能为undefined的字符串比较
  1162. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1163. const artistB = b.artist?.trim() || '';
  1164. return artistB.localeCompare(artistA);
  1165. });
  1166. break;
  1167. case 2:
  1168. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1169. // 类型排序优先级
  1170. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1171. if (typeOrder !== 0) {
  1172. return typeOrder;
  1173. }
  1174. // 处理专辑可能为undefined的字符串比较
  1175. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1176. const albumB = b.album?.trim() || '';
  1177. return albumA.localeCompare(albumB);
  1178. });
  1179. break;
  1180. case 3:
  1181. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1182. // 类型排序优先级
  1183. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1184. if (typeOrder !== 0) {
  1185. return typeOrder;
  1186. }
  1187. // 处理专辑可能为undefined的字符串比较
  1188. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1189. const albumB = b.album?.trim() || '';
  1190. return albumB.localeCompare(albumA);
  1191. });
  1192. break;
  1193. case 4:
  1194. Utility.doSortListAscending(this.videoLocalList)
  1195. break;
  1196. case 5:
  1197. Utility.doSortListDescending(this.videoLocalList)
  1198. break;
  1199. case 6:
  1200. this.videoLocalList.sort((a, b) => {
  1201. // First, sort by type
  1202. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1203. if (typeOrder !== 0) {
  1204. return typeOrder;
  1205. }
  1206. // If types are the same, sort by cTime in ascending order
  1207. return a.cTime.localeCompare(b.cTime);
  1208. });
  1209. break;
  1210. case 7:
  1211. this.videoLocalList.sort((a, b) => {
  1212. // First, sort by type
  1213. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1214. if (typeOrder !== 0) {
  1215. return typeOrder;
  1216. }
  1217. // If types are the same, sort by cTime in descending order
  1218. return b.cTime.localeCompare(a.cTime);
  1219. });
  1220. break;
  1221. }
  1222. }
  1223. showSheelDialog() {
  1224. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  1225. // this.showTips()
  1226. // return
  1227. // }
  1228. this.showAddDialog()
  1229. }
  1230. showAddDialog() {
  1231. if (this.modeType === 2 || this.modeType === 3) {
  1232. return
  1233. }
  1234. DialogHelper.showActionSheetDialog({
  1235. title: "请选择添加方式(建议歌词文件一起导入)",
  1236. // sheets: ["新建歌单", "手动导入", "自动导入"],
  1237. sheets: [
  1238. { value: "新建歌单", fontColor: $r('app.color.text_color') },
  1239. { value: "手动导入", fontColor: $r('app.color.text_color') },
  1240. { value: "自动导入", fontColor: $r('app.color.text_color') },
  1241. { value: "全选导入", fontColor: $r('app.color.text_color') },
  1242. ],
  1243. maskColor: Color.Transparent,
  1244. backgroundColor: $r('app.color.bg_card'),
  1245. transition: AnimationHelper.transitionInDown(555),
  1246. onAction: (index) => {
  1247. switch (index) {
  1248. case 0:
  1249. if (this.modeType === 0) {
  1250. this.showMkDialog()
  1251. } else {
  1252. ToastUtil.showToast('请切换到首页才能新建歌单!')
  1253. }
  1254. break;
  1255. case 1:
  1256. this.callFilePickerSelectFile()
  1257. break;
  1258. case 2:
  1259. this.showTips()
  1260. break;
  1261. case 3:
  1262. this.goSelectMusic()
  1263. break;
  1264. }
  1265. }
  1266. })
  1267. }
  1268. //拉起音频
  1269. goSelectMusic() {
  1270. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  1271. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  1272. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  1273. ) {
  1274. ToastUtil.showToast('暂时不支持该设备')
  1275. return
  1276. }
  1277. try {
  1278. let documentSelectOptions = new picker.DocumentSelectOptions();
  1279. documentSelectOptions.authMode = true
  1280. documentSelectOptions.multiAuthMode = true
  1281. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  1282. let documentPicker = new picker.DocumentViewPicker(this.context);
  1283. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  1284. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  1285. this.saveVideoDatas(documentSelectResult)
  1286. }
  1287. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  1288. JSON.stringify(documentSelectResult));
  1289. }).catch((err: BusinessError) => {
  1290. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  1291. });
  1292. } catch (error) {
  1293. let err: BusinessError = error as BusinessError;
  1294. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1295. }
  1296. }
  1297. async showTips() {
  1298. DialogHelper.showTipsDialog({
  1299. title: '使用提示:自动导入教程',
  1300. content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  1301. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  1302. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  1303. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  1304. onAction: (action) => {
  1305. if (action == DialogAction.TWO) {
  1306. PreferencesUtil.putSync('isFirstMusic', false)
  1307. router.pushUrl({
  1308. url: 'pages/ScanFilePage'
  1309. });
  1310. }
  1311. }
  1312. })
  1313. }
  1314. showMkDialog() {
  1315. DialogHelper.showTextInputDialog({
  1316. title: '新建歌单',
  1317. maskColor: Color.Transparent,
  1318. text: '',
  1319. transition: AnimationHelper.transitionInDown(666),
  1320. onChange: (text) => {
  1321. console.error("onChange: " + text);
  1322. },
  1323. onAction: (action, dialogId, content) => {
  1324. // ToastUtil.showToast('content = ' +content)
  1325. if (action == DialogAction.TWO) {
  1326. const newName = content
  1327. const newPath = this.currentPath + '/' + newName
  1328. FileUtil.mkdir(newPath, true).then(() => {
  1329. this.cache.delete(this.currentPath); // 删除目标路径缓存
  1330. this.getSortedFiles(this.currentPath)
  1331. }).catch((error: BusinessError) => {
  1332. console.error(error.message);
  1333. });
  1334. }
  1335. }
  1336. })
  1337. }
  1338. @State progress: number = 0;
  1339. async saveVideoDatas(uris: string[], isOpen?: boolean) {
  1340. if (ArrayUtil.isEmpty(uris)) {
  1341. return;
  1342. }
  1343. let newUris: string[] = [];
  1344. this.progress = 0
  1345. DialogHelper.showLoadingProgress({
  1346. progress: this.progress,
  1347. backCancel: false,
  1348. autoCancel: false,
  1349. loadColor: this.themeColor,
  1350. fontColor: this.themeColor
  1351. });
  1352. // 计算所有文件的总大小
  1353. let totalSize = 0;
  1354. for (let uri of uris) {
  1355. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  1356. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  1357. await fileIo.close(sourceFile.fd);
  1358. }
  1359. let totalRead = 0;
  1360. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  1361. Logger.info(TAG, 'destPath uri: ' + destPath);
  1362. for (let i = 0; i < uris.length; i++) {
  1363. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  1364. Logger.info(TAG, 'filePath uri: ' + filePath);
  1365. newUris.push(filePath);
  1366. try {
  1367. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  1368. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  1369. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  1370. const buffer = new ArrayBuffer(buffSize);
  1371. let len = await fileIo.read(sourceFile.fd, buffer);
  1372. while (len > 0) {
  1373. await fileIo.write(destFile.fd, buffer.slice(0, len));
  1374. totalRead += len;
  1375. // 计算总进度
  1376. this.progress = Math.floor((totalRead / totalSize) * 100);
  1377. DialogHelper.updateLoading('正在导入', this.progress);
  1378. len = await fileIo.read(sourceFile.fd, buffer);
  1379. }
  1380. await fileIo.close(sourceFile.fd);
  1381. await fileIo.close(destFile.fd);
  1382. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  1383. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  1384. let mediaItem: VideoItem =
  1385. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, true);
  1386. this.table.insert(mediaItem, (id: number) => {
  1387. // 删除目标路径缓存
  1388. this.cache.delete(this.currentPath);
  1389. this.getSortedFiles(this.currentPath, true, destPath, isOpen)
  1390. });
  1391. }
  1392. }
  1393. } catch (error) {
  1394. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  1395. }
  1396. }
  1397. DialogHelper.closeLoading()
  1398. this.isZero = false
  1399. // setTimeout(() => {
  1400. // // 删除目标路径缓存
  1401. // this.cache.delete(this.currentPath);
  1402. // this.getSortedFiles(this.currentPath,true,destPath,isOpen)
  1403. // }, 500);
  1404. Logger.info(TAG, 'scan select video result:' + newUris)
  1405. }
  1406. //拉起音频
  1407. // goSelectMusic(){
  1408. //
  1409. // try {
  1410. // let audioSelectOptions = new picker.AudioSelectOptions();
  1411. // let audioPicker = new picker.AudioViewPicker(this.context);
  1412. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  1413. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  1414. // this.saveVideoDatas(audioSelectResult)
  1415. // }
  1416. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  1417. // }).catch((err: BusinessError) => {
  1418. //
  1419. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  1420. // });
  1421. // } catch (error) {
  1422. // let err: BusinessError = error as BusinessError;
  1423. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1424. // }
  1425. //
  1426. //
  1427. //
  1428. // }
  1429. goSelectImage(item: VideoItem) {
  1430. if (!item) {
  1431. return
  1432. }
  1433. let selectUris: Array<string> = [];
  1434. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  1435. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  1436. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; // 过滤选择媒体文件类型为IMAGE
  1437. photoSelectOptions.maxSelectNumber = 1; // 选择媒体文件的最大数目
  1438. photoPicker.select(photoSelectOptions).then(async (photoSelectResult: photoAccessHelper.PhotoSelectResult) => {
  1439. //用一个全局变量存储返回的uri
  1440. selectUris = photoSelectResult.photoUris;
  1441. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  1442. //使用fs.openSync接口,通过uri打开这个文件得到fd
  1443. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  1444. console.info('file fd: ' + file.fd);
  1445. let name = await MD5.digestSync(this.videoUrl)
  1446. let imagePath = this.context.filesDir + FileUtil.separator + name
  1447. imagePath = fileUri.getUriFromPath(imagePath)
  1448. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  1449. fileIo.copyFileSync(file.fd, file2.fd)
  1450. fileIo.closeSync(file);
  1451. fileIo.closeSync(file2);
  1452. if (item.filePath == this.currentSong?.filePath) {
  1453. this.cover = imagePath
  1454. }
  1455. if (item) {
  1456. item.pixelMapPath = imagePath
  1457. }
  1458. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  1459. if (success) {
  1460. this.doUpdateData()
  1461. console.log(" onecold 更新音乐封面成功,数据库已同步");
  1462. } else {
  1463. console.error(" onecold 更新音乐封面数据库失败原因: " + error);
  1464. }
  1465. });
  1466. LogUtil.debug("onecold this.cover =" + this.cover)
  1467. }).catch((err: BusinessError) => {
  1468. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  1469. })
  1470. }
  1471. // 拉起picker选择文件管理器
  1472. async callFilePickerSelectFile(): Promise<void> {
  1473. try {
  1474. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  1475. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  1476. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  1477. } else {
  1478. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  1479. }
  1480. let documentPicker = new picker.DocumentViewPicker();
  1481. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  1482. Logger.info(TAG,
  1483. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  1484. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  1485. this.saveVideoDatas(DocumentSelectResult)
  1486. }
  1487. }).catch((err: BusinessError) => {
  1488. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  1489. });
  1490. } catch (err) {
  1491. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  1492. }
  1493. }
  1494. showWarnIsDeleteFile(item: VideoItem, index: string, filePath: string) {
  1495. //操作确认类弹出框
  1496. DialogHelper.showAlertDialog({
  1497. maskColor: Color.Transparent,
  1498. content: "确定要删除这个文件吗?",
  1499. backgroundColor: Color.Grey,
  1500. transition: AnimationHelper.transitionInUp(555),
  1501. onAction: (action) => {
  1502. if (action == DialogAction.ONE) {
  1503. // ToastUtil.showToast(`您点击了取消按钮`);
  1504. } else if (action == DialogAction.TWO) {
  1505. // ToastUtil.showToast(`您点击了确认按钮`);
  1506. this.doDelete(item, index + '', filePath)
  1507. }
  1508. }
  1509. })
  1510. }
  1511. //删除单个索引index的视频
  1512. doDelete(item: VideoItem, index: string, filePath: string) {
  1513. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1514. Logger.info(TAG, 'delete filePath = ' + filePath);
  1515. if (item.type === CommonConstants.TYPE_IS_DIR) {
  1516. //旧文件删除
  1517. this.table.deleteDataForParentPath(item.filePath, () => {
  1518. FileUtil.rmdir(filePath).then(() => {
  1519. this.videoLocalList.splice(Number(index), 1)
  1520. this.deleteCache(this.currentPath)
  1521. this.getSortedFiles(this.currentPath, true)
  1522. }).catch((error: BusinessError) => {
  1523. console.error(error.message);
  1524. });
  1525. });
  1526. } else {
  1527. this.table.deleteData(item, () => {
  1528. FileUtil.unlink(filePath)
  1529. .catch((error: BusinessError) => {
  1530. console.error(error.message);
  1531. // 可以根据 error.code 判断是否为"文件不存在",如需特殊处理
  1532. })
  1533. .finally(() => {
  1534. this.videoLocalList.splice(Number(index), 1)
  1535. this.deleteCache(this.currentPath)
  1536. this.getSortedFiles(this.currentPath, true)
  1537. });
  1538. });
  1539. }
  1540. }
  1541. }
  1542. //重命名的对话框
  1543. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  1544. DialogHelper.showTextInputDialog({
  1545. title: '重命名',
  1546. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  1547. maskColor: Color.Transparent,
  1548. backgroundColor: Color.Grey,
  1549. transition: AnimationHelper.transitionInDown(666),
  1550. onChange: (text) => {
  1551. console.error("onChange: " + text);
  1552. },
  1553. onAction: (action, dialogId, content) => {
  1554. // ToastUtil.showToast('content = ' +content)
  1555. if (action == DialogAction.TWO) {
  1556. const newName = content
  1557. const newPath = this.currentPath + '/' + newName
  1558. console.log("onecold item = " + item.type);
  1559. this.doReName(index, newName, filePath, newPath, item)
  1560. }
  1561. }
  1562. })
  1563. }
  1564. //剪切 移动到另个文件夹的对话框
  1565. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1566. Logger.info('onecold showCutDialog')
  1567. let mList: Array<string> = []
  1568. let rPath = this.rootPath
  1569. if (isCurrent) {
  1570. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1571. rPath = this.currentPath
  1572. } else {
  1573. mList = Utility.getNameList(this.dirList);
  1574. rPath = this.rootPath
  1575. }
  1576. let dataBean = new BubbleBean()
  1577. dataBean.data = mList
  1578. dataBean.color = this.themeColor
  1579. dataBean.onItemClick = (i) => {
  1580. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1581. Logger.info('newPath = ' + newPath)
  1582. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  1583. ToastUtil.showToast('移动成功')
  1584. this.table.deleteData(item, () => {
  1585. });
  1586. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1587. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1588. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1589. CommonConstants.TYPE_LOCAL, true);
  1590. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1591. this.table.insert(newItem, (id: number) => {
  1592. //加入数据库
  1593. });
  1594. }
  1595. this.cache.delete(this.currentPath); // 删除原路径缓存
  1596. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1597. this.getSortedFiles(this.currentPath, true)
  1598. }).catch((error: BusinessError) => {
  1599. console.error(error.message);
  1600. });
  1601. XPopup.dismissTop()
  1602. }
  1603. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1604. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1605. popupPosition = PopupPosition.TOP
  1606. }
  1607. if (index <= 3) {
  1608. popupPosition = PopupPosition.BOTTOM
  1609. }
  1610. let pup: XPopup
  1611. if (this.isDarkMode) {
  1612. pup = XPopup.Builder()
  1613. .setPopupPosition(popupPosition)
  1614. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  1615. .setBackgroundColor(Color.Black)
  1616. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1617. .show()
  1618. } else {
  1619. pup = XPopup.Builder()
  1620. .setPopupPosition(popupPosition)
  1621. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  1622. .setBackgroundColor(Color.White)
  1623. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1624. .show()
  1625. }
  1626. }
  1627. //复制 到另个文件夹的对话框
  1628. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1629. Logger.info('onecoldv showCopyDialog')
  1630. let mList: Array<string> = []
  1631. let rPath = this.rootPath
  1632. if (isCurrent) {
  1633. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1634. rPath = this.currentPath
  1635. } else {
  1636. mList = Utility.getNameList(this.dirList);
  1637. rPath = this.rootPath
  1638. }
  1639. let dataBean = new BubbleBean()
  1640. dataBean.data = mList
  1641. dataBean.isCopy = true
  1642. dataBean.color = this.themeColor
  1643. dataBean.onItemClick = (i) => {
  1644. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1645. Logger.info('newPath = ' + newPath)
  1646. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  1647. ToastUtil.showToast('复制成功')
  1648. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1649. this.getSortedFiles(this.currentPath)
  1650. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1651. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1652. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1653. CommonConstants.TYPE_LOCAL, true);
  1654. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1655. this.table.insert(newItem, (id: number) => {
  1656. //加入数据库
  1657. });
  1658. }
  1659. }).catch((error: BusinessError) => {
  1660. console.error(error.message);
  1661. });
  1662. XPopup.dismissTop()
  1663. }
  1664. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1665. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1666. popupPosition = PopupPosition.TOP
  1667. }
  1668. if (index <= 3) {
  1669. popupPosition = PopupPosition.BOTTOM
  1670. }
  1671. let pup: XPopup
  1672. if (this.isDarkMode) {
  1673. pup = XPopup.Builder()
  1674. .setPopupPosition(popupPosition)
  1675. .atView(id)
  1676. .setMaxHeight('60%')
  1677. .setBackgroundColor(Color.Black)
  1678. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1679. .show();
  1680. } else {
  1681. pup = XPopup.Builder()
  1682. .setPopupPosition(popupPosition)
  1683. .atView(id)
  1684. .setMaxHeight('60%')
  1685. .setBackgroundColor(Color.White)
  1686. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1687. .show();
  1688. }
  1689. }
  1690. //重命名索引index的视频
  1691. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  1692. FileUtil.rename(oldPath, newPath).then(async () => {
  1693. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1694. if (info.type === CommonConstants.TYPE_IS_DIR) {
  1695. //如果是文件夹先删除源数据,再添加新数据
  1696. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  1697. if (success) {
  1698. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  1699. } else {
  1700. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  1701. }
  1702. });
  1703. this.scanDirectory(newPath)
  1704. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  1705. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  1706. if (success) {
  1707. console.log(" onecold 重命名成功,数据库已同步");
  1708. } else {
  1709. console.error(" onecold 重命名数据库失败原因: " + error);
  1710. }
  1711. });
  1712. }
  1713. let mediaItem: VideoItem =
  1714. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, true);
  1715. this.videoLocalList[index] = mediaItem;
  1716. }
  1717. this.cache.delete(this.currentPath)
  1718. this.getSortedFiles(this.currentPath, true)
  1719. }).catch((error: BusinessError) => {
  1720. console.error(error.message);
  1721. });
  1722. }
  1723. build() {
  1724. Scroll() {
  1725. Column() {
  1726. if (!this.isShowCoverHeader()) {
  1727. Column() {
  1728. Line().width('100%').height('100%')
  1729. }
  1730. .height(this.topRectHeight)
  1731. .backgroundColor(this.isCustomizeBg ? Color.Transparent :
  1732. (this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor))
  1733. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  1734. TitleBar({ model: $titleBarModel })
  1735. .id('pup_positon_music')
  1736. }
  1737. Stack() {
  1738. Column() {
  1739. XComponent({
  1740. id: 'xcomponentId',
  1741. type: 'surface',
  1742. libraryname: 'ijkplayer_napi',
  1743. controller: this.xcomponentController
  1744. })
  1745. .onLoad((event?: object) => {
  1746. if (!!event) {
  1747. this.initDelayPlay(event);
  1748. }
  1749. })
  1750. .onKeyEvent((event?: KeyEvent) => {
  1751. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  1752. if (!event || event.type !== KeyType.Down) {
  1753. return;
  1754. }
  1755. //空格键 Space key controls pause/play
  1756. if (event.keyCode === KeyCode.KEYCODE_SPACE) {
  1757. this.playOrPause()
  1758. }
  1759. // Right-click to fast forward
  1760. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  1761. this.sessionFastForwardCallback(15);
  1762. }
  1763. // Left-click to rewind
  1764. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  1765. this.sessionRewindCallback(15);
  1766. }
  1767. })
  1768. .onDestroy(() => {
  1769. })
  1770. .width('100%')// .width(this.videoWidth)
  1771. .aspectRatio(this.videoAspectRatio)
  1772. }
  1773. .aspectRatio(this.videoAspectRatio)
  1774. .justifyContent(FlexAlign.Center)
  1775. .backgroundColor(Color.Transparent)
  1776. .visibility(Visibility.Hidden)
  1777. .height(CommonConstants.FULL_PERCENT)
  1778. .width(CommonConstants.FULL_PERCENT)
  1779. Stack() {
  1780. Row() {
  1781. Blank()
  1782. .layoutWeight(1)
  1783. IndexerView(
  1784. {
  1785. indexArray: DEFAULT_INDEX,
  1786. selectedIndex: this.selectedIndex,
  1787. textSize: 12,
  1788. selectedColor: "#ff419ee5",
  1789. normalColor: "#ffa0a0a0",
  1790. floatSelectedTextColor: "#ffffff",
  1791. floatSelectedViewColor: "#ff419ee5",
  1792. onIndexChanged: (index) => {
  1793. this.listScroller.scrollToIndex(index)
  1794. }
  1795. })
  1796. .width(24)
  1797. .height("50%")
  1798. }.visibility(Visibility.None)
  1799. Column() {
  1800. if (!this.isShowCoverHeader()) {
  1801. this.tabTitle()
  1802. }
  1803. if (this.isGridMusic) {
  1804. this.getGridView()
  1805. } else {
  1806. this.getListView()
  1807. }
  1808. if (this.modeType == 0) {
  1809. Column() {
  1810. Button('同步数据', { type: ButtonType.Capsule, stateEffect: true })
  1811. .width(130)
  1812. .height(50)
  1813. .margin({ top: 100, bottom: 40 })
  1814. .backgroundColor(this.themeColor)
  1815. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  1816. .onClick(() => {
  1817. this.asyncCurrentPathData()
  1818. })
  1819. }
  1820. .height(100)
  1821. .position({ top: 260 })
  1822. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  1823. .animation({ duration: 500 }),
  1824. TransitionEffect.scale({ x: 0, y: 0 })))
  1825. .justifyContent(FlexAlign.Center)
  1826. .opacity(this.isZero ? 1 : 0)
  1827. .visibility(this.isZero && !this.isFavMusic && !this.isHistory
  1828. && this.modeType === 0 ? Visibility.Visible : Visibility.None)
  1829. .animation({
  1830. duration: 500,
  1831. curve: 'ease-in-out' // 可选动画曲线
  1832. })
  1833. .width('100%')
  1834. }
  1835. }
  1836. .layoutWeight(1)
  1837. .height('100%')
  1838. }
  1839. .layoutWeight(1)
  1840. .height('100%')
  1841. Row() {
  1842. Button(this.isAllSelected ? '全不选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  1843. .width('35%')
  1844. .height(60)
  1845. .margin({ top: 10, bottom: 10, right: 6 })
  1846. .backgroundColor(this.themeColor)
  1847. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1848. .onClick(() => {
  1849. if (this.isAllSelected) {
  1850. // 全不选
  1851. this.selectedFiles = [];
  1852. } else {
  1853. // 全选
  1854. this.selectedFiles = [...this.getCurFileList()];
  1855. }
  1856. this.isAllSelected = !this.isAllSelected;
  1857. })
  1858. Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  1859. .width('35%')
  1860. .height(60)
  1861. .id('music_cut')
  1862. .margin({ top: 10, bottom: 10, right: 6 })
  1863. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1864. .backgroundColor(this.themeColor)
  1865. .onClick(() => {
  1866. this.showCutDialogForMultipleFiles(false, 'music_cut')
  1867. })
  1868. Button('移动', { type: ButtonType.Circle, stateEffect: true })
  1869. .width('35%')
  1870. .height(60)
  1871. .id('music_cut_current')
  1872. .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  1873. .margin({ top: 10, bottom: 10, right: 6 })
  1874. .backgroundColor(this.themeColor)
  1875. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1876. .onClick(() => {
  1877. this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  1878. })
  1879. Button('复制', { type: ButtonType.Circle, stateEffect: true })
  1880. .width('35%')
  1881. .height(60)
  1882. .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  1883. .margin({ top: 10, bottom: 10, right: 6 })
  1884. .backgroundColor(this.themeColor)
  1885. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1886. .onClick(() => {
  1887. this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  1888. })
  1889. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  1890. .width('35%')
  1891. .height(60)
  1892. .margin({ top: 10, bottom: 10, right: 6 })
  1893. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  1894. .backgroundColor(this.themeColor)
  1895. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1896. .onClick(() => {
  1897. this.showWarnIsDelete()
  1898. })
  1899. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  1900. .width('35%')
  1901. .height(60)
  1902. .margin({ top: 10, bottom: 10, right: 6 })
  1903. .backgroundColor(this.themeColor)
  1904. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1905. .onClick(() => {
  1906. this.selectedFiles = [];
  1907. this.isAllSelected = false
  1908. this.isMultiSelect = false
  1909. })
  1910. }
  1911. .width('100%')
  1912. .justifyContent(FlexAlign.Center)
  1913. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  1914. .opacity(this.isMultiSelect ? 1 : 0)
  1915. .animation({
  1916. duration: 666,
  1917. curve: 'ease-in-out' // 可选动画曲线
  1918. })
  1919. .position(this.isShowCoverHeader() ? { bottom: 78 }
  1920. : { bottom: this.isPhoneLan() ? 130 : 168 }) // 将 Row 固定在底部
  1921. }
  1922. .width('100%')
  1923. .height('100%')
  1924. .alignContent(Alignment.Top)
  1925. Column() {
  1926. this.PlayController()
  1927. }
  1928. .hitTestBehavior(HitTestMode.Transparent)
  1929. .position({ bottom: 0 }) // 将 Row 固定在底部
  1930. .opacity(this.barBottomOpacity)
  1931. }
  1932. .width('100%')
  1933. .height('100%')
  1934. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  1935. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  1936. .backgroundImagePosition(Alignment.Center)
  1937. .backdropBlur(this.blurValue)
  1938. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  1939. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  1940. }
  1941. }
  1942. asyncCurrentPathData() {
  1943. if (this.modeType == 0) {
  1944. workerInstance.postMessage({
  1945. code: 1,
  1946. data1: this.context,
  1947. data2: this.currentPath,
  1948. data3: this.lockPath,
  1949. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  1950. });
  1951. }
  1952. }
  1953. // 处理文件选择的函数
  1954. handleFileSelection(item: VideoItem, checked: boolean) {
  1955. if (checked) {
  1956. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  1957. this.selectedFiles.push(item);
  1958. }
  1959. } else {
  1960. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  1961. if (index > -1) {
  1962. this.selectedFiles.splice(index, 1);
  1963. }
  1964. }
  1965. }
  1966. showWarnIsDelete() {
  1967. //操作确认类弹出框
  1968. DialogHelper.showAlertDialog({
  1969. content: "确定要删除这些文件吗?",
  1970. transition: AnimationHelper.transitionInUp(666),
  1971. maskColor: Color.Transparent,
  1972. backgroundColor: Color.Grey,
  1973. onAction: (action) => {
  1974. if (action == DialogAction.ONE) {
  1975. // ToastUtil.showToast(`您点击了取消按钮`);
  1976. } else if (action == DialogAction.TWO) {
  1977. // ToastUtil.showToast(`您点击了确认按钮`);
  1978. this.deleteMultipleFiles()
  1979. }
  1980. }
  1981. })
  1982. }
  1983. //多选删除文件
  1984. deleteMultipleFiles() {
  1985. if (ArrayUtil.isNotEmpty(this.selectedFiles)) {
  1986. this.selectedFiles.forEach((item) => {
  1987. Logger.info(TAG, 'delete filePath = ' + item.filePath);
  1988. if (item.type === CommonConstants.TYPE_IS_DIR) {
  1989. this.table.deleteDataForParentPath(item.filePath, () => {
  1990. FileUtil.rmdir(item.filePath).then(() => {
  1991. this.videoLocalList = this.videoLocalList.filter(v => v !== item);
  1992. this.selectedFiles = [];
  1993. this.isMultiSelect = false
  1994. this.isAllSelected = false
  1995. this.cache.delete(this.currentPath);
  1996. this.getSortedFiles(this.currentPath, true);
  1997. }).catch((error: Error) => {
  1998. console.error(error.message);
  1999. });
  2000. });
  2001. } else {
  2002. this.table.deleteData(item, () => {
  2003. FileUtil.unlink(item.filePath).catch((error: Error) => {
  2004. console.error(error.message);
  2005. }).finally(() => {
  2006. this.videoLocalList = this.videoLocalList.filter(v => v !== item);
  2007. this.selectedFiles = [];
  2008. this.isMultiSelect = false
  2009. this.isAllSelected = false
  2010. this.cache.delete(this.currentPath);
  2011. this.getSortedFiles(this.currentPath, true);
  2012. });
  2013. });
  2014. }
  2015. });
  2016. }
  2017. }
  2018. //多选移动文件
  2019. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  2020. Logger.info('onecold showCutDialogForMultipleFiles')
  2021. let mList: Array<string> = []
  2022. let rPath = this.rootPath
  2023. if (isCurrent) {
  2024. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2025. rPath = this.currentPath
  2026. } else {
  2027. mList = Utility.getNameList(this.dirList);
  2028. rPath = this.rootPath
  2029. }
  2030. let dataBean = new BubbleBean();
  2031. dataBean.data = mList;
  2032. dataBean.color = this.themeColor
  2033. dataBean.onItemClick = (i) => {
  2034. const newDirPath = rPath + '/' + mList[i];
  2035. // Logger.info('newDirPath = ' + newDirPath)
  2036. this.selectedFiles.forEach((item) => {
  2037. const newPath = newDirPath + '/' + item.fileName;
  2038. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  2039. ToastUtil.showToast('移动成功');
  2040. this.table.deleteData(item, () => {
  2041. this.cache.delete(this.currentPath); // 删除原路径缓存
  2042. this.cache.delete(newDirPath); // 删除目标路径缓存
  2043. this.getSortedFiles(this.currentPath, true);
  2044. });
  2045. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2046. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2047. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2048. CommonConstants.TYPE_LOCAL, true);
  2049. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2050. this.table.insert(newItem, (id: number) => {
  2051. //加入数据库
  2052. });
  2053. }
  2054. }).catch((error: Error) => {
  2055. console.error(error.message);
  2056. });
  2057. });
  2058. this.isMultiSelect = false
  2059. this.selectedFiles = [];
  2060. this.isAllSelected = false
  2061. XPopup.dismissTop();
  2062. };
  2063. let pup: XPopup
  2064. if (this.isDarkMode) {
  2065. pup = XPopup.Builder()
  2066. .setPopupPosition(PopupPosition.TOP)
  2067. .atView(viewId)
  2068. .setBackgroundColor(Color.Black)
  2069. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2070. .show();
  2071. } else {
  2072. pup = XPopup.Builder()
  2073. .setPopupPosition(PopupPosition.TOP)
  2074. .atView(viewId)
  2075. .setBackgroundColor(Color.White)
  2076. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2077. .show();
  2078. }
  2079. }
  2080. doFav(item: VideoItem) {
  2081. LogUtil.info('onecold doFav isFav=' + item.isFav)
  2082. let isFav = 0
  2083. if (Utility.getIsFav(this.favList, item)) {
  2084. isFav = 0
  2085. } else {
  2086. isFav = 1
  2087. }
  2088. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  2089. if (result) {
  2090. if (isFav === 1) {
  2091. ToastUtil.showToast('收藏成功');
  2092. } else {
  2093. ToastUtil.showToast('取消收藏成功');
  2094. }
  2095. this.deleteCache(this.currentPath)
  2096. this.getFavList(false)
  2097. if (this.modeType === 0 && !this.isFavMusic) {
  2098. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  2099. this.getSortedFiles(this.currentPath)
  2100. }
  2101. workerInstance.postMessage({ code: 2, data: this.context });
  2102. workerInstance.postMessage({ code: 3, data: this.context });
  2103. workerInstance.postMessage({ code: 4, data: this.context });
  2104. }
  2105. })
  2106. }
  2107. //多选复制文件
  2108. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  2109. console.log('onecold showCopyDialogForMultipleFiles');
  2110. let mList: Array<string> = []
  2111. let rPath = this.rootPath
  2112. if (isCurrent) {
  2113. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2114. rPath = this.currentPath
  2115. } else {
  2116. mList = Utility.getNameList(this.dirList);
  2117. rPath = this.rootPath
  2118. }
  2119. let dataBean = new BubbleBean();
  2120. dataBean.data = mList;
  2121. dataBean.isCopy = true
  2122. dataBean.color = this.themeColor
  2123. dataBean.onItemClick = (i) => {
  2124. const newDirPath = rPath + '/' + mList[i];
  2125. // Logger.info('newDirPath = ' + newDirPath)
  2126. this.selectedFiles.forEach((item) => {
  2127. const newPath = newDirPath + '/' + item.fileName;
  2128. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2129. ToastUtil.showToast('复制成功');
  2130. this.cache.delete(newDirPath); // 删除目标路径缓存
  2131. this.getSortedFiles(this.currentPath);
  2132. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2133. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2134. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2135. CommonConstants.TYPE_LOCAL, true);
  2136. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2137. this.table.insert(newItem, (id: number) => {
  2138. //加入数据库
  2139. });
  2140. }
  2141. }).catch((error: Error) => {
  2142. console.error(error.message);
  2143. });
  2144. });
  2145. this.isMultiSelect = false
  2146. this.selectedFiles = [];
  2147. this.isAllSelected = false
  2148. XPopup.dismissTop();
  2149. };
  2150. let pup: XPopup
  2151. if (this.isDarkMode) {
  2152. pup = XPopup.Builder()
  2153. .setPopupPosition(PopupPosition.TOP)
  2154. .atView(viewId)
  2155. .setBackgroundColor(Color.Black)
  2156. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2157. .show();
  2158. } else {
  2159. pup = XPopup.Builder()
  2160. .setPopupPosition(PopupPosition.TOP)
  2161. .atView(viewId)
  2162. .setBackgroundColor(Color.White)
  2163. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2164. .show();
  2165. }
  2166. }
  2167. @Builder
  2168. private DirItem(item: VideoItem, index?: number) {
  2169. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2170. Row() {
  2171. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  2172. $r('app.media.music_group'))
  2173. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2174. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2175. .fillColor(this.themeColor)// .fontSize(33)
  2176. .alt($r('app.media.music_group'))
  2177. .borderRadius('100%')
  2178. .clip(true)
  2179. .margin({ left: 20, top: 8, bottom: 8 })
  2180. Column() {
  2181. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  2182. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2183. .maxLines(1)// .width('88%')
  2184. .animation({
  2185. duration: 555,
  2186. curve: 'ease-in-out',
  2187. })
  2188. .transition({
  2189. type: TransitionType.Insert,
  2190. opacity: 0,
  2191. translate: { x: 160 }
  2192. })
  2193. .margin({ left: 10, right: 20 })
  2194. .fontColor($r('app.color.text_color'))
  2195. Row() {
  2196. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  2197. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2198. .padding({ top: 8 })
  2199. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  2200. .fontColor($r('app.color.text_color'))
  2201. .margin({ left: 10 })
  2202. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  2203. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2204. .padding({ top: 8 })
  2205. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2206. .fontColor($r('app.color.text_color'))
  2207. .margin({ left: 10 })
  2208. Blank()
  2209. }
  2210. }
  2211. .height('100%')
  2212. .layoutWeight(1)
  2213. .justifyContent(FlexAlign.Center)
  2214. .alignItems(HorizontalAlign.Start)
  2215. Blank()
  2216. Image($r('app.media.arrow_right'))
  2217. .height(25)
  2218. .margin({ right: 10 })
  2219. .alignSelf(ItemAlign.Center)
  2220. .id(item.filePath)
  2221. }
  2222. }
  2223. .backgroundColor(Color.Transparent)
  2224. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2225. .width('100%')
  2226. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  2227. .opacity(this.opacityItem) // 绑定透明度
  2228. }
  2229. isShowDir(dirName: string) {
  2230. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  2231. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  2232. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  2233. if (dirName === undefined) {
  2234. return true
  2235. }
  2236. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  2237. return this.isShowSimi
  2238. }
  2239. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  2240. return this.isShowFAV
  2241. }
  2242. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  2243. return this.isShowHistory
  2244. }
  2245. return true
  2246. }
  2247. @State opacityItem: number = 1; // 控制透明度的状态变量
  2248. @Builder
  2249. private MusicItem(item: VideoItem, index?: number) {
  2250. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2251. Row() {
  2252. Stack() {
  2253. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  2254. .fillColor(this.themeColor)
  2255. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2256. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2257. .alt($r('app.media.music_red'))
  2258. .borderRadius('100%')
  2259. .clip(true)
  2260. .opacity(this.opacityItem)// 绑定透明度
  2261. .margin({ left: 20 })
  2262. }
  2263. Column() {
  2264. Column() {
  2265. Text(item.name)
  2266. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2267. .maxLines(1)
  2268. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  2269. .animation({
  2270. duration: 555,
  2271. curve: 'Linear',
  2272. })
  2273. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2274. $r('app.color.text_color'))
  2275. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2276. .bindPopup(this.longItemFilePath === item.filePath, {
  2277. builder: this.MenuBuilder(item,index,item.filePath),
  2278. placement: Placement.Top,
  2279. // autoCancel: true,
  2280. mask: {color:'#33000000'},
  2281. // popupColor: Color.Yellow,
  2282. enableArrow: false,//是否显示箭头
  2283. showInSubWindow: false,
  2284. onStateChange: (e) => {
  2285. if (!e.isVisible) {
  2286. this.longItemFilePath = ''
  2287. this.tempLyricContent = ''
  2288. }
  2289. }
  2290. })
  2291. .gesture(LongPressGesture()
  2292. .onAction(async () => {
  2293. //如果是专辑和艺术家的首页,不能长按
  2294. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2295. return
  2296. //如果是我的收藏 最近播放等也不能长按
  2297. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2298. item.name === LocalMusic.STR_HISTORY_MUSIC
  2299. )
  2300. return
  2301. this.longItemFilePath = item.filePath
  2302. this.tempLyricContent = await this.getLyricContent(item)
  2303. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2304. })
  2305. .onActionEnd((event: GestureEvent) => {
  2306. })
  2307. )
  2308. Row() {
  2309. Column(){
  2310. Text(item.md5Str?.includes('Lossless')?
  2311. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  2312. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  2313. .padding({ top: 3,right:6,left:6,bottom:3 })
  2314. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2315. $r('app.color.text_color'))
  2316. .fontWeight(500)
  2317. .borderRadius(12)
  2318. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2319. .backgroundColor('#FFC107')
  2320. }
  2321. .padding({ top: 8 })
  2322. Text(StrUtil.isEmpty(item.artist) ? item.cTime : item.artist + ' ' + item?.album)
  2323. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2324. .padding({ top: 8 })
  2325. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2326. $r('app.color.text_color'))
  2327. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2328. Blank()
  2329. Text(item.size)
  2330. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2331. .padding({ top: 8 })
  2332. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  2333. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2334. $r('app.color.text_color'))
  2335. .margin({ left: 10 })
  2336. }
  2337. .gesture(LongPressGesture()
  2338. .onAction(async () => {
  2339. //如果是专辑和艺术家的首页,不能长按
  2340. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2341. return
  2342. //如果是我的收藏 最近播放等也不能长按
  2343. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2344. item.name === LocalMusic.STR_HISTORY_MUSIC
  2345. )
  2346. return
  2347. this.longItemFilePath = item.filePath
  2348. this.tempLyricContent = await this.getLyricContent(item)
  2349. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2350. })
  2351. .onActionEnd((event: GestureEvent) => {
  2352. })
  2353. )
  2354. }
  2355. .height('100%')
  2356. .width('100%')
  2357. .justifyContent(FlexAlign.Center)
  2358. .alignItems(HorizontalAlign.Start)
  2359. }
  2360. .height('100%')
  2361. .margin({ left: 5 })
  2362. .layoutWeight(1)
  2363. Column() {
  2364. Checkbox({ name: 'checkbox' + index })
  2365. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  2366. .selectedColor(this.themeColor)
  2367. .shape(CheckBoxShape.CIRCLE)
  2368. .opacity(this.isMultiSelect ? 1 : 0)
  2369. .animation({
  2370. duration: 666,
  2371. curve: 'Smooth' // 可选动画曲线
  2372. })
  2373. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2374. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  2375. .margin({ left: 20, top: 8, bottom: 8 })
  2376. .width(22)
  2377. .height(22)
  2378. ImageAnimator()
  2379. .images(this.imagesF)// 动画数组
  2380. .duration(1000)// 持续
  2381. .state(this.animationState)// 动画状态
  2382. .fillMode(FillMode.Forwards)
  2383. .width(18)
  2384. .margin({ right: 20, top: 8, bottom: 8 })
  2385. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  2386. Visibility.None)
  2387. .height(18)
  2388. .iterations(-1) // 播放次数
  2389. }
  2390. }
  2391. }
  2392. .backgroundColor(Color.Transparent)
  2393. .width('100%')
  2394. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2395. }
  2396. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  2397. @Builder
  2398. tabTitle() {
  2399. Column() {
  2400. // 使用 Stack 布局来实现绝对定位效果
  2401. Stack() {
  2402. // 背景动画容器
  2403. Row() {
  2404. ForEach(this.tabs, (i: string, index) => {
  2405. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2406. Flex()
  2407. .backgroundColor(this.isDarkMode ? $r('app.color.tab_item_bg') : this.themeColor)
  2408. .borderRadius(20)
  2409. .padding(10)
  2410. .margin(6)
  2411. .width('100%')
  2412. .height('100%')
  2413. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2414. .visibility(this.modeType === index ? Visibility.Visible : Visibility.None)
  2415. .opacity(this.modeType === index ? 1 : 0)
  2416. .animation({
  2417. duration: 666,
  2418. playMode: PlayMode.Normal,
  2419. curve: 'ease-in-out'
  2420. });
  2421. }
  2422. .layoutWeight(1)
  2423. .margin({
  2424. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5,
  2425. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5, bottom: 1
  2426. });
  2427. });
  2428. }
  2429. .width('100%')
  2430. .height(50);
  2431. // 导航栏容器
  2432. Row() {
  2433. ForEach(this.tabs, (item: string, index) => {
  2434. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2435. Text(item)
  2436. .fontSize(16)
  2437. .fontColor(this.modeType === index ? Color.White : $r('app.color.text_color'))
  2438. .padding(15)
  2439. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2440. .onClick(() => {
  2441. this.modeType = index;
  2442. this.onModeChange();
  2443. });
  2444. }
  2445. .layoutWeight(1)
  2446. .stateStyles({
  2447. pressed: { opacity: 0.6 } // 按压反馈
  2448. });
  2449. });
  2450. }
  2451. .width('100%')
  2452. .height(this.topBarHeight)
  2453. .opacity(this.barOpacity)
  2454. .backgroundColor(Color.Transparent);
  2455. }
  2456. .width('100%')
  2457. .height(this.topBarHeight)
  2458. .opacity(this.barOpacity)
  2459. Line()
  2460. .width('100%')
  2461. .height(1)
  2462. .backgroundColor($r('app.color.index_background'))
  2463. .opacity(this.barOpacity)
  2464. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  2465. }
  2466. .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  2467. }
  2468. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  2469. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  2470. isShowCoverHeader() {
  2471. if (!this.isShowHeader) {
  2472. return false
  2473. }
  2474. if (this.modeType == 0) {
  2475. if (this.isHistory || this.isFavMusic) {
  2476. return true
  2477. }
  2478. if (this.currentPath != this.rootPath) {
  2479. return true
  2480. }
  2481. }
  2482. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  2483. }
  2484. @Builder
  2485. coverHeader() {
  2486. if (this.isShowCoverHeader()) {
  2487. Column() {
  2488. Stack() {
  2489. // 居中标题
  2490. Text('')
  2491. .fontSize(18)
  2492. .fontColor(Color.White)
  2493. .align(Alignment.Center)
  2494. // 左右按钮
  2495. Row() {
  2496. Image($r('app.media.left_back_white'))
  2497. .width(28)
  2498. .height(28)
  2499. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2500. .margin({ left: 12, right: 8 })
  2501. .onClick(() => {
  2502. animateTo({ duration: 555 }, () => {
  2503. this.doSwipBack()
  2504. })
  2505. })
  2506. Blank().flexGrow(1)
  2507. if (this.modeType == 0 && !this.isHistory && !this.isFavMusic) {
  2508. Image($r('app.media.add'))
  2509. .width(25)
  2510. .height(25)
  2511. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2512. .margin({ left: 8, right: 15 })
  2513. .onClick(() => {
  2514. this.showAddDialog()
  2515. })
  2516. }
  2517. }
  2518. .height(48)
  2519. .width('100%')
  2520. .alignItems(VerticalAlign.Center)
  2521. }
  2522. .height(48)
  2523. .width('100%')
  2524. Row() {
  2525. Column() {
  2526. Image(this.currentTitleCover)
  2527. .height(100)
  2528. .width(100)
  2529. .alt(this.imageLabel)
  2530. .borderRadius(8)
  2531. .clickEffect({ level: ClickEffectLevel.HEAVY })
  2532. }
  2533. .alignItems(HorizontalAlign.Start)
  2534. .margin({ left: 30, top: 3, bottom: 15 })
  2535. Column() {
  2536. Column() {
  2537. Text(this.currentTitleName)
  2538. .fontSize(16)
  2539. .maxLines(1)
  2540. .fontWeight(FontWeight.Bold)
  2541. .fontColor($r('app.color.text_color'))
  2542. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2543. if (this.modeType == 3 && ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2544. Text(`艺术家:${this.videoLocalList[0].artist}`)
  2545. .fontSize(14)
  2546. .padding({ top: 8 })
  2547. .maxLines(1)
  2548. .fontWeight(FontWeight.Bold)
  2549. .fontColor($r('app.color.text_color'))
  2550. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2551. if(this.videoLocalList[0].genre){
  2552. Text(`风格:${this.videoLocalList[0].genre}`)
  2553. .fontSize(14)
  2554. .padding({ top: 8 })
  2555. .maxLines(1)
  2556. .visibility(StrUtil.isEmpty(this.videoLocalList[0].genre)||
  2557. this.videoLocalList[0].genre.includes(this.UNKONWN)
  2558. ?Visibility.None:Visibility.Visible)
  2559. .fontWeight(FontWeight.Bold)
  2560. .fontColor($r('app.color.text_color'))
  2561. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2562. }
  2563. if(this.videoLocalList[0].year){
  2564. Text(`发行时间:${this.videoLocalList[0].year}`)
  2565. .fontSize(14)
  2566. .padding({ top: 8 })
  2567. .maxLines(1)
  2568. .visibility(StrUtil.isEmpty(this.videoLocalList[0].year)||
  2569. this.videoLocalList[0].year.includes(this.UNKONWN)
  2570. ?Visibility.None:Visibility.Visible)
  2571. .fontWeight(FontWeight.Bold)
  2572. .fontColor($r('app.color.text_color'))
  2573. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2574. }
  2575. }
  2576. if(this.modeType != 3){
  2577. Row() {
  2578. Text(`共${this.videoLocalList.length}首歌`)
  2579. .fontSize(13)
  2580. .fontWeight(FontWeight.Bold)
  2581. .padding({ top: 8 })
  2582. .fontColor($r('app.color.text_color'))
  2583. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2584. Blank()
  2585. }
  2586. }
  2587. }
  2588. .height('100%')
  2589. .width('100%')
  2590. .justifyContent(FlexAlign.Center)
  2591. .alignItems(HorizontalAlign.Start)
  2592. }
  2593. .height('100%')
  2594. .layoutWeight(1)
  2595. .margin({ left: 20 })
  2596. }
  2597. this.listViewTitle()
  2598. }
  2599. .backgroundImage(this.getCoverTitleBg())
  2600. .height(250)
  2601. .width('100%')
  2602. .backgroundImageSize({ height: '100%', width: '100%' })
  2603. .backgroundBlurStyle(this.isCustomizeBg ? BlurStyle.NONE : BlurStyle.BACKGROUND_ULTRA_THICK)
  2604. .padding({ top: this.topRectHeight, bottom: this.bottomBarHeight + 48 })
  2605. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  2606. .justifyContent(FlexAlign.SpaceBetween)
  2607. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.7, y: 0.7 }).animation({ duration: 500 }),
  2608. TransitionEffect.scale({ x: 0, y: 0 })))
  2609. } else {
  2610. this.listViewTitle()
  2611. }
  2612. }
  2613. getCoverTitleBg(): ResourceStr | image.PixelMap {
  2614. if (this.isCustomizeBg) {
  2615. return ('rgba(255,255,255,0.2)')
  2616. }
  2617. if (this.isDarkMode) {
  2618. return $r('app.color.user_center_card_background')
  2619. }
  2620. return this.currentTitleCover
  2621. }
  2622. @Builder
  2623. listViewTitle() {
  2624. Column() {
  2625. Row({ space: 8 }) {
  2626. Row({ space: 8 }) {
  2627. Image($r("app.media.hm_playlist"))
  2628. .width(25)
  2629. .margin({ left: 8 })
  2630. .fillColor(this.themeColor)
  2631. Text(`共找到${this.artistList.length}位艺术家`)
  2632. .fontColor($r('app.color.text_color'))
  2633. .fontSize(14)
  2634. .opacity(this.opacityItem)
  2635. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  2636. Text(`共找到${this.albumList.length}张专辑`)
  2637. .fontColor($r('app.color.text_color'))
  2638. .opacity(this.opacityItem)
  2639. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2640. .fontSize(14)
  2641. }
  2642. .layoutWeight(1)
  2643. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  2644. Row() {
  2645. TextInput({
  2646. placeholder: this.modeType === 2 ? '输入艺术家名称...' : '输入专辑名称...',
  2647. text: this.searchText
  2648. })
  2649. .height(35)
  2650. .onChange((value: string) => {
  2651. this.onSearchInput(value);
  2652. })
  2653. .layoutWeight(1)
  2654. Text(`取消`)
  2655. .margin({ left: 10, right: 10 })
  2656. .fontColor($r('app.color.text_color'))
  2657. .fontSize(16)
  2658. .onClick(() => {
  2659. this.isSearchMode = false
  2660. this.searchText = ''
  2661. if (this.modeType === 2) {
  2662. this.updateListData(this.artistList)
  2663. } else {
  2664. this.updateListData(this.albumList)
  2665. }
  2666. })
  2667. }
  2668. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  2669. .animation({
  2670. duration: 666,
  2671. curve: 'ease-in-out' // 可选动画曲线
  2672. })
  2673. Blank()
  2674. Image($r("app.media.search"))
  2675. .width(25)
  2676. .visibility(this.modeType === 2 || this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2677. .animation({
  2678. duration: 666,
  2679. curve: 'ease-in-out' // 可选动画曲线
  2680. })// .opacity(this.opacityItem)
  2681. .fillColor(this.themeColor)
  2682. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2683. .onClick(() => {
  2684. this.isSearchMode = true
  2685. })
  2686. Image($r("app.media.top_rank"))
  2687. .width(25)// .opacity(this.opacityItem)
  2688. .fillColor(this.themeColor)
  2689. .animation({
  2690. duration: 666,
  2691. curve: 'ease-in-out' // 可选动画曲线
  2692. })
  2693. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2694. .onClick(() => {
  2695. this.showRankDialog()
  2696. })
  2697. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  2698. .width(25)
  2699. .animation({
  2700. duration: 666,
  2701. curve: 'ease-in-out' // 可选动画曲线
  2702. })
  2703. .fillColor(this.themeColor)
  2704. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2705. .onClick(() => {
  2706. this.isGridMusic = !this.isGridMusic
  2707. })
  2708. }
  2709. .visibility(((this.modeType === 2 || this.modeType === 3) && !this.isCanBack) ? Visibility.Visible :
  2710. Visibility.None)
  2711. .width('100%')
  2712. .padding(10)
  2713. .height(50)
  2714. .border({
  2715. width: { bottom: 1 },
  2716. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  2717. })
  2718. Row({ space: 8 }) {
  2719. Row({ space: 8 }) {
  2720. Image($r("app.media.hm_play"))
  2721. .width(25)
  2722. .margin({ left: 8 })
  2723. .fillColor(this.themeColor)
  2724. Text(`播放全部`)
  2725. .fontColor($r('app.color.text_color'))
  2726. .fontSize(14)
  2727. .animation({
  2728. duration: 666,
  2729. curve: 'ease-in-out' // 可选动画曲线
  2730. })
  2731. Text(`(${Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length}首)`)
  2732. .fontColor($r('app.color.text_color'))
  2733. .fontSize(14)
  2734. .opacity(this.opacityItem)
  2735. .animation({
  2736. duration: 666,
  2737. curve: 'ease-in-out' // 可选动画曲线
  2738. })
  2739. }
  2740. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2741. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  2742. .animation({
  2743. duration: 666,
  2744. curve: 'ease-in-out' // 可选动画曲线
  2745. })
  2746. // .backgroundColor(this.isClickedPLayAll ? $r('app.color.button_click') : Color.Transparent)
  2747. .onTouch((event: TouchEvent) => {
  2748. if (event.type === TouchType.Down) {
  2749. this.isClickedPLayAll = true;
  2750. } else if (event.type === TouchType.Up || event.type === TouchType.Cancel) {
  2751. this.isClickedPLayAll = false;
  2752. }
  2753. })
  2754. .onClick(() => {
  2755. // ToastUtil.showToast('当前的手机的折叠状态 ='+DisplayUtil.getFoldStatus())
  2756. if (this.modeType === 0) {
  2757. if (ArrayUtil.isNotEmpty(this.getCurFileList())) {
  2758. this.doPlay(this.getCurFileList()[0])
  2759. }
  2760. } else {
  2761. if (ArrayUtil.isNotEmpty(this.mediaKuList)) {
  2762. this.doPlay(this.mediaKuList[0])
  2763. }
  2764. }
  2765. })
  2766. Row() {
  2767. TextInput({ placeholder: '输入名称...', text: this.searchText })
  2768. .height(35)
  2769. .onChange((value: string) => {
  2770. this.onSearchInput(value);
  2771. })
  2772. .layoutWeight(1)
  2773. Text(`取消`)
  2774. .margin({ left: 10, right: 10 })
  2775. .fontColor($r('app.color.text_color'))
  2776. .fontSize(16)
  2777. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2778. .onClick(() => {
  2779. this.isSearchMode = false
  2780. this.searchText = ''
  2781. this.updateListData(this.mediaKuList)
  2782. })
  2783. }
  2784. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  2785. .animation({
  2786. duration: 666,
  2787. curve: 'ease-in-out' // 可选动画曲线
  2788. })
  2789. Blank()
  2790. Image($r("app.media.search"))
  2791. .width(25)// .visibility(this.modeType===1?Visibility.Visible:Visibility.None)
  2792. .animation({
  2793. duration: 666,
  2794. curve: 'ease-in-out' // 可选动画曲线
  2795. })// .opacity(this.opacityItem)
  2796. .fillColor(this.themeColor)
  2797. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2798. .onClick(() => {
  2799. this.isSearchMode = true
  2800. })
  2801. Image($r("app.media.refresh"))
  2802. .fillColor(this.themeColor)
  2803. .width(25)
  2804. .visibility(this.isHistory || this.isCanBack || this.isSearchMode ? Visibility.None : Visibility.Visible)
  2805. .animation({
  2806. duration: 666,
  2807. curve: 'ease-in-out' // 可选动画曲线
  2808. })
  2809. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2810. .onClick(() => {
  2811. if (this.isFavMusic) {
  2812. this.getFavList(true)
  2813. } else {
  2814. if(this.modeType == 0){
  2815. this.asyncCurrentPathData()
  2816. }else if(this.modeType ==1){
  2817. workerInstance.postMessage({ code: 2, data: this.context });
  2818. }
  2819. }
  2820. })
  2821. Image($r("app.media.top_rank"))
  2822. .width(25)
  2823. .visibility(this.isHistory || this.isSearchMode ? Visibility.None :
  2824. Visibility.Visible)// .opacity(this.opacityItem)
  2825. .animation({
  2826. duration: 666,
  2827. curve: 'ease-in-out' // 可选动画曲线
  2828. })
  2829. .fillColor(this.themeColor)
  2830. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2831. .onClick(() => {
  2832. this.showRankDialog()
  2833. })
  2834. Image(this.isMultiSelect ? $r("app.media.cancel_multi") : $r("app.media.top_flower"))
  2835. .width(24)
  2836. .visibility(this.isHistory || this.isSearchMode ? Visibility.None : Visibility.Visible)
  2837. .animation({
  2838. duration: 666,
  2839. curve: 'ease-in-out' // 可选动画曲线
  2840. })
  2841. .fillColor(this.themeColor)
  2842. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2843. .onClick(() => {
  2844. this.isMultiSelect = !this.isMultiSelect
  2845. })
  2846. SymbolGlyph($r('sys.symbol.trash'))
  2847. .fontColor([this.themeColor])
  2848. .fontSize(25)
  2849. .effectStrategy(1)
  2850. .visibility(this.isHistory ? Visibility.Visible : Visibility.None)
  2851. .animation({
  2852. duration: 666,
  2853. curve: 'ease-in-out' // 可选动画曲线
  2854. })
  2855. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2856. .onClick(() => {
  2857. this.clearVideoHistory() //清空播放记录
  2858. })
  2859. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  2860. .width(24)
  2861. .animation({
  2862. duration: 666,
  2863. curve: 'ease-in-out' // 可选动画曲线
  2864. })
  2865. .fillColor(this.themeColor)
  2866. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2867. .bindPopup($$this.tipPopup, {
  2868. builder: this.popupBuilder,
  2869. placement: Placement.Bottom,
  2870. maskColor: 0x33000000,
  2871. enableArrow: true,
  2872. onStateChange: (e) => {
  2873. if (!e.isVisible) {
  2874. this.tipPopup = false;
  2875. }
  2876. }
  2877. })
  2878. .onClick(() => {
  2879. this.isGridMusic = !this.isGridMusic
  2880. })
  2881. }
  2882. .width('100%')
  2883. .padding(10)
  2884. .height(50)
  2885. .visibility(this.modeType === 0 || this.modeType === 1 || this.isCanBack ? Visibility.Visible : Visibility.None)
  2886. .border({
  2887. width: { bottom: 1 },
  2888. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  2889. })
  2890. }
  2891. .visibility(this.isShowAllBar ? Visibility.Visible : Visibility.None)
  2892. }
  2893. // 第二步:popup构造器定义弹框内容
  2894. @Builder popupBuilder() {
  2895. Column({ space: 2 }) {
  2896. Text('友情提示:双指缩放可以放大缩小列表')
  2897. .fontSize(12)
  2898. .fontWeight(FontWeight.Regular)
  2899. .fontColor($r('app.color.text_color'))
  2900. }
  2901. .justifyContent(FlexAlign.SpaceAround)
  2902. .width(220)
  2903. .height(55)
  2904. .padding(15)
  2905. }
  2906. //搜索功能的实现
  2907. @State searchText: string = ''; // 用户输入内容
  2908. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  2909. @State isSearchMode: boolean = false
  2910. // 实时搜索逻辑(带防抖)
  2911. private onSearchInput(value: string) {
  2912. this.searchText = value.trim();
  2913. let mSearchList: Array<VideoItem> = []
  2914. switch (this.modeType) {
  2915. case 0:
  2916. mSearchList = this.videoLocalList
  2917. break;
  2918. case 1:
  2919. mSearchList = this.mediaKuList
  2920. break;
  2921. case 2:
  2922. mSearchList = this.artistList
  2923. break;
  2924. case 3:
  2925. mSearchList = this.albumList
  2926. break;
  2927. }
  2928. // 新增条件判断:空输入时显示所有数据
  2929. if (this.searchText === '') {
  2930. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  2931. } else {
  2932. this.filteredList = mSearchList.filter((item: VideoItem) => {
  2933. return item.name.toLowerCase().includes(this.searchText.toLowerCase());
  2934. });
  2935. }
  2936. this.updateListData(this.filteredList);
  2937. // this.isSearchMode = false; // 根据业务需求决定是否启用
  2938. }
  2939. @State dragItem: number = -1
  2940. @State scaleItem: number = -1
  2941. @State neighborItem: number = -1
  2942. @State neighborScale: number = -1
  2943. @State offsetY: number = 0
  2944. private dragRefOffset: number = 0
  2945. private ITEM_INTV: number = 78
  2946. scaleSelect(item: number): number {
  2947. if (this.scaleItem === item) {
  2948. return 1.05
  2949. } else if (this.neighborItem === item) {
  2950. return this.neighborScale
  2951. } else {
  2952. return 1
  2953. }
  2954. }
  2955. itemMove(index: number, newIndex: number): void {
  2956. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  2957. return;
  2958. }
  2959. let tmp = this.videoLocalList.splice(index, 1);
  2960. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  2961. this.dataSource.pushArrayData(this.videoLocalList)
  2962. }
  2963. // Grid布局的开始
  2964. private dragRefOffSetX: number = 0;
  2965. private dragRefOffSetY: number = 0;
  2966. private FIX_VP_X: number = 180;
  2967. private FIX_VP_Y: number = 84;
  2968. isDraggable(index: number): boolean {
  2969. return index >= 0;
  2970. }
  2971. getRowEnd(item: number) {
  2972. if (item.toString() === '0') {
  2973. return 1;
  2974. } else {
  2975. return 0;
  2976. }
  2977. }
  2978. // [Start itemMove_start]
  2979. // itemMoveGrid(index: number, newIndex: number): void {
  2980. // if (!this.isDraggable(newIndex)) {
  2981. // return;
  2982. // }
  2983. // let tmp = this.videoLocalList.splice(index, 1);
  2984. // this.videoLocalList.splice(newIndex, 0, tmp[0]);
  2985. // // this.bigItemIndex = this.videoLocalList.findIndex((item) => item === 0);
  2986. // }
  2987. isInLeft(index: number) {
  2988. return index % 2 == 0;
  2989. }
  2990. down(index: number): void {
  2991. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  2992. return;
  2993. }
  2994. this.offsetY -= this.FIX_VP_Y;
  2995. this.dragRefOffSetY += this.FIX_VP_Y;
  2996. this.itemMove(index, index + 1);
  2997. }
  2998. up(index: number): void {
  2999. if (!this.isDraggable(index - 2)) {
  3000. return;
  3001. }
  3002. this.offsetY += this.FIX_VP_Y;
  3003. this.dragRefOffSetY -= this.FIX_VP_Y;
  3004. this.itemMove(index, index - 1);
  3005. }
  3006. left(index: number): void {
  3007. if (this.isInLeft(index)) {
  3008. return;
  3009. }
  3010. if (!this.isDraggable(index - 1)) {
  3011. return;
  3012. }
  3013. this.offsetX += this.FIX_VP_X;
  3014. this.dragRefOffSetX -= this.FIX_VP_X;
  3015. this.itemMove(index, index - 1)
  3016. }
  3017. right(index: number): void {
  3018. if (!this.isInLeft(index)) {
  3019. return;
  3020. }
  3021. if (!this.isDraggable(index + 1)) {
  3022. return;
  3023. }
  3024. this.offsetX -= this.FIX_VP_X;
  3025. this.dragRefOffSetX += this.FIX_VP_X;
  3026. this.itemMove(index, index + 1)
  3027. }
  3028. private scroller: Scroller = new Scroller();
  3029. @State startIndex: number = 0
  3030. @State endIndex: number = 0
  3031. @State scaleValue: number = 1
  3032. @State pinchValue: number = 1
  3033. layoutOptionsForHeader: GridLayoutOptions = {
  3034. regularSize: [1, 1], // 只支持[1, 1]
  3035. irregularIndexes: [0], // 索引为0的GridItem占用一行
  3036. };
  3037. @Builder
  3038. getGridView() {
  3039. Grid(this.scroller, this.layoutOptionsForHeader) {
  3040. GridItem() {
  3041. if (this.isShowCoverHeader()) {
  3042. this.coverHeader()
  3043. } else {
  3044. this.listViewTitle()
  3045. }
  3046. }
  3047. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  3048. GridItem() {
  3049. Stack({ alignContent: Alignment.Center }) {
  3050. this.MusicItemGrid(item, index)
  3051. }
  3052. }
  3053. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  3054. TransitionEffect.scale({ x: 0, y: 0 })))
  3055. .clickEffect({ level: ClickEffectLevel.LIGHT })
  3056. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  3057. .zIndex(this.dragItem === index ? 1 : 0)
  3058. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  3059. .hitTestBehavior(this.isDraggable(this.videoLocalList.indexOf(item)) ? HitTestMode.Default : HitTestMode.None)
  3060. //长按拖动代码
  3061. .gesture(
  3062. GestureGroup(GestureMode.Sequence,
  3063. LongPressGesture({ repeat: true })
  3064. .onAction(() => {
  3065. this.getUIContext().animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3066. this.scaleItem = index;
  3067. })
  3068. })
  3069. .onActionEnd(() => {
  3070. this.getUIContext().animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3071. this.scaleItem = -1;
  3072. })
  3073. }),
  3074. PanGesture({ fingers: 1, direction: null, distance: 0 })
  3075. .onActionStart(() => {
  3076. this.dragItem = index;
  3077. this.dragRefOffSetX = 0;
  3078. this.dragRefOffSetY = 0;
  3079. })
  3080. .onActionUpdate((event: GestureEvent) => {
  3081. this.offsetX = event.offsetX - this.dragRefOffSetX;
  3082. this.offsetY = event.offsetY - this.dragRefOffSetY;
  3083. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3084. let index = this.videoLocalList.indexOf(item);
  3085. if (this.offsetY >= this.FIX_VP_Y / 2 && (this.offsetX <= 44 && this.offsetX >= -44)) {
  3086. this.down(index);
  3087. } else if (this.offsetY <= -this.FIX_VP_Y / 2 && (this.offsetX <= 44 && this.offsetX >= -44)) {
  3088. this.up(index);
  3089. } else if (this.offsetX >= this.FIX_VP_X / 2 && (this.offsetY <= 50 && this.offsetY >= -50)) {
  3090. this.right(index);
  3091. } else if (this.offsetX <= -this.FIX_VP_Y / 2 && (this.offsetY <= 50 && this.offsetY >= -50)) {
  3092. this.left(index);
  3093. }
  3094. })
  3095. // if (this.offsetY > this.FIX_VP_Y * 0.7) {
  3096. // this.scroller.scrollToIndex(index + 10, true,ScrollAlign.CENTER);
  3097. // }
  3098. })
  3099. .onActionEnd(() => {
  3100. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3101. this.dragItem = -1;
  3102. })
  3103. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150 }, () => {
  3104. this.scaleItem = -1;
  3105. })
  3106. })
  3107. )
  3108. .onCancel(() => {
  3109. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3110. this.dragItem = -1;
  3111. })
  3112. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150 }, () => {
  3113. this.scaleItem = -1;
  3114. })
  3115. })
  3116. )
  3117. // [End gesture_start]
  3118. // [EndExclude GridItem_start]
  3119. }, (item: VideoItem) => item.filePath)
  3120. }
  3121. .width(this.isShowHeader ? '100%' : '94%')
  3122. .height('100%')
  3123. .editMode(true)
  3124. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3125. .animation({ duration: 500, curve: Curve.Ease }))
  3126. // .margin({ bottom: this.isCoverOpacity() ? 80 : 175 })
  3127. .margin({
  3128. bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? this.topBarHeight+30 : this.topBarHeight+90)
  3129. : (this.isShowCoverHeader() ? this.topBarHeight+45 : this.topBarHeight+128)
  3130. })
  3131. .layoutWeight(1)
  3132. .scrollBar(BarState.Off)
  3133. .supportAnimation(true)
  3134. .cachedCount(3)
  3135. // .columnsTemplate('1fr '.repeat(this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM ? 2 : 5))
  3136. .columnsTemplate(
  3137. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  3138. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  3139. )
  3140. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  3141. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  3142. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  3143. .gesture(PinchGesture({ fingers: 2 })
  3144. .onActionEnd((event: GestureEvent) => {
  3145. this.setGridTwoFingers()
  3146. })
  3147. .onActionUpdate(e => {
  3148. this.scaleValue = this.pinchValue * e.scale
  3149. })
  3150. .onActionStart(e => {
  3151. }))
  3152. .enableScrollInteraction(true)
  3153. // 滚轴滑动,记录下滑动时的起始位置和终点位置
  3154. .onScrollIndex((start: number, end: number) => {
  3155. this.startIndex = start
  3156. this.endIndex = end
  3157. })
  3158. .onScrollFrameBegin((offset: number) => {
  3159. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  3160. // if (this.isPhoneLan()) {
  3161. // this.setBarHeightHide(offset)
  3162. // } else
  3163. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  3164. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  3165. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  3166. if (this.isScrollHide) {
  3167. this.setBarHeightHide2(offset)
  3168. } else {
  3169. this.setBarHeightNormal()
  3170. }
  3171. } else {
  3172. this.setBarHeightHide(offset)
  3173. }
  3174. return { offsetRemain: offset };
  3175. })
  3176. //允许拖拽音乐和视频到List或Grid上自动导入视频
  3177. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3178. .onDrop((event?: DragEvent) => {
  3179. try {
  3180. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3181. if (dragData !== undefined) {
  3182. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3183. if (records.length > 0) {
  3184. for (let i = 0; i < records.length; i++) {
  3185. let types = records[i].getTypes();
  3186. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3187. const fileUriUds =
  3188. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3189. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3190. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3191. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3192. this.targetFile = fileUriUds.oriUri;
  3193. this.saveVideoDatas([this.targetFile])
  3194. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3195. }
  3196. }
  3197. }
  3198. } else {
  3199. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3200. }
  3201. } else {
  3202. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3203. }
  3204. } catch (error) {
  3205. const err = error as BusinessError;
  3206. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3207. }
  3208. })
  3209. }
  3210. @State targetFile: string = '';
  3211. setGridTwoFingers() {
  3212. this.pinchValue = this.scaleValue;
  3213. Logger.info('this.pinchValue = ' + this.pinchValue);
  3214. if (this.pinchValue >= 1) {
  3215. this.twoFingerType++
  3216. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  3217. if (this.twoFingerType > 3) {
  3218. this.twoFingerType = 3
  3219. }
  3220. } else {
  3221. this.twoFingerType--
  3222. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  3223. if (this.twoFingerType < 1) {
  3224. this.twoFingerType = 3
  3225. this.isGridMusic = false
  3226. }
  3227. }
  3228. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  3229. this.pinchValue = 1;
  3230. this.scaleValue = 1;
  3231. }
  3232. @State longItemFilePath: string = ''
  3233. @State tempLyricContent: string = ''
  3234. @Builder
  3235. private MusicItemGrid(item: VideoItem, index: number) {
  3236. Button({ type: ButtonType.Normal, stateEffect: false }) {
  3237. Stack() {
  3238. Column() {
  3239. Image(StrUtil.isEmpty(item.pixelMapPath) ? Utility.getMusisBg2(index) : item.pixelMapPath)
  3240. .height(this.getGridHeight())
  3241. .width(this.getGridWight())
  3242. .alt($r('app.media.ic_avatar6'))
  3243. .clip(true)
  3244. .borderRadius({
  3245. topLeft: 12,
  3246. topRight: 12,
  3247. bottomLeft: 0,
  3248. bottomRight: 0
  3249. })
  3250. .draggable(false)
  3251. .opacity(this.opacityItem)// 绑定透明度
  3252. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3253. // .animation({ duration: 500, curve: Curve.Ease }))
  3254. .animation({
  3255. duration: 666,
  3256. curve: 'ease-in-out' // 可选动画曲线
  3257. })
  3258. .margin({
  3259. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3260. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3261. })
  3262. Column() {
  3263. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  3264. .fontSize(this.twoFingerType == 1 ? 14 : this.twoFingerType == 2 ? 16 : 18)
  3265. .maxLines(1)
  3266. .fontWeight(FontWeight.Bold)
  3267. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3268. .animation({
  3269. duration: 555,
  3270. curve: 'Linear',
  3271. })
  3272. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3273. $r('app.color.text_color'))
  3274. Column() {
  3275. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  3276. .fontSize(11)
  3277. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  3278. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3279. .fontColor($r('app.color.text_color'))
  3280. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  3281. .fontSize(11)
  3282. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  3283. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3284. .fontColor($r('app.color.text_color'))
  3285. Row(){
  3286. Column(){
  3287. Text(item.md5Str?.includes('Lossless')?
  3288. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  3289. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  3290. .padding({ top: 3,right:6,left:6,bottom:3 })
  3291. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3292. $r('app.color.text_color'))
  3293. .fontWeight(500)
  3294. .borderRadius(12)
  3295. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  3296. .backgroundColor('#FFC107')
  3297. }
  3298. .margin({ top: 2 ,right:6})
  3299. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  3300. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  3301. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  3302. .fontSize(11)
  3303. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  3304. .maxLines(1)
  3305. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3306. .margin({ top: 2 ,right:18})
  3307. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  3308. || item.type == CommonConstants.TYPE_IS_ALBUM
  3309. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3310. .fontWeight(FontWeight.Medium)
  3311. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3312. $r('app.color.text_color'))
  3313. }
  3314. }
  3315. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  3316. }
  3317. .bindPopup(this.longItemFilePath === item.filePath, {
  3318. builder: this.MenuBuilder(item, index, item.filePath),
  3319. placement: Placement.Top,
  3320. // autoCancel: true,
  3321. mask: { color: '#33000000' },
  3322. // popupColor: Color.Yellow,
  3323. enableArrow: false, //是否显示箭头
  3324. showInSubWindow: false,
  3325. onStateChange: (e) => {
  3326. if (!e.isVisible) {
  3327. this.longItemFilePath = ''
  3328. this.tempLyricContent = ''
  3329. }
  3330. }
  3331. })
  3332. .gesture(LongPressGesture()
  3333. .onAction(async () => {
  3334. //如果是专辑和艺术家的首页,不能长按
  3335. if ((this.modeType === 2 || this.modeType == 3) && !this.isCanBack) {
  3336. return
  3337. }
  3338. //如果是我的收藏 最近播放等也不能长按
  3339. if (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3340. item.name === LocalMusic.STR_HISTORY_MUSIC
  3341. ) {
  3342. return
  3343. }
  3344. this.longItemFilePath = item.filePath
  3345. this.tempLyricContent = await this.getLyricContent(item)
  3346. LogUtil.info('长按this.tempLyricContent = ' + this.tempLyricContent)
  3347. })
  3348. .onActionEnd((event: GestureEvent) => {
  3349. })
  3350. )
  3351. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 55 : 42)
  3352. .width(this.getGridWight())
  3353. .justifyContent(FlexAlign.Center)
  3354. .margin({
  3355. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3356. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3357. })
  3358. }
  3359. .width(this.getGridWight())
  3360. .borderRadius(12)
  3361. .backgroundImage(item.pixelMapPath)
  3362. .backgroundImageSize({ height: '100%', width: '100%' })
  3363. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  3364. .animation({ curve: Curve.Sharp, duration: 300 })
  3365. Checkbox({ name: 'checkbox' + index })
  3366. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  3367. .selectedColor(this.themeColor)
  3368. .shape(CheckBoxShape.CIRCLE)
  3369. .opacity(this.isMultiSelect ? 1 : 0)
  3370. .animation({
  3371. duration: 666,
  3372. curve: 'Smooth' // 可选动画曲线
  3373. })
  3374. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  3375. Visibility.None)
  3376. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  3377. .margin({ left: 20, top: 8, bottom: 8 })
  3378. .width(38)
  3379. .height(38)
  3380. }
  3381. }
  3382. .backgroundColor(Color.Transparent)
  3383. .width('100%')
  3384. .padding({ top: 15 })
  3385. .height(this.getGridAllHeight())
  3386. .onClick(() => {
  3387. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  3388. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3389. this.handleFileSelection(item, !isChecked);
  3390. } else {
  3391. this.doPlay(item, index)
  3392. }
  3393. })
  3394. }
  3395. getGridAllHeight() {
  3396. let heightG = 222
  3397. switch (this.twoFingerType) {
  3398. case 1:
  3399. heightG = 118
  3400. break;
  3401. case 2:
  3402. heightG = 168
  3403. break;
  3404. case 3:
  3405. heightG = 222
  3406. break;
  3407. }
  3408. return heightG
  3409. }
  3410. getGridHeight() {
  3411. let heightG = 150
  3412. switch (this.twoFingerType) {
  3413. case 1:
  3414. heightG = 55
  3415. break;
  3416. case 2:
  3417. heightG = 100
  3418. break;
  3419. case 3:
  3420. heightG = 150
  3421. break;
  3422. }
  3423. return heightG
  3424. }
  3425. getGridWight() {
  3426. let wightG = 158
  3427. switch (this.twoFingerType) {
  3428. case 1:
  3429. wightG = 80
  3430. break;
  3431. case 2:
  3432. wightG = 110
  3433. break;
  3434. case 3:
  3435. wightG = 158
  3436. break;
  3437. }
  3438. return wightG
  3439. }
  3440. @State isShowDetail:boolean = false
  3441. @Builder
  3442. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  3443. Scroll() {
  3444. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  3445. Menu() {
  3446. MenuItem({
  3447. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  3448. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  3449. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  3450. })
  3451. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3452. .onClick(() => {
  3453. if (item) {
  3454. this.doFav(item)
  3455. }
  3456. this.longItemFilePath = ''
  3457. })
  3458. MenuItem({
  3459. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  3460. content: '下一首播放'
  3461. })
  3462. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3463. .onClick(() => {
  3464. this.addToNextPlay(item);
  3465. this.longItemFilePath = ''
  3466. })
  3467. MenuItem({
  3468. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  3469. content: '编辑信息'
  3470. })
  3471. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  3472. height: this.isCoverOpacity() ? '95%' : '88%',
  3473. dragBar: true,
  3474. showClose: true,
  3475. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3476. title: { title: '编辑信息' }
  3477. })
  3478. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3479. .onClick(() => {
  3480. this.isShowEdit = !this.isShowEdit;
  3481. })
  3482. MenuItem({
  3483. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  3484. content: $r('app.string.rename')
  3485. })
  3486. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  3487. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3488. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  3489. .onClick(() => {
  3490. this.showReNameDialog(item, index + '', filePath)
  3491. this.longItemFilePath = ''
  3492. })
  3493. MenuItem({
  3494. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  3495. content: $r('app.string.delete')
  3496. })
  3497. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  3498. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3499. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  3500. .onClick(() => {
  3501. this.showWarnIsDeleteFile(item, index + '', filePath)
  3502. this.longItemFilePath = ''
  3503. })
  3504. MenuItem({
  3505. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  3506. content: $r('app.string.detail')
  3507. })
  3508. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  3509. height:this.isCoverOpacity()?'95%': '95%',
  3510. dragBar: true,
  3511. showClose: true,
  3512. blurStyle:BlurStyle.Thin,
  3513. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3514. backgroundColor:Color.Transparent,
  3515. title: { title: '详情信息' }
  3516. })
  3517. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3518. .onClick(() => {
  3519. this.isShowDetail = !this.isShowDetail
  3520. })
  3521. MenuItem({
  3522. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  3523. content: $r('app.string.share')
  3524. })
  3525. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3526. .onClick(() => {
  3527. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  3528. this.longItemFilePath = ''
  3529. })
  3530. }
  3531. .font({ size: 15, weight: FontWeight.Normal })
  3532. }
  3533. .width(180)
  3534. }
  3535. .height(item.type === CommonConstants.TYPE_IS_DIR ? 150 : 400)
  3536. }
  3537. private listMaxScrollOffsetY: number = 0
  3538. @State selectedIndex: number = -1
  3539. setlistTwoFingers() {
  3540. this.pinchValue = this.scaleValue;
  3541. Logger.info('this.pinchValue = ' + this.pinchValue);
  3542. if (this.pinchValue >= 1) {
  3543. this.twoFingerType++
  3544. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  3545. if (this.twoFingerType > 3) {
  3546. this.twoFingerType = 1
  3547. this.isGridMusic = true
  3548. }
  3549. } else {
  3550. this.twoFingerType--
  3551. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  3552. if (this.twoFingerType < 1) {
  3553. this.twoFingerType = 1
  3554. }
  3555. }
  3556. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  3557. this.pinchValue = 1;
  3558. this.scaleValue = 1;
  3559. }
  3560. @Builder
  3561. getListView() {
  3562. List({ scroller: this.listScroller }) {
  3563. ListItemGroup({ header: this.coverHeader() }) {
  3564. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  3565. ListItem() {
  3566. Column() {
  3567. if (item.type === CommonConstants.TYPE_IS_DIR
  3568. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  3569. this.DirItem(item, index)
  3570. } else if (item.type === CommonConstants.TYPE_IS_CSJAD) { //如果是穿山甲广告
  3571. } else {
  3572. this.MusicItem(item, index)
  3573. }
  3574. }
  3575. .shadow(this.scaleItem === index ? {
  3576. radius: 70,
  3577. color: '#15000000',
  3578. offsetX: 0,
  3579. offsetY: 0
  3580. } :
  3581. {
  3582. radius: 0,
  3583. color: '#15000000',
  3584. offsetX: 0,
  3585. offsetY: 0
  3586. })
  3587. .animation({ curve: Curve.Sharp, duration: 300 })
  3588. }
  3589. // .transition(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }))
  3590. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  3591. .animation({ duration: 500 }),
  3592. TransitionEffect.scale({ x: 0, y: 0 })))
  3593. .clickEffect({ level: ClickEffectLevel.LIGHT })
  3594. .swipeAction((
  3595. (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
  3596. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  3597. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath) } : {}) //左滑
  3598. .onClick(() => {
  3599. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  3600. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3601. this.handleFileSelection(item, !isChecked);
  3602. } else {
  3603. this.doPlay(item, index)
  3604. }
  3605. })
  3606. //拖动List关键代码开始
  3607. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  3608. .zIndex(this.dragItem === index ? 1 : 0)
  3609. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  3610. .gesture(
  3611. GestureGroup(GestureMode.Sequence,
  3612. LongPressGesture({ repeat: true })
  3613. .onAction((event?: GestureEvent) => {
  3614. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3615. this.scaleItem = index
  3616. })
  3617. })
  3618. .onActionEnd(() => {
  3619. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3620. this.scaleItem = -1
  3621. })
  3622. }),
  3623. PanGesture({ fingers: 1, direction: null, distance: 0 })
  3624. .onActionStart(() => {
  3625. this.dragItem = index // 记录当前拖动项索引
  3626. this.dragRefOffset = 0 // 重置偏移基准
  3627. })
  3628. .onActionUpdate((event: GestureEvent) => {
  3629. this.offsetY = event.offsetY - this.dragRefOffset;
  3630. this.neighborItem = -1;
  3631. let indexA = this.videoLocalList.indexOf(item);
  3632. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  3633. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  3634. let value: number = 0;
  3635. if (this.offsetY < 0) {
  3636. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  3637. this.neighborItem = indexA - 1;
  3638. this.neighborScale = 1 - value / 20;
  3639. } else if (this.offsetY > 0) {
  3640. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  3641. this.neighborItem = indexA + 1;
  3642. this.neighborScale = 1 - value / 20;
  3643. }
  3644. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  3645. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3646. this.offsetY -= this.ITEM_INTV;
  3647. this.dragRefOffset += this.ITEM_INTV;
  3648. this.itemMove(indexA, indexA + 1);
  3649. });
  3650. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  3651. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3652. this.offsetY += this.ITEM_INTV;
  3653. this.dragRefOffset -= this.ITEM_INTV;
  3654. this.itemMove(indexA, indexA - 1);
  3655. });
  3656. }
  3657. let curListOffset = this.listScroller.currentOffset()
  3658. // 获取手指信息
  3659. let fingerInfo = event.fingerList[0]
  3660. let clickPercentY =
  3661. (fingerInfo.globalY - Number(this.listArea.globalPosition.y)) / Number(this.listArea.height)
  3662. if (clickPercentY > 0.8 && !this.listScroller.isAtEnd()) {
  3663. let scrollVelocity = clickPercentY > 0.9 ? 4 : 2
  3664. if (this.listMaxScrollOffsetY - curListOffset.yOffset > scrollVelocity + 5) {
  3665. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset += scrollVelocity })
  3666. }
  3667. } else if (clickPercentY < 0.2 && curListOffset.yOffset >= 0) {
  3668. let scrollVelocity = clickPercentY < 0.1 ? 4 : 2
  3669. if (curListOffset.yOffset > scrollVelocity + 5) {
  3670. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset -= scrollVelocity })
  3671. }
  3672. }
  3673. })
  3674. .onActionEnd((event: GestureEvent) => {
  3675. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3676. this.dragItem = -1
  3677. this.neighborItem = -1
  3678. })
  3679. animateTo({
  3680. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  3681. }, () => {
  3682. this.scaleItem = -1
  3683. })
  3684. })
  3685. )
  3686. .onCancel(() => {
  3687. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3688. this.dragItem = -1
  3689. this.neighborItem = -1
  3690. })
  3691. animateTo({
  3692. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  3693. }, () => {
  3694. this.scaleItem = -1
  3695. })
  3696. })
  3697. ) //拖动List关键代码结束
  3698. }, (item: VideoItem) => item.filePath)
  3699. }
  3700. }
  3701. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  3702. .gesture(PinchGesture({ fingers: 2 })
  3703. .onActionEnd((event: GestureEvent) => {
  3704. this.setlistTwoFingers()
  3705. })
  3706. .onActionUpdate(e => {
  3707. this.scaleValue = this.pinchValue * e.scale
  3708. })
  3709. .onActionStart(e => {
  3710. }))
  3711. // .divider({ strokeWidth: 1, color: this.isDarkMode? '#333333':'#ffe9f0f0' })
  3712. .margin({
  3713. bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? this.topBarHeight+25 : this.topBarHeight+80)
  3714. : (this.isShowCoverHeader() ? this.topBarHeight+35 : this.isHiCarSmall()?this.topBarHeight+90:this.topBarHeight+125)
  3715. })
  3716. .cachedCount(6)
  3717. .borderRadius(20)
  3718. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  3719. TransitionEffect.scale({ x: 0, y: 0 })))
  3720. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3721. // .animation({ duration: 500, curve: Curve.Ease }))
  3722. .layoutWeight(1)
  3723. .onScrollIndex((start) => {
  3724. this.selectedIndex = start
  3725. })
  3726. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  3727. .lanes(
  3728. new BreakpointType<number>({
  3729. sm: 1,
  3730. md: 2,
  3731. lg: 2,
  3732. xl: 3,
  3733. xxl: 4
  3734. }).getValue(this.currentBreakpoint),
  3735. new BreakpointType<number>({
  3736. sm: 0,
  3737. md: 12,
  3738. lg: 12,
  3739. xl: 16,
  3740. xxl: 20
  3741. }).getValue(this.currentBreakpoint)
  3742. )
  3743. .onAreaChange((oldValue: Area, newValue: Area) => {
  3744. this.listArea = newValue
  3745. if (this.twoFingerType == 3) {
  3746. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  3747. } else if (this.twoFingerType == 2) {
  3748. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  3749. } else if (this.twoFingerType == 1) {
  3750. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  3751. }
  3752. })
  3753. .onScrollFrameBegin((offset: number) => {
  3754. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  3755. // if (this.isPhoneLan()) {
  3756. // this.setBarHeightHide(offset)
  3757. // } else
  3758. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  3759. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  3760. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  3761. if (this.isScrollHide) {
  3762. this.setBarHeightHide2(offset)
  3763. } else {
  3764. this.setBarHeightNormal()
  3765. }
  3766. } else {
  3767. this.setBarHeightHide(offset)
  3768. }
  3769. return { offsetRemain: offset };
  3770. })
  3771. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  3772. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3773. .onDrop((event?: DragEvent) => {
  3774. try {
  3775. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3776. if (dragData !== undefined) {
  3777. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3778. if (records.length > 0) {
  3779. for (let i = 0; i < records.length; i++) {
  3780. let types = records[i].getTypes();
  3781. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3782. const fileUriUds =
  3783. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3784. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3785. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3786. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3787. this.targetFile = fileUriUds.oriUri;
  3788. this.saveVideoDatas([this.targetFile])
  3789. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3790. }
  3791. }
  3792. }
  3793. } else {
  3794. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3795. }
  3796. } else {
  3797. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3798. }
  3799. } catch (error) {
  3800. const err = error as BusinessError;
  3801. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3802. }
  3803. })
  3804. }
  3805. setBarHeightNormal() {
  3806. this.hideDone = false;
  3807. this.getUIContext().animateTo({
  3808. duration: 300
  3809. }, () => {
  3810. this.bottomBarHeight = 55 + 0;
  3811. this.topBarHeight = 50 + 0;
  3812. this.barOpacity = 1;
  3813. this.barBottomOpacity = 1
  3814. this.currentYOffset = 0;
  3815. this.isHiding = false;
  3816. });
  3817. }
  3818. setBarHeightHide(offset: number) {
  3819. if (offset > 0 && !this.hideDone) {
  3820. this.currentYOffset += offset;
  3821. if (this.currentYOffset <= 100) {
  3822. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  3823. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  3824. this.barOpacity = 1 - this.currentYOffset / 100;
  3825. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  3826. } else {
  3827. this.topBarHeight = 0;
  3828. this.bottomBarHeight = 0;
  3829. this.barBottomOpacity = 0
  3830. this.barOpacity = 0;
  3831. this.hideDone = true;
  3832. }
  3833. this.isHiding = true;
  3834. }
  3835. if (offset < 0 && this.isHiding) {
  3836. this.hideDone = false;
  3837. this.getUIContext().animateTo({
  3838. duration: 300
  3839. }, () => {
  3840. this.bottomBarHeight = 55 + 0;
  3841. this.topBarHeight = 50 + 0;
  3842. this.barOpacity = 1;
  3843. this.barBottomOpacity = 1
  3844. this.currentYOffset = 0;
  3845. this.isHiding = false;
  3846. });
  3847. }
  3848. }
  3849. //这个方法没隐藏bottomBar,只隐藏topbar
  3850. setBarHeightHide2(offset: number) {
  3851. if (offset > 0 && !this.hideDone) {
  3852. this.currentYOffset += offset;
  3853. if (this.currentYOffset <= 100) {
  3854. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  3855. this.barOpacity = 1 - this.currentYOffset / 100;
  3856. } else {
  3857. this.topBarHeight = 0;
  3858. this.barOpacity = 0;
  3859. this.hideDone = true;
  3860. }
  3861. this.isHiding = true;
  3862. }
  3863. if (offset < 0 && this.isHiding) {
  3864. this.hideDone = false;
  3865. this.getUIContext().animateTo({
  3866. duration: 300
  3867. }, () => {
  3868. this.topBarHeight = 50 + 0;
  3869. this.barOpacity = 1;
  3870. this.currentYOffset = 0;
  3871. this.isHiding = false;
  3872. });
  3873. }
  3874. }
  3875. private doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean) {
  3876. switch (item.type) {
  3877. case CommonConstants.TYPE_IS_DIR:
  3878. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  3879. let offsetB = 0
  3880. if (this.isGridMusic) {
  3881. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  3882. let cur = this.scroller.currentOffset()
  3883. if (cur && typeof cur.yOffset === 'number') {
  3884. offsetB = cur.yOffset
  3885. }
  3886. }
  3887. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  3888. } else {
  3889. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  3890. let cur = this.listScroller.currentOffset()
  3891. if (cur && typeof cur.yOffset === 'number') {
  3892. offsetB = cur.yOffset
  3893. }
  3894. }
  3895. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  3896. }
  3897. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  3898. this.showVerifyDialog()
  3899. this.currentTitleName = '私密音频'
  3900. this.currentTitleCover = $r('app.media.ic_avatar5')
  3901. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  3902. this.titleBarModel.setTitleName('最近播放')
  3903. this.currentTitleCover = $r('app.media.ic_avatar2')
  3904. this.currentTitleName = '最近播放'
  3905. //加载动画效果
  3906. this.updateListData(this.historyList, true)
  3907. // this.videoLocalList = this.historyList
  3908. if (ArrayUtil.isEmpty(this.historyList)) {
  3909. ToastUtil.showToast('最近播放记录空空如也')
  3910. } else {
  3911. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  3912. }
  3913. this.isHistory = true
  3914. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3915. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  3916. this.titleBarModel.setTitleName('我的收藏')
  3917. this.currentTitleName = '我的收藏'
  3918. this.currentTitleCover = $r('app.media.ic_avatar1')
  3919. //加载动画效果
  3920. this.updateListData(this.favList)
  3921. if (ArrayUtil.isEmpty(this.favList)) {
  3922. ToastUtil.showToast('无音乐收藏记录')
  3923. } else {
  3924. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  3925. }
  3926. this.isFavMusic = true
  3927. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3928. } else {
  3929. this.currentTitleName = item.name
  3930. this.currentPath = item.filePath
  3931. this.currentTitleCover = $r('app.media.ic_avatar5')
  3932. this.getSortedFiles(this.currentPath)
  3933. }
  3934. //进入歌单的时候的滚动位置在顶部
  3935. if (this.isGridMusic) {
  3936. this.scroller.scrollToIndex(0)
  3937. }
  3938. setTimeout(() => {
  3939. if (this.modeType == 0) {
  3940. if (!this.isGridMusic) {
  3941. this.listScroller.scrollToIndex(0)
  3942. }
  3943. }
  3944. }, 200)
  3945. break;
  3946. case CommonConstants.TYPE_IS_ARTIST:
  3947. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  3948. let offsetA = 0
  3949. if (this.isGridMusic) {
  3950. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  3951. let cur = this.scroller.currentOffset()
  3952. if (cur && typeof cur.yOffset === 'number') {
  3953. offsetA = cur.yOffset
  3954. }
  3955. }
  3956. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  3957. } else {
  3958. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  3959. let cur = this.listScroller.currentOffset()
  3960. if (cur && typeof cur.yOffset === 'number') {
  3961. offsetA = cur.yOffset
  3962. }
  3963. }
  3964. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  3965. }
  3966. let mList = this.artistMap.get(item.name)
  3967. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  3968. Utility.doSortListAscending(mList)
  3969. this.isCanBack = true
  3970. this.titleBarModel.setTitleName(item.name)
  3971. this.currentTitleName = '艺术家:' + item.name
  3972. if (item.pixelMapPath) {
  3973. this.currentTitleCover = item.pixelMapPath
  3974. }
  3975. this.updateListData(mList)
  3976. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3977. }
  3978. //进入歌单的时候的滚动位置在顶部
  3979. if (this.isGridMusic) {
  3980. this.scroller.scrollToIndex(0)
  3981. }
  3982. break;
  3983. case CommonConstants.TYPE_IS_ALBUM:
  3984. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  3985. let offset = 0
  3986. if (this.isGridMusic) {
  3987. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  3988. let cur = this.scroller.currentOffset()
  3989. if (cur && typeof cur.yOffset === 'number') {
  3990. offset = cur.yOffset
  3991. }
  3992. }
  3993. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  3994. } else {
  3995. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  3996. let cur = this.listScroller.currentOffset()
  3997. if (cur && typeof cur.yOffset === 'number') {
  3998. offset = cur.yOffset
  3999. }
  4000. }
  4001. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  4002. }
  4003. let albumList = this.albumMap.get(item.name)
  4004. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  4005. Utility.doSortListAscending(albumList)
  4006. this.isCanBack = true
  4007. this.titleBarModel.setTitleName(item.name)
  4008. this.currentTitleName = '专辑:' + item.name
  4009. if (item.pixelMapPath) {
  4010. this.currentTitleCover = item.pixelMapPath
  4011. }
  4012. this.updateListData(albumList)
  4013. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4014. this.mScrollMap.set(item.name, this.selectedIndex)
  4015. }
  4016. //进入歌单的时候的滚动位置在顶部
  4017. if (this.isGridMusic) {
  4018. this.scroller.scrollToIndex(0)
  4019. }
  4020. break;
  4021. case CommonConstants.TYPE_IS_CSJAD:
  4022. return
  4023. break;
  4024. case CommonConstants.TYPE_LOCAL:
  4025. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  4026. this.stop();
  4027. }
  4028. if (isFromSonPlayList) { //点击来自右下角的播放列表
  4029. this.currentSong = item
  4030. if (index !== undefined) {
  4031. this.curIndex = index
  4032. }
  4033. } else {
  4034. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  4035. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  4036. this.songList = globalVideoList
  4037. this.sonDataSource.pushArrayData(this.songList)
  4038. this.currentSong = globalVideoList[this.curIndex]
  4039. }
  4040. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  4041. this.videoUrl = this.currentSong.filePath
  4042. this.name = this.currentSong.name
  4043. this.cover = this.currentSong.pixelMapPath
  4044. this.artist = this.currentSong.artist
  4045. LogUtil.info('this.currentSong.duration =' + this.currentSong.duration)
  4046. LogUtil.info('this.currentSong.sampleRate =' + this.currentSong.sampleRate)
  4047. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  4048. this.startPlayOrResumePlay()
  4049. break;
  4050. }
  4051. }
  4052. @Builder
  4053. PlayController() {
  4054. Column() {
  4055. Line().width('100%').height(1).backgroundColor($r('app.color.index_background'))
  4056. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  4057. Row() {
  4058. Row() {
  4059. RotatingCover({ songLabel: this.currentSong?.pixelMapPath })
  4060. Column() {
  4061. Text(this.currentSong?.name)
  4062. .fontSize(16)
  4063. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4064. .maxLines(1)
  4065. .fontColor($r('app.color.text_color'))
  4066. .fontWeight(500)
  4067. Row() {
  4068. Text(this.currentSong?.artist)
  4069. .margin({ top: 2 })
  4070. .fontSize(13)
  4071. .fontColor($r('app.color.text_color'))
  4072. }
  4073. }
  4074. .alignItems(HorizontalAlign.Start)
  4075. .margin({ right: 22 })
  4076. }
  4077. .padding({ right: 18 })
  4078. .layoutWeight(1)
  4079. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4080. .onClick(() => {
  4081. if (ArrayUtil.isNotEmpty(this.songList)) {
  4082. this.isShowPlay = true;
  4083. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  4084. this.initLyric(lyricPath);
  4085. this.startAutoHide()
  4086. } else {
  4087. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4088. }
  4089. })
  4090. Row() {
  4091. Image($r('app.media.hm_previous'))
  4092. .height(28)
  4093. .width(28)
  4094. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4095. .margin({ left: 8, right: 16 })
  4096. .fillColor(this.themeColor)
  4097. .displayPriority(2)
  4098. .onClick(() => {
  4099. if (ArrayUtil.isNotEmpty(this.songList)) {
  4100. this.playPrevious()
  4101. } else {
  4102. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4103. }
  4104. })
  4105. //播放进度条
  4106. Stack() {
  4107. Progress({
  4108. value: Math.floor(this.progressValue),
  4109. type: ProgressType.Ring,
  4110. })
  4111. .color(this.themeColor)// 进度条前景色为灰色
  4112. .backgroundColor($r('app.color.index_background'))
  4113. .height(40)
  4114. .aspectRatio(CommonConstants.ASPECT_RATIO)
  4115. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ? $r('app.media.hm_pause') : $r('app.media.hm_play2'))
  4116. .height(38)
  4117. .width(38)
  4118. .displayPriority(3)
  4119. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4120. .fillColor(this.themeColor)
  4121. .onClick(() => {
  4122. if (ArrayUtil.isNotEmpty(this.songList)) {
  4123. this.playOrPause()
  4124. } else {
  4125. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4126. }
  4127. })
  4128. }
  4129. Image($r('app.media.hm_next'))
  4130. .height(28)
  4131. .width(28)
  4132. .margin({
  4133. right: 16,
  4134. left: 16
  4135. })
  4136. .fillColor(this.themeColor)
  4137. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4138. .displayPriority(2)
  4139. .onClick(() => {
  4140. if (ArrayUtil.isNotEmpty(this.songList)) {
  4141. this.playNext()
  4142. } else {
  4143. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4144. }
  4145. })
  4146. Image($r('app.media.hm_playlist'))
  4147. .height(28)
  4148. .width(28)
  4149. .displayPriority(1)
  4150. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4151. .fillColor(this.themeColor)
  4152. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  4153. height: '95%',
  4154. dragBar: true,
  4155. showClose: true,
  4156. blurStyle: BlurStyle.Thin,
  4157. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  4158. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  4159. title: {
  4160. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  4161. + `(${this.songList.length}首)`
  4162. }
  4163. })
  4164. .onClick(() => {
  4165. if (ArrayUtil.isNotEmpty(this.songList)) {
  4166. this.isShowSheet = !this.isShowSheet;
  4167. this.isFrontWhite = false
  4168. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  4169. setTimeout(() => {
  4170. this.playListScroller.scrollToIndex(this.curIndex, true, ScrollAlign.CENTER)
  4171. }, 123)
  4172. } else {
  4173. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4174. }
  4175. })
  4176. }
  4177. }
  4178. .width('100%')
  4179. .height(this.bottomBarHeight)
  4180. .justifyContent(FlexAlign.Center)
  4181. .hitTestBehavior(HitTestMode.Transparent)
  4182. .backgroundColor(this.isCustomizeBg ? Color.Transparent : $r('app.color.bottom_control_background'))
  4183. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  4184. // modalTransition: ModalTransition.DEFAULT,
  4185. transition: AnimationHelper.transitionInDown(666),
  4186. backgroundColor: 'rgba(0, 0, 0, 0.9)',
  4187. })
  4188. .padding({
  4189. left: 16,
  4190. right: 16
  4191. })
  4192. Line()
  4193. .width('100%')
  4194. .height(25)
  4195. .backgroundColor($r('app.color.bottom_control_background'))// .visibility(this.isPhoneLan()?Visibility.None:this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
  4196. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  4197. }
  4198. .clickEffect({ level: ClickEffectLevel.HEAVY })
  4199. }
  4200. @State isFrontWhite: boolean = false
  4201. //播放列表布局
  4202. @Builder
  4203. PlayListSheet() {
  4204. Column() {
  4205. this.PlayList()
  4206. }
  4207. .width('100%')
  4208. .height('100%')
  4209. }
  4210. @State titleStr: string = ''
  4211. @State ablumStr: string = ''
  4212. @State artistStr: string = ''
  4213. @State lyricConStr: string = ''
  4214. @State currentEditItem: string = ''
  4215. doUpdateData() {
  4216. setTimeout(() => {
  4217. if (this.modeType === 0) {
  4218. this.deleteCache(this.currentPath)
  4219. this.getSortedFiles(this.currentPath)
  4220. }
  4221. workerInstance.postMessage({ code: 2, data: this.context });
  4222. workerInstance.postMessage({ code: 3, data: this.context });
  4223. workerInstance.postMessage({ code: 4, data: this.context });
  4224. }, 999)
  4225. }
  4226. //编辑信息
  4227. doEdit(item: VideoItem) {
  4228. if (!item) {
  4229. return
  4230. }
  4231. if (StrUtil.isEmpty(this.titleStr)) {
  4232. ToastUtil.showToast('标题不能为空')
  4233. return
  4234. }
  4235. this.table.updateMediaInfo(item.filePath, this.titleStr, this.artistStr, this.ablumStr,
  4236. (success: boolean, error?: string) => {
  4237. this.isShowEdit = false
  4238. if (success) {
  4239. console.log(" onecold 编辑信息成功,数据库已同步");
  4240. ToastUtil.showToast('保存成功')
  4241. this.isShowMoreView = false
  4242. this.name = this.titleStr
  4243. if (item.filePath == this.currentSong?.filePath) {
  4244. this.currentSong.name = this.titleStr
  4245. this.artist = this.artistStr
  4246. this.currentSong.artist = this.artistStr
  4247. this.currentSong.album = this.ablumStr
  4248. }
  4249. this.doUpdateData()
  4250. } else {
  4251. ToastUtil.showToast('保存失败' + error?.toString())
  4252. console.error(" onecold 编辑信息数据库失败原因: " + error);
  4253. }
  4254. });
  4255. let doChangeLyric = false
  4256. if (item.filePath == this.currentSong?.filePath) {
  4257. if (this.lyricConStr !== this.lyricContent) {
  4258. doChangeLyric = true
  4259. }
  4260. } else if (this.lyricConStr !== this.tempLyricContent) {
  4261. doChangeLyric = true
  4262. }
  4263. if (doChangeLyric) {
  4264. let lyricPath = item.filePath.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  4265. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  4266. let isJiaMi = false;
  4267. let realLyricPath = lyricPath
  4268. if (FileUtil.accessSync(jiaMilyricPath)) {
  4269. isJiaMi = true
  4270. realLyricPath = jiaMilyricPath
  4271. console.info("onecold doEdit找到加密本地歌词 ");
  4272. } else {
  4273. isJiaMi = false
  4274. realLyricPath = lyricPath
  4275. console.info("onecold doEdit本地歌词 ");
  4276. }
  4277. this.saveDataToFile(this.lyricConStr, realLyricPath, isJiaMi)
  4278. }
  4279. }
  4280. updateLyricToDB() {
  4281. }
  4282. @Builder
  4283. editSheet(item: VideoItem) {
  4284. Scroll() {
  4285. Column() {
  4286. this.editDetail(item)
  4287. }
  4288. }
  4289. .width('100%')
  4290. .height('100%')
  4291. }
  4292. @Builder
  4293. editDetail(item: VideoItem) {
  4294. Column() {
  4295. if (item) {
  4296. Row() {
  4297. Stack() {
  4298. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') :
  4299. item.pixelMapPath)
  4300. .fillColor(this.themeColor)
  4301. .height(33)
  4302. .width(33)
  4303. .borderRadius('100%')
  4304. .clip(true)
  4305. .opacity(this.opacityItem)// 绑定透明度
  4306. .margin({ left: 20 })
  4307. }
  4308. .width('15%')
  4309. Row() {
  4310. Column() {
  4311. Text(item.name)
  4312. .fontSize(14)
  4313. .maxLines(1)
  4314. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4315. .animation({
  4316. duration: 555,
  4317. curve: 'Linear',
  4318. })
  4319. .fontColor(this.themeColor)
  4320. .margin({ left: 10 })
  4321. Row() {
  4322. Text(item.artist)
  4323. .fontSize(11)
  4324. .maxLines(1)
  4325. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4326. .padding({ top: 8 })
  4327. .fontColor(this.themeColor)
  4328. .margin({ left: 10 })
  4329. }
  4330. }
  4331. .height('100%')
  4332. .width(100)
  4333. .visibility(this.isDarkMode ? Visibility.None : Visibility.Visible)
  4334. .justifyContent(FlexAlign.Center)
  4335. .alignItems(HorizontalAlign.Start)
  4336. Button('本地封面')
  4337. .fontColor(Color.White)
  4338. .fontSize(12)
  4339. .height(38)
  4340. .width(88)
  4341. .backgroundColor(this.themeColor)
  4342. .stateEffect(true)
  4343. .margin({ right: 5, left: 12 })
  4344. .onClick(async () => {
  4345. this.goSelectImage(item)
  4346. })
  4347. Button('获取封面')
  4348. .fontColor(Color.White)
  4349. .fontSize(12)
  4350. .height(38)
  4351. .width(88)
  4352. .backgroundColor(this.themeColor)
  4353. .stateEffect(true)
  4354. .margin({ right: 12, left: 5 })
  4355. .onClick(async () => {
  4356. this.doSearchCover(item)
  4357. })
  4358. }
  4359. .height('100%')
  4360. .justifyContent(FlexAlign.Start)
  4361. .layoutWeight(1)
  4362. }
  4363. .width('100%')
  4364. .height(58)
  4365. Row() {
  4366. Text('标题:')
  4367. .fontSize(14)
  4368. .fontColor($r('app.color.text_color'))
  4369. .margin({ left: 22 })
  4370. TextInput({ text: item.name })
  4371. .height(40)
  4372. .maxLines(1)
  4373. .fontSize(14)
  4374. .layoutWeight(1)
  4375. .fontColor($r('app.color.text_color'))
  4376. .margin({ right: 20, left: 10 })
  4377. .onChange((val: string) => {
  4378. this.titleStr = val
  4379. })
  4380. }
  4381. .width('100%')
  4382. .margin({ top: 10, bottom: 10 })
  4383. .justifyContent(FlexAlign.Start)
  4384. Row() {
  4385. Text('艺术家:')
  4386. .fontSize(14)
  4387. .fontColor($r('app.color.text_color'))
  4388. .margin({ left: 22 })
  4389. TextInput({ text: item.artist })
  4390. .height(40)
  4391. .maxLines(1)
  4392. .fontSize(14)
  4393. .layoutWeight(1)
  4394. .fontColor($r('app.color.text_color'))
  4395. .margin({ right: 20, left: 10 })
  4396. .onChange((val: string) => {
  4397. this.artistStr = val
  4398. })
  4399. }
  4400. .width('100%')
  4401. .margin({ top: 10, bottom: 10 })
  4402. .justifyContent(FlexAlign.Start)
  4403. Row() {
  4404. Text('专辑名:')
  4405. .fontSize(14)
  4406. .fontColor($r('app.color.text_color'))
  4407. .margin({ left: 22 })
  4408. TextInput({ text: item.album })
  4409. .height(40)
  4410. .maxLines(1)
  4411. .fontSize(14)
  4412. .layoutWeight(1)
  4413. .fontColor($r('app.color.text_color'))
  4414. .margin({ right: 20, left: 10 })
  4415. .onChange((val: string) => {
  4416. this.ablumStr = val
  4417. })
  4418. }
  4419. .width('100%')
  4420. .margin({ top: 10, bottom: 10 })
  4421. .justifyContent(FlexAlign.Start)
  4422. Row() {
  4423. Text('歌词:')
  4424. .fontSize(14)
  4425. .fontColor($r('app.color.text_color'))
  4426. .margin({ left: 22 })
  4427. TextArea({ text: item.filePath === this.currentSong?.filePath ? this.lyricContent : this.tempLyricContent })
  4428. .type(TextAreaType.NORMAL)
  4429. .height(275)
  4430. .fontSize(14)
  4431. .layoutWeight(1)
  4432. .fontColor($r('app.color.text_color'))
  4433. .margin({ right: 20, left: 10 })
  4434. .onChange((val: string) => {
  4435. this.lyricConStr = val
  4436. })
  4437. }
  4438. .width('100%')
  4439. .margin({ top: 10, bottom: 10 })
  4440. .justifyContent(FlexAlign.Start)
  4441. Row() {
  4442. Button('保存')
  4443. .fontColor(Color.White)
  4444. .layoutWeight(1)
  4445. .height(50)
  4446. .width(100)
  4447. .backgroundColor(this.themeColor)
  4448. .stateEffect(true)
  4449. .margin({ right: 20, bottom: 20 })
  4450. .onClick(async () => {
  4451. this.doEdit(item)
  4452. })
  4453. Button('取消')
  4454. .fontColor(Color.White)
  4455. .layoutWeight(1)
  4456. .height(50)
  4457. .width(100)
  4458. .backgroundColor(this.themeColor)
  4459. .stateEffect(true)
  4460. .margin({ left: 20, bottom: 20 })
  4461. .onClick(async () => {
  4462. this.isShowEdit = false
  4463. })
  4464. }
  4465. .margin({
  4466. left: 38,
  4467. right: 38,
  4468. top: 10,
  4469. bottom: 10
  4470. })
  4471. .width(250)
  4472. .height(60)
  4473. }
  4474. }
  4475. .margin({ bottom: 20 })
  4476. }
  4477. @Builder
  4478. detailSheet(item:VideoItem) {
  4479. Scroll() {
  4480. Column() {
  4481. this.songDetail(item)
  4482. }
  4483. }
  4484. .width('100%')
  4485. .height('100%')
  4486. }
  4487. @Builder
  4488. songDetail(currentItem:VideoItem) {
  4489. Column() {
  4490. if (currentItem) {
  4491. Row() {
  4492. Stack() {
  4493. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.music_red') :
  4494. currentItem.pixelMapPath)
  4495. .fillColor(this.themeColor)
  4496. .height(33)
  4497. .width(33)
  4498. .borderRadius('100%')
  4499. .clip(true)
  4500. .opacity(this.opacityItem)// 绑定透明度
  4501. .margin({ left: 20 })
  4502. }
  4503. .width('15%')
  4504. Column() {
  4505. Column() {
  4506. Text(currentItem.name)
  4507. .fontSize(14)
  4508. .maxLines(1)
  4509. .animation({
  4510. duration: 555,
  4511. curve: 'Linear',
  4512. })
  4513. .fontColor($r('app.color.text_color'))
  4514. .margin({ left: 10 })
  4515. Row() {
  4516. Text(StrUtil.isEmpty(currentItem.artist) ? currentItem.cTime :
  4517. currentItem.artist + ' ' + currentItem?.album)
  4518. .fontSize(11)
  4519. .padding({ top: 8 })
  4520. .fontColor($r('app.color.text_color'))
  4521. .margin({ left: 10 })
  4522. }
  4523. }
  4524. .height('100%')
  4525. .width('100%')
  4526. .justifyContent(FlexAlign.Center)
  4527. .alignItems(HorizontalAlign.Start)
  4528. }
  4529. .height('100%')
  4530. }
  4531. .width('100%')
  4532. .height(58)
  4533. .justifyContent(FlexAlign.SpaceBetween)
  4534. Row() {
  4535. Text('歌手名:')
  4536. .fontSize(14)
  4537. .fontColor(Color.White)
  4538. .margin({ left: 22 })
  4539. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  4540. .fontSize(14)
  4541. .fontColor(Color.White)
  4542. .margin({ left: 10 })
  4543. .layoutWeight(1)
  4544. }
  4545. .width('100%')
  4546. .margin({ top: 10, bottom: 10 })
  4547. .justifyContent(FlexAlign.Start)
  4548. Row() {
  4549. Text('专辑名:')
  4550. .fontSize(14)
  4551. .fontColor(Color.White)
  4552. .margin({ left: 22 })
  4553. Text(currentItem?.album ?currentItem.album : '未知专辑')
  4554. .fontSize(14)
  4555. .margin({ left: 10 })
  4556. .fontColor(Color.White)
  4557. .layoutWeight(1)
  4558. }
  4559. .width('100%')
  4560. .margin({ top: 10, bottom: 10 })
  4561. .justifyContent(FlexAlign.Start)
  4562. Row() {
  4563. Text('时长:')
  4564. .fontSize(14)
  4565. .fontColor(Color.White)
  4566. .margin({ left: 22 })
  4567. Text(StrUtil.isEmpty(currentItem.duration)?
  4568. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  4569. .fontSize(14)
  4570. .margin({ left: 10 })
  4571. .fontColor(Color.White)
  4572. .layoutWeight(1)
  4573. }
  4574. .width('100%')
  4575. .margin({ top: 10, bottom: 10 })
  4576. .justifyContent(FlexAlign.Start)
  4577. Row() {
  4578. Text('采样率:')
  4579. .fontSize(14)
  4580. .fontColor(Color.White)
  4581. .margin({ left: 22 })
  4582. Text(Utility.convertToKHz(currentItem.sampleRate))
  4583. .fontSize(14)
  4584. .margin({ left: 10 })
  4585. .fontColor(Color.White)
  4586. .layoutWeight(1)
  4587. }
  4588. .width('100%')
  4589. .margin({ top: 10, bottom: 10 })
  4590. .justifyContent(FlexAlign.Start)
  4591. Row() {
  4592. Text('比特率:')
  4593. .fontSize(14)
  4594. .fontColor(Color.White)
  4595. .margin({ left: 22 })
  4596. Text(currentItem.bit_rate)
  4597. .fontSize(14)
  4598. .margin({ left: 10 })
  4599. .fontColor(Color.White)
  4600. .layoutWeight(1)
  4601. }
  4602. .width('100%')
  4603. .margin({ top: 10, bottom: 10 })
  4604. .justifyContent(FlexAlign.Start)
  4605. Row() {
  4606. Text('风格:')
  4607. .fontSize(14)
  4608. .fontColor(Color.White)
  4609. .margin({ left: 22 })
  4610. Text(currentItem.genre)
  4611. .fontSize(14)
  4612. .margin({ left: 10 })
  4613. .fontColor(Color.White)
  4614. .layoutWeight(1)
  4615. }
  4616. .width('100%')
  4617. .margin({ top: 10, bottom: 10 })
  4618. .justifyContent(FlexAlign.Start)
  4619. Row() {
  4620. Text('发行时间:')
  4621. .fontSize(14)
  4622. .fontColor(Color.White)
  4623. .margin({ left: 22 })
  4624. Text(currentItem.year)
  4625. .fontSize(14)
  4626. .margin({ left: 10 })
  4627. .fontColor(Color.White)
  4628. .layoutWeight(1)
  4629. }
  4630. .width('100%')
  4631. .margin({ top: 10, bottom: 10 })
  4632. .justifyContent(FlexAlign.Start)
  4633. Row() {
  4634. Text('质量评分:')
  4635. .fontSize(14)
  4636. .fontColor(Color.White)
  4637. .margin({ left: 22 })
  4638. Text(currentItem.probe_score+"")
  4639. .fontSize(14)
  4640. .margin({ left: 10 })
  4641. .fontColor(Color.White)
  4642. .layoutWeight(1)
  4643. }
  4644. .width('100%')
  4645. .margin({ top: 10, bottom: 10 })
  4646. .justifyContent(FlexAlign.Start)
  4647. Row() {
  4648. Text('音轨号:')
  4649. .fontSize(14)
  4650. .fontColor(Color.White)
  4651. .margin({ left: 22 })
  4652. Text(currentItem.track)
  4653. .fontSize(14)
  4654. .margin({ left: 10 })
  4655. .fontColor(Color.White)
  4656. .layoutWeight(1)
  4657. }
  4658. .width('100%')
  4659. .margin({ top: 10, bottom: 10 })
  4660. .justifyContent(FlexAlign.Start)
  4661. Row() {
  4662. Text('格式:')
  4663. .fontSize(14)
  4664. .fontColor(Color.White)
  4665. .margin({ left: 22 })
  4666. Text(Utility.formatMimeType(currentItem.mimeType))
  4667. .fontSize(14)
  4668. .margin({ left: 10 })
  4669. .fontColor(Color.White)
  4670. .layoutWeight(1)
  4671. }
  4672. .width('100%')
  4673. .margin({ top: 10, bottom: 10 })
  4674. .justifyContent(FlexAlign.Start)
  4675. Row() {
  4676. Text('播放次数:')
  4677. .fontSize(14)
  4678. .fontColor(Color.White)
  4679. .margin({ left: 22 })
  4680. Text(currentItem.playCount?.toString())
  4681. .fontSize(14)
  4682. .margin({ left: 10 })
  4683. .fontColor(Color.White)
  4684. .layoutWeight(1)
  4685. }
  4686. .width('100%')
  4687. .margin({ top: 10, bottom: 10 })
  4688. .justifyContent(FlexAlign.Start)
  4689. Row() {
  4690. Text('流数量:')
  4691. .fontSize(14)
  4692. .fontColor(Color.White)
  4693. .margin({ left: 22 })
  4694. Text(currentItem.nb_streams?.toString())
  4695. .fontSize(14)
  4696. .margin({ left: 10 })
  4697. .fontColor(Color.White)
  4698. .layoutWeight(1)
  4699. }
  4700. .width('100%')
  4701. .margin({ top: 10, bottom: 10 })
  4702. .justifyContent(FlexAlign.Start)
  4703. Row() {
  4704. Text('文件大小:')
  4705. .fontSize(14)
  4706. .fontColor(Color.White)
  4707. .margin({ left: 22 })
  4708. Text(currentItem.size)
  4709. .fontSize(14)
  4710. .margin({ left: 10 })
  4711. .fontColor(Color.White)
  4712. .layoutWeight(1)
  4713. }
  4714. .width('100%')
  4715. .margin({ top: 10, bottom: 10 })
  4716. .justifyContent(FlexAlign.Start)
  4717. Row() {
  4718. Text('文件名:')
  4719. .fontSize(14)
  4720. .fontColor(Color.White)
  4721. .margin({ left: 22 })
  4722. Text(currentItem.fileName)
  4723. .fontSize(14)
  4724. .margin({ left: 10 })
  4725. .fontColor(Color.White)
  4726. .layoutWeight(1)
  4727. }
  4728. .width('100%')
  4729. .margin({ top: 10, bottom: 10 })
  4730. .justifyContent(FlexAlign.Start)
  4731. Row() {
  4732. Text('修改时间:')
  4733. .fontSize(14)
  4734. .fontColor(Color.White)
  4735. .margin({ left: 22 })
  4736. Text(currentItem.cTime)
  4737. .fontSize(14)
  4738. .margin({ left: 10 })
  4739. .fontColor(Color.White)
  4740. .layoutWeight(1)
  4741. }
  4742. .width('100%')
  4743. .margin({ top: 10, bottom: 10 })
  4744. .justifyContent(FlexAlign.Start)
  4745. Row() {
  4746. Text('存放目录:')
  4747. .fontSize(14)
  4748. .fontColor(Color.White)
  4749. .margin({ left: 22 })
  4750. Text(currentItem.filePath)
  4751. .fontSize(12)
  4752. .margin({ left: 10 })
  4753. .fontColor(Color.White)
  4754. .layoutWeight(1)
  4755. }
  4756. .margin({ top: 10, bottom: 10 })
  4757. .width('100%')
  4758. .justifyContent(FlexAlign.Start)
  4759. }
  4760. }
  4761. .margin({ bottom: 20 })
  4762. }
  4763. //定时关闭布局
  4764. @Builder
  4765. TimeCloseSheet() {
  4766. Scroll() {
  4767. Column() {
  4768. this.TimeClose()
  4769. }
  4770. }
  4771. .width('100%')
  4772. .height('100%')
  4773. }
  4774. //倒计时关闭音乐,退出App功能实现。
  4775. @State selectedMinutes: number = 0 // 0表示未开启
  4776. @State remainingSeconds: number = 0
  4777. // 预设时间选项
  4778. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  4779. private formatTime(seconds: number): string {
  4780. const mins = Math.floor(seconds / 60)
  4781. const secs = seconds % 60
  4782. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  4783. }
  4784. // 开始倒计时
  4785. private handleTimeSelect(minutes: number) {
  4786. if (minutes === this.selectedMinutes) {
  4787. this.stopCountdown();
  4788. this.selectedMinutes = 0;
  4789. return;
  4790. }
  4791. this.selectedMinutes = minutes;
  4792. this.remainingSeconds = minutes * 60;
  4793. this.startCountdown(); // 新增调用
  4794. }
  4795. @Builder
  4796. TimeClose() {
  4797. Column() {
  4798. // 倒计时显示区域
  4799. Text(this.selectedMinutes > 0 ?
  4800. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  4801. "定时关闭未开启")
  4802. .fontSize(17)
  4803. .fontColor($r('app.color.text_color'))
  4804. .margin({ top: 2, bottom: 8 });
  4805. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  4806. ForEach(this.presetTimes, (minutes: number, index: number) => {
  4807. // 单行时间选项容器
  4808. Row() {
  4809. // 文字描述区域
  4810. Text(this.getDisplayText(minutes))
  4811. .fontSize(15)
  4812. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  4813. $r('app.color.text_color'))// 选中态颜色变化
  4814. .textAlign(TextAlign.Start)
  4815. .layoutWeight(1); // 占据剩余空间
  4816. // 复选框样式的选择器
  4817. Row() {
  4818. if (minutes === this.selectedMinutes) {
  4819. // 选中状态 - 带勾号的圆形复选框
  4820. Row() {
  4821. // 使用系统内置的勾号图标
  4822. Image($r('sys.media.ohos_ic_public_ok'))
  4823. .width(14)
  4824. .height(14)
  4825. .fillColor(Color.White)
  4826. }
  4827. .width(24)
  4828. .height(24)
  4829. .borderRadius(12)
  4830. .backgroundColor(this.themeColor)
  4831. .justifyContent(FlexAlign.Center)
  4832. .alignItems(VerticalAlign.Center)
  4833. } else {
  4834. // 未选中状态的圆形边框
  4835. Row()
  4836. .width(24)
  4837. .height(24)
  4838. .borderRadius(12)
  4839. .border({
  4840. width: 2,
  4841. color: $r('app.color.text_color'),
  4842. style: BorderStyle.Solid
  4843. })
  4844. .backgroundColor(Color.Transparent)
  4845. }
  4846. }
  4847. .width(24)
  4848. .height(24)
  4849. .margin({ left: 20 })
  4850. .justifyContent(FlexAlign.Center)
  4851. .alignItems(VerticalAlign.Center)
  4852. }
  4853. .width('100%')
  4854. .padding({
  4855. top: 18,
  4856. bottom: 18,
  4857. left: 18,
  4858. right: 18
  4859. })
  4860. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  4861. $r('app.color.bottom_control_background')) // 选中背景高亮
  4862. .borderRadius(12)
  4863. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  4864. .margin({ bottom: 18 })
  4865. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  4866. });
  4867. }
  4868. .width('100%')
  4869. .padding(16)
  4870. }
  4871. }
  4872. // 获取显示文本
  4873. private getDisplayText(minutes: number): string {
  4874. if (minutes === -1) {
  4875. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  4876. }
  4877. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  4878. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  4879. }
  4880. // 处理选择事件
  4881. private handleSelect(minutes: number): void {
  4882. if (minutes === -1) { // 自定义
  4883. // 弹出自定义时间对话框
  4884. DialogHelper.showTextInputDialog({
  4885. title: '自定义时间',
  4886. maskColor: Color.Transparent,
  4887. inputType: InputType.Number,
  4888. text: '',
  4889. onChange: (text) => {
  4890. console.error("onChange: " + text);
  4891. },
  4892. onAction: (action, dialogId, content) => {
  4893. if (action == DialogAction.TWO) {
  4894. const customMinutes = Number(content);
  4895. if (customMinutes > 0) {
  4896. this.handleTimeSelect(customMinutes); // 设置自定义时间
  4897. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  4898. }
  4899. }
  4900. }
  4901. });
  4902. } else {
  4903. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  4904. }
  4905. }
  4906. // 添加定时器引用
  4907. private timerId: number = -1;
  4908. // 启动/重置倒计时
  4909. private startCountdown() {
  4910. // 清除旧定时器
  4911. if (this.timerId !== -1) {
  4912. clearInterval(this.timerId);
  4913. }
  4914. // 创建新定时器
  4915. if (this.selectedMinutes > 0) {
  4916. this.timerId = setInterval(() => {
  4917. if (this.remainingSeconds === 15) {
  4918. this.showConfirmationDialog();
  4919. }
  4920. if (this.remainingSeconds > 0) {
  4921. this.remainingSeconds -= 1;
  4922. } else {
  4923. this.stopCountdown();
  4924. this.handleTimeout();
  4925. }
  4926. }, 1000);
  4927. }
  4928. }
  4929. // 15倒计时后再次提示显示确认是否关闭App对话框
  4930. private showConfirmationDialog() {
  4931. DialogHelper.showAlertDialog({
  4932. backgroundColor: $r('app.color.btn_green'),
  4933. title: '确认关闭',
  4934. maskColor: Color.Transparent,
  4935. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  4936. borderStyle: BorderStyle.Dashed,
  4937. primaryButton: '暂不关闭',
  4938. secondaryButton: '确定',
  4939. onAction: (action) => {
  4940. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  4941. this.stopCountdown();
  4942. this.selectedMinutes = 0
  4943. } else if (action == DialogAction.TWO) {
  4944. }
  4945. }
  4946. })
  4947. }
  4948. // 停止倒计时
  4949. private stopCountdown() {
  4950. if (this.timerId !== -1) {
  4951. clearInterval(this.timerId);
  4952. this.timerId = -1;
  4953. }
  4954. }
  4955. // 超时处理
  4956. private handleTimeout() {
  4957. // 执行播放器关闭逻辑
  4958. this.selectedMinutes = 0;
  4959. ToastUtil.showToast(" 定时关闭已完成");
  4960. this.stop(); // 假设存在的播放器实例
  4961. //退出APP
  4962. const mContext = getContext(this) as common.UIAbilityContext
  4963. mContext.terminateSelf();
  4964. AvSessionController.getInstance(true).unregisterSessionListener()
  4965. }
  4966. //倒计时关闭音乐,退出App功能实现结束。
  4967. //播放列表的拖动List 重新排序
  4968. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  4969. //左滑操作 移动文件 重命名 删除等操作
  4970. @Builder
  4971. sonButton(item: VideoItem, index: number, filePath: string) {
  4972. Row() {
  4973. //加入下一首播放
  4974. Button() {
  4975. Image($r('app.media.next_to_play'))
  4976. .fillColor(Color.White)
  4977. .width(20)
  4978. }
  4979. .width(40)
  4980. .height(40)
  4981. .type(ButtonType.Circle)
  4982. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  4983. .backgroundColor(this.themeColor)
  4984. .margin(5)
  4985. .onClick(() => {
  4986. this.addToNextPlay(item);
  4987. })
  4988. Button() {
  4989. Image($r('app.media.close'))
  4990. .fillColor(Color.White)
  4991. .width(20)
  4992. }
  4993. .width(40)
  4994. .height(40)
  4995. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  4996. .type(ButtonType.Circle)
  4997. .backgroundColor(this.themeColor)
  4998. .margin(5)
  4999. .onClick(() => {
  5000. this.songList.splice(Number(index), 1)
  5001. this.sonDataSource.pushArrayData(this.songList)
  5002. })
  5003. Button() {
  5004. Image($r('app.media.share2'))
  5005. .fillColor(Color.White)
  5006. .width(20)
  5007. }
  5008. .width(40)
  5009. .height(40)
  5010. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  5011. .type(ButtonType.Circle)
  5012. .backgroundColor(this.themeColor)
  5013. .margin(5)
  5014. .onClick(() => {
  5015. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  5016. })
  5017. }
  5018. }
  5019. itemMoveSon(index: number, newIndex: number): void {
  5020. if (newIndex < 0 || newIndex >= this.songList.length) {
  5021. return;
  5022. }
  5023. let tmp = this.songList.splice(index, 1);
  5024. this.songList.splice(newIndex, 0, tmp[0]);
  5025. this.sonDataSource.pushArrayData(this.songList)
  5026. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  5027. }
  5028. @Builder
  5029. PlayList() {
  5030. List({ scroller: this.playListScroller }) {
  5031. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  5032. ListItem() {
  5033. this.MusicItemSon(item, index)
  5034. }
  5035. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  5036. .animation({
  5037. duration: 666,
  5038. curve: 'ease-in-out' // 可选动画曲线
  5039. })
  5040. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
  5041. TransitionEffect.scale({ x: 0, y: 0 })))
  5042. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  5043. //拖动List关键代码开始
  5044. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  5045. .zIndex(this.dragItem === index ? 1 : 0)
  5046. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  5047. .gesture(
  5048. GestureGroup(GestureMode.Sequence,
  5049. LongPressGesture({ repeat: true })
  5050. .onAction((event?: GestureEvent) => {
  5051. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5052. this.scaleItem = index
  5053. })
  5054. })
  5055. .onActionEnd(() => {
  5056. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5057. this.scaleItem = -1
  5058. })
  5059. }),
  5060. PanGesture({ fingers: 1, direction: null, distance: 0 })
  5061. .onActionStart(() => {
  5062. this.dragItem = index // 记录当前拖动项索引
  5063. this.dragRefOffset = 0 // 重置偏移基准
  5064. })
  5065. .onActionUpdate((event: GestureEvent) => {
  5066. this.offsetY = event.offsetY - this.dragRefOffset;
  5067. this.neighborItem = -1;
  5068. let indexA = this.songList.indexOf(item);
  5069. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  5070. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  5071. let value: number = 0;
  5072. if (this.offsetY < 0) {
  5073. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  5074. this.neighborItem = indexA - 1;
  5075. this.neighborScale = 1 - value / 20;
  5076. } else if (this.offsetY > 0) {
  5077. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  5078. this.neighborItem = indexA + 1;
  5079. this.neighborScale = 1 - value / 20;
  5080. }
  5081. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  5082. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5083. this.offsetY -= this.ITEM_INTV;
  5084. this.dragRefOffset += this.ITEM_INTV;
  5085. this.itemMoveSon(indexA, indexA + 1);
  5086. });
  5087. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  5088. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5089. this.offsetY += this.ITEM_INTV;
  5090. this.dragRefOffset -= this.ITEM_INTV;
  5091. this.itemMoveSon(indexA, indexA - 1);
  5092. });
  5093. }
  5094. })
  5095. .onActionEnd((event: GestureEvent) => {
  5096. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5097. this.dragItem = -1
  5098. this.neighborItem = -1
  5099. })
  5100. animateTo({
  5101. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5102. }, () => {
  5103. this.scaleItem = -1
  5104. })
  5105. })
  5106. )
  5107. .onCancel(() => {
  5108. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5109. this.dragItem = -1
  5110. this.neighborItem = -1
  5111. })
  5112. animateTo({
  5113. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5114. }, () => {
  5115. this.scaleItem = -1
  5116. })
  5117. })
  5118. ) //拖动List关键代码结束
  5119. .onClick(() => {
  5120. this.doPlay(item, index, true)
  5121. })
  5122. }, (item: VideoItem) => item.filePath)
  5123. }
  5124. .width('100%')
  5125. .height('100%')
  5126. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  5127. // .animation({ duration: 500, curve: Curve.Ease }))
  5128. .cachedCount(10)
  5129. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5130. .gesture(PinchGesture({ fingers: 2 })
  5131. .onActionEnd((event: GestureEvent) => {
  5132. this.setlistTwoFingers()
  5133. })
  5134. .onActionUpdate(e => {
  5135. this.scaleValue = this.pinchValue * e.scale
  5136. })
  5137. .onActionStart(e => {
  5138. }))
  5139. .padding({
  5140. bottom: 0
  5141. })
  5142. }
  5143. @Builder
  5144. private MusicItemSon(item: VideoItem, index?: number) {
  5145. Button({ type: ButtonType.Normal, stateEffect: true }) {
  5146. Row() {
  5147. Stack() {
  5148. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  5149. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  5150. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  5151. .alt($r('app.media.music_red'))
  5152. .fillColor(this.themeColor)
  5153. .borderRadius('100%')
  5154. .clip(true)
  5155. .margin({ left: 20 })
  5156. }
  5157. .width('15%')
  5158. Column() {
  5159. Column() {
  5160. Text(item.name)
  5161. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5162. .fontColor(this.curIndex === index ? this.themeColor :
  5163. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  5164. .maxLines(1)
  5165. .margin({ left: this.twoFingerType == 3 ? 18 : 10 })
  5166. Row() {
  5167. Column(){
  5168. Text(item.md5Str?.includes('Lossless')?
  5169. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5170. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  5171. .padding({ top: 3,right:6,left:6,bottom:3 })
  5172. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5173. $r('app.color.text_color'))
  5174. .fontWeight(500)
  5175. .borderRadius(12)
  5176. .margin({ left: this.twoFingerType == 3 ? 12 : 10 })
  5177. .backgroundColor('#FFC107')
  5178. }
  5179. .padding({ top: 8 })
  5180. Text(StrUtil.isEmpty(item.artist) ? item.cTime : item.artist + ' ' + item?.album)
  5181. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5182. .padding({ top: 8 })
  5183. .fontColor(this.curIndex === index ? this.themeColor :
  5184. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  5185. .margin({ left: this.twoFingerType == 3 ? 5 : 3 })
  5186. Blank()
  5187. Text(item.size)
  5188. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5189. .padding({ top: 8 })
  5190. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  5191. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  5192. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  5193. .margin({ left: 10 })
  5194. }
  5195. }
  5196. .height('100%')
  5197. .width('100%')
  5198. .justifyContent(FlexAlign.Center)
  5199. .alignItems(HorizontalAlign.Start)
  5200. }
  5201. .height('100%')
  5202. .width('65%')
  5203. Column() {
  5204. ImageAnimator()
  5205. .images(this.imagesF)// 动画数组
  5206. .duration(1000)// 持续
  5207. .state(this.animationState)// 动画状态
  5208. .fillMode(FillMode.Forwards)
  5209. .width(18)
  5210. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  5211. Visibility.None)
  5212. .height(18)
  5213. .iterations(-1) // 播放次数
  5214. }
  5215. .width('20%')
  5216. }
  5217. }
  5218. .backgroundColor(Color.Transparent)
  5219. .width('100%')
  5220. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  5221. .shadow(this.scaleItem === index ? {
  5222. radius: 70,
  5223. color: '#15000000',
  5224. offsetX: 0,
  5225. offsetY: 0
  5226. } :
  5227. {
  5228. radius: 0,
  5229. color: '#15000000',
  5230. offsetX: 0,
  5231. offsetY: 0
  5232. })
  5233. .animation({ curve: Curve.Sharp, duration: 300 })
  5234. }
  5235. @Builder
  5236. MusicPlayBuilder() {
  5237. Column() {
  5238. this.IjkMusicPlayerView()
  5239. }
  5240. .height('100%')
  5241. .width('100%')
  5242. .onDisAppear(() => {
  5243. this.translateY = 0;
  5244. })
  5245. .translate({ y: this.translateY })
  5246. .gesture(
  5247. PanGesture(this.panOption)
  5248. .onActionUpdate((event?: GestureEvent) => {
  5249. if (event) {
  5250. // 只允许向下滑动,向上滑动时限制为0
  5251. this.translateY = Math.max(0, event.offsetY);
  5252. }
  5253. })
  5254. .onActionEnd((event?: GestureEvent) => {
  5255. // 使用更低的阈值和滑动速度判断
  5256. const minDistance = 100; // 最小滑动距离 100vp
  5257. const minVelocity = 500; // 最小滑动速度
  5258. // 获取滑动速度(如果可用)
  5259. const velocity = event?.velocityY || 0;
  5260. // 判断是否应该关闭:距离足够 或者 速度足够快
  5261. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  5262. if (shouldClose) {
  5263. // 添加关闭动画
  5264. this.getUIContext().animateTo({
  5265. duration: 300,
  5266. curve: Curve.Smooth
  5267. }, () => {
  5268. this.isShowPlay = false;
  5269. this.translateY = 0;
  5270. })
  5271. } else {
  5272. // 回弹动画
  5273. this.getUIContext().animateTo({
  5274. duration: 300,
  5275. curve: Curve.Smooth
  5276. }, () => {
  5277. this.translateY = 0;
  5278. })
  5279. }
  5280. })
  5281. )
  5282. }
  5283. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  5284. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  5285. HeightBreakpoint.HEIGHT_LG;
  5286. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  5287. @State topBarHeight: number = 50
  5288. @State barOpacity: number = 1
  5289. @State barBottomOpacity: number = 1
  5290. private hideDone: boolean = false;
  5291. @State currentYOffset: number = 0;
  5292. @State bottomBarHeight: number = 60;
  5293. private isHiding: boolean = false;
  5294. //是否是Pura X外屏,或者小屏幕
  5295. isPuraWP() {
  5296. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  5297. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  5298. }
  5299. //是否是Pura X外屏,或者小屏幕,手机横屏
  5300. isCoverOpacity() {
  5301. if (this.isPuraWP()) {
  5302. return true
  5303. }
  5304. if (this.isPhoneLan()) {
  5305. return true
  5306. }
  5307. if (deviceInfo.marketName.includes('Pura X')
  5308. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  5309. return true
  5310. }
  5311. return false
  5312. }
  5313. //是不是手机横屏
  5314. isPhoneLan() {
  5315. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  5316. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  5317. LogUtil.info('hicar isPhoneLan width= ' + this.windowWidth);
  5318. LogUtil.info('hicar isPhoneLan height= ' + this.windowHeight);
  5319. LogUtil.info(`twocold hicarWindow size: ${this.windowWidth}x${this.windowHeight}, this.isHiCarStatus: ${this.isHiCarStatus}`);
  5320. LogUtil.info(`twocold hicar Window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall: ${this.isHiCarSmall()}`);
  5321. if (this.isHiCarStatus) {
  5322. return false
  5323. }
  5324. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  5325. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  5326. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  5327. return true
  5328. }
  5329. return false
  5330. }
  5331. //是不是1920x720的hicar的屏幕分辨率
  5332. isHiCarKuanBianPing(){
  5333. const hiCarAspectRatios: HiCarAspectRatio[] = [
  5334. { ratio: 1920 / 720, name: "1920x720" },
  5335. ];
  5336. const currentRatio: number = this.windowWidth / this.windowHeight;
  5337. const RATIO_TOLERANCE: number = 0.18; // 宽高比容差
  5338. LogUtil.info('twocold currentRatio = ' + currentRatio)
  5339. for (const hiCarRatio of hiCarAspectRatios) {
  5340. LogUtil.info('twocold hiCarRatio= ' + hiCarRatio.ratio)
  5341. LogUtil.info('twocold Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  5342. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  5343. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  5344. return true&&this.isHiCarStatus;
  5345. }
  5346. }
  5347. return false;
  5348. }
  5349. //是不是hicar的屏幕分辨率
  5350. isHiCarSmall() {
  5351. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  5352. return false
  5353. const hiCarAspectRatios: HiCarAspectRatio[] = [
  5354. { ratio: 800 / 480, name: "800x480" },
  5355. { ratio: 1280 / 720, name: "1280x720" },
  5356. { ratio: 1920 / 720, name: "1920x720" },
  5357. ];
  5358. const currentRatio: number = this.windowWidth / this.windowHeight;
  5359. const RATIO_TOLERANCE: number = 0.18; // 宽高比容差
  5360. LogUtil.info('twocold currentRatio = ' + currentRatio)
  5361. for (const hiCarRatio of hiCarAspectRatios) {
  5362. LogUtil.info('twocold hiCarRatio= ' + hiCarRatio.ratio)
  5363. LogUtil.info('twocold Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  5364. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  5365. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  5366. return true&&this.isHiCarStatus;
  5367. }
  5368. }
  5369. return false;
  5370. }
  5371. isHiCar() {
  5372. return this.isHiCarStatus;
  5373. // const hiCarAspectRatios: HiCarAspectRatio[] = [
  5374. // { ratio: 800 / 480, name: "800x480" },
  5375. // { ratio: 762 / 752, name: "762x752" },
  5376. // { ratio: 968 / 1280, name: "968x1280" },
  5377. // { ratio: 1200 / 1200, name: "1200x1200" },
  5378. // { ratio: 1280 / 720, name: "1280x720" },
  5379. // { ratio: 1920 / 720, name: "1920x720" },
  5380. // { ratio: 1920 / 1080, name: "1920x1080" }
  5381. // ];
  5382. // const currentRatio: number = this.windowWidth / this.windowHeight;
  5383. // const RATIO_TOLERANCE: number = 0.18; // 宽高比容差
  5384. // LogUtil.info('twocold currentRatio = ' + currentRatio)
  5385. //
  5386. // for (const hiCarRatio of hiCarAspectRatios) {
  5387. // LogUtil.info('twocold hiCarRatio= ' + hiCarRatio.ratio)
  5388. // LogUtil.info('twocold Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  5389. // if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  5390. // // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  5391. // return true&&this.isHiCarStatus;
  5392. // }
  5393. // }
  5394. //
  5395. // return false;
  5396. }
  5397. //是不是正常的手机竖屏
  5398. isPhonePortrait() {
  5399. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  5400. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  5401. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  5402. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  5403. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  5404. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  5405. return true
  5406. }
  5407. return false
  5408. }
  5409. @State showSpeedDialog: boolean = false
  5410. @State longPressSpeed: number = 3 //长按默认倍数
  5411. @Builder
  5412. SpeedDialog() {
  5413. Stack() {
  5414. Column() {
  5415. Text('已切换至' + this.longPressSpeed + '倍速播放')
  5416. .fontColor(Color.White)
  5417. .visibility(Visibility.Hidden)
  5418. }
  5419. .backgroundColor(Color.Black)
  5420. .borderRadius(20)
  5421. .padding({
  5422. top: 10,
  5423. right: 20,
  5424. left: 15,
  5425. bottom: 20
  5426. })
  5427. .opacity(0.6)
  5428. Text('已切换至' + this.longPressSpeed + '倍速播放')
  5429. .fontColor(Color.White)
  5430. }
  5431. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  5432. .zIndex(5)
  5433. .margin({ top: 80 })
  5434. }
  5435. @Builder
  5436. IjkMusicPlayerView() {
  5437. Column() {
  5438. Column() {
  5439. Column() {
  5440. //播放标题
  5441. Column() {
  5442. this.PlayTitle()
  5443. }
  5444. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  5445. .width('100%')
  5446. .margin({ top: 0 })
  5447. .height(PlayConstants.HEIGHT)
  5448. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  5449. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  5450. if (this.showSpeedDialog) {
  5451. this.SpeedDialog()
  5452. }
  5453. Stack() {
  5454. //手势拖动快进
  5455. Column()
  5456. .width(CommonConstants.FULL_PERCENT)
  5457. .height('100%')
  5458. .gesture(
  5459. GestureGroup(GestureMode.Parallel,
  5460. // 长按屏幕倍数播放
  5461. LongPressGesture({ repeat: true })
  5462. .onAction(() => {
  5463. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  5464. this.showSpeedDialog = true;
  5465. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  5466. }
  5467. })
  5468. .onActionEnd(() => {
  5469. this.showSpeedDialog = false;
  5470. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  5471. }),
  5472. //双击屏幕暂停或者播放
  5473. TapGesture({ count: 2 })
  5474. .onAction((event: GestureEvent) => {
  5475. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  5476. ToastUtil.showToast('已暂停')
  5477. }
  5478. this.playOrPause()
  5479. })
  5480. )
  5481. )
  5482. }
  5483. .height('65%')
  5484. Swiper() {
  5485. this.CoverInfo()
  5486. this.PlayerLyrics()
  5487. }
  5488. .onChange((index: number) => {
  5489. this.currentSwiperIndex = index
  5490. })
  5491. .indicator(false)
  5492. // .indicator(this.currentBreakpoint === BreakpointTypeEnum.SM ?
  5493. // new DotIndicator()
  5494. // .top(this.isCoverOpacity()?0:10)
  5495. //
  5496. // .selectedColor($r('app.color.select_swiper'))
  5497. // .color($r('app.color.slider_track')):false
  5498. // )
  5499. .displayCount(new BreakpointType({
  5500. sm: 1,
  5501. md: 2,
  5502. lg: 2,
  5503. xl: 2,
  5504. xxl: 2
  5505. }).getValue(this.currentBreakpoint))
  5506. .clip(false)
  5507. .loop(false)
  5508. .autoPlay(false)
  5509. // .interval(8000)
  5510. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  5511. .height('100%')
  5512. .hitTestBehavior(HitTestMode.Transparent)
  5513. Image($r('app.media.icon_replay'))
  5514. .objectFit(ImageFit.Auto)
  5515. .width('120px')
  5516. .height('120px')
  5517. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  5518. .border({ width: 0 })
  5519. .visibility(Visibility.None)
  5520. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  5521. .onClick(() => {
  5522. this.startPlayOrResumePlay();
  5523. })
  5524. }
  5525. .width(CommonConstants.FULL_PERCENT)
  5526. .height(CommonConstants.FULL_PERCENT)
  5527. .justifyContent(FlexAlign.End)
  5528. }
  5529. .justifyContent(FlexAlign.End)
  5530. .margin({ bottom: 8 })
  5531. }
  5532. // .backgroundImage(this.imageLabelBg)
  5533. .backgroundImage(this.isPuraWP() && this.currentSwiperIndex === 0 ?
  5534. (StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover) : this.imageLabelBg)
  5535. .backgroundImageSize(this.isPuraWP() ? { width: '100%' } : { height: '150%', width: '100%' })
  5536. // .backgroundImagePosition(Alignment.Center)
  5537. .animation({
  5538. duration: 666,
  5539. curve: 'ease-in-out' // 可选动画曲线
  5540. })
  5541. .backgroundBlurStyle(this.isPuraWP() && this.currentSwiperIndex === 0 ? BlurStyle.NONE :
  5542. BlurStyle.BACKGROUND_ULTRA_THICK)
  5543. .hitTestBehavior(HitTestMode.Transparent)
  5544. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  5545. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  5546. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  5547. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  5548. .onClick(() => {
  5549. // this.startAutoHide()
  5550. this.is_auto_hide_progress = false
  5551. setTimeout(() => {
  5552. this.is_auto_hide_progress = true
  5553. }, 6000)
  5554. })
  5555. }
  5556. @State progressValue: number = 0;
  5557. @State currentTime: string = "00:00";
  5558. @State totalTime: string = "00:00";
  5559. @State loadingVisible: Visibility = Visibility.None;
  5560. @State replayVisible: Visibility = Visibility.None;
  5561. @State slideEnable: boolean = false;
  5562. @State aspRatio: number = 0.5;
  5563. @State mContext: object | undefined = undefined;
  5564. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  5565. @State mFirst: boolean = true;
  5566. @State mDestroyPage: boolean = false;
  5567. @State playSpeed: number = 1;
  5568. @State oldSeconds: number = 0;
  5569. @State isSeekTo: boolean = false;
  5570. @State isCurrentTime: boolean = false;
  5571. @State videoWidth: string = '100%';
  5572. @State videoHeight: string = '100%';
  5573. @State initAspectRatio: number = 1;
  5574. @State videoAspectRatio: number = this.initAspectRatio;
  5575. private videoUrl: string = '';
  5576. private last: number = 0;
  5577. @State videoParentAspectRatio: number = this.initAspectRatio;
  5578. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  5579. @State CONTROL_PlayStatus: number = PlayStatus.INIT;
  5580. @State PROGRESS_MAX_VALUE: number = 100;
  5581. @State updateProgressTimer: number = 0;
  5582. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  5583. @State name: string = '';
  5584. // @State loop: boolean = false;
  5585. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  5586. @State multiple: string = '1.0X';
  5587. xcomponentController: XComponentController = new XComponentController()
  5588. private panOptionBright: PanGestureOptions =
  5589. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  5590. private panOptionVolume: PanGestureOptions =
  5591. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  5592. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  5593. //手势的音量控制和亮度控制
  5594. private positionX: number = PlayConstants.POSITION_X;
  5595. private positionY: number = PlayConstants.POSITION_Y;
  5596. private windowClass: window.Window = globalThis.windowClass
  5597. @State volume: number = 0.3;
  5598. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  5599. @State bright: number = PlayConstants.BRIGHT;
  5600. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  5601. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  5602. @State screenWidth: number = 0
  5603. @State screenHeight: number = 0
  5604. @State statusBarHeight: number = 0
  5605. @State isYesFull: boolean = false
  5606. private seekValue: number = 0
  5607. @State isVideoLock: boolean = false; // Whether the video playback is locked
  5608. eventHub = getContext().eventHub;
  5609. //投播组件
  5610. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  5611. private avSessionWidgetListener: AvSessionWidgetListener = AvSessionWidgetListener.getInstance();
  5612. private castController: avSession.AVCastController | undefined = undefined;
  5613. @State isCastPlaying: boolean = false;
  5614. @State currentTime2: number = 0;
  5615. @State currentStringTime: string = '00:00';
  5616. @State duration: number = 0;
  5617. @State isReady: boolean = false;
  5618. @State durationTime: number = 0;
  5619. @State durationStringTime: string = '00:00';
  5620. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  5621. // @State isPlaying: boolean = false;
  5622. private castSeek: boolean = false;
  5623. private castItem: avSession.AVQueueItem | undefined = undefined;
  5624. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  5625. @State imageLabel: PixelMap | Resource = CommonConstants.musicBgList[0];
  5626. @State imageLabelBg: PixelMap | Resource = CommonConstants.musicBgList[0];
  5627. @State rotateAngle2: number = 0
  5628. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  5629. @State cover: string | undefined = '';
  5630. @State artist: string | undefined = ''
  5631. // 1.初始化controller
  5632. private lyricController: LyricController = new LyricController()
  5633. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  5634. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  5635. private parser = new LyricParser()
  5636. @State randomColor: string = 'rgb(0,0,0)'
  5637. @State randomShakenX: number = 0
  5638. @State randomShakenY: number = 0
  5639. @State lyricTextSize: number = 24
  5640. @State lyricContent: string = ''
  5641. @State isDebug: boolean = false
  5642. @State isHightLightCenter: boolean = true
  5643. /**
  5644. * 初始化歌词加载与展示逻辑
  5645. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  5646. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  5647. * @param isApi2 是否使用API2获取歌词(可选)
  5648. *
  5649. * 主要流程:
  5650. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  5651. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  5652. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  5653. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  5654. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  5655. * 6. 解析失败或读取失败时,清空歌词显示。
  5656. *
  5657. * 注意事项:
  5658. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  5659. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  5660. * - 歌词内容解析后通过lyricController驱动UI渲染。
  5661. */
  5662. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean) {
  5663. if (StrUtil.isEmpty(lyricPath)) {
  5664. return
  5665. }
  5666. this.initPipLyricSetting()
  5667. this.lyricControllerSingle
  5668. .setTextSize(15)
  5669. .setCacheSize(4)
  5670. .setTextColor("#FFFFFF")
  5671. .setHighlightColor("#FFFFFF")
  5672. .setHighlightScale(1.2)
  5673. .setEmptyHint("")
  5674. .setAlignMode('center')
  5675. .setAnimationDuration(500)
  5676. .setSingleLine(true)
  5677. this.lyricContent = ''
  5678. this.lyricController
  5679. .setTextSize(this.currentLyricSize)
  5680. .setCacheSize(4)
  5681. .setTextColor("#DDDDDD")
  5682. .setHighlightColor("#FFFFFF")
  5683. .setEmptyHint("")
  5684. .setAnimationDuration(1000)
  5685. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  5686. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  5687. this.setBlurDegree(this.blurDegree, false)
  5688. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  5689. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  5690. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  5691. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  5692. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  5693. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  5694. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  5695. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  5696. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  5697. this.lyricController.setTextWeight(this.lyricTextWeight)
  5698. this.showSingleLyric = false
  5699. this.timeOffset = 0
  5700. this.lyricController.setLyric(null)
  5701. this.lyricControllerSingle.setLyric(null)
  5702. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  5703. console.log("onecold lyricPath =" + lyricPath)
  5704. let neiqianLrc = ''
  5705. let lyContent = this.currentSong?.lyricContent
  5706. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  5707. neiqianLrc = lyContent
  5708. }else{
  5709. neiqianLrc = LrcParser.getLyrics(this.videoUrl); //获取内嵌歌词
  5710. }
  5711. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast) {
  5712. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  5713. //赋值给this.lyricContent,播控中心才可以显示歌词
  5714. this.lyricContent = neiqianLrc
  5715. // 将文件内容按行分割成字符串数组
  5716. let lines = neiqianLrc.split('\n').map(line => line.trim());
  5717. // 3.解析歌词
  5718. let lyric = this.parser.parse(lines);
  5719. // 4.设置歌词
  5720. this.lyricController.setLyric(lyric);
  5721. this.lyricControllerXF.setLyric(lyric)
  5722. this.lyricControllerSingle.setLyric(lyric)
  5723. return
  5724. }
  5725. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  5726. && !Utility.isVideoByExtension(this.videoUrl))) {
  5727. if (this.currentSong !== undefined) {
  5728. // ToastUtil.showShort('正在为你搜索在线歌词!')
  5729. //判断是不是赞助会员,是会员的话才开启歌词功能
  5730. // if (!this.isDebug) {
  5731. // if (!Utility.isNoble()) {
  5732. // LogUtil.debug("onecold 不是赞助会员")
  5733. // return
  5734. // }
  5735. // if(!Utility.isPassInstallTime(33)){
  5736. // LogUtil.debug("onecold not pass time")
  5737. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  5738. // return
  5739. // }
  5740. // }
  5741. let artist = this.currentSong?.artist
  5742. if (artist === undefined) {
  5743. artist = ''
  5744. }
  5745. if (isApi2 === undefined) {
  5746. isApi2 = false
  5747. }
  5748. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  5749. // LogUtil.debug("onecold res =" + res)
  5750. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  5751. if (StrUtil.isNotEmpty(res)) {
  5752. this.lyricContent = res
  5753. let lines = res.split('\n').map(line => line.trim());
  5754. // 3.解析歌词
  5755. let lyric = this.parser.parse(lines);
  5756. // 4.设置歌词
  5757. this.lyricController.setLyric(lyric);
  5758. this.lyricControllerXF.setLyric(lyric)
  5759. this.lyricControllerSingle.setLyric(lyric)
  5760. this.showSingleLyric = true
  5761. // 4.保存歌词文件lyric到本地
  5762. this.saveDataToFile(res, jiaMilyricPath, true)
  5763. } else {
  5764. this.lyricController.setLyric(null)
  5765. this.lyricControllerXF.setLyric(null)
  5766. this.lyricControllerSingle.setLyric(null)
  5767. if (isOnLineAndToast) {
  5768. ToastUtil.showShort('未获取到歌词!')
  5769. }
  5770. }
  5771. } else {
  5772. this.lyricController.setLyric(null)
  5773. this.lyricControllerXF.setLyric(null)
  5774. this.lyricControllerSingle.setLyric(null)
  5775. if (isOnLineAndToast) {
  5776. ToastUtil.showShort('未获取到歌词!')
  5777. }
  5778. }
  5779. })
  5780. } else {
  5781. this.lyricController.setLyric(null)
  5782. this.lyricControllerXF.setLyric(null)
  5783. this.lyricControllerSingle.setLyric(null)
  5784. if (isOnLineAndToast) {
  5785. ToastUtil.showShort('未获取到歌词!')
  5786. }
  5787. }
  5788. return
  5789. }
  5790. try {
  5791. let isJiaMi = false;
  5792. let realLyricPath = lyricPath
  5793. if (FileUtil.accessSync(jiaMilyricPath)) {
  5794. isJiaMi = true
  5795. realLyricPath = jiaMilyricPath
  5796. console.info("onecold 找到加密本地歌词 ");
  5797. } else {
  5798. isJiaMi = false
  5799. realLyricPath = lyricPath
  5800. console.info("onecold 找到本地歌词 ");
  5801. }
  5802. // 3.读取文件内容并指定编码为 UTF-8
  5803. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_WRITE);
  5804. let arrayBuffer = new ArrayBuffer(4096);
  5805. fs.read(file.fd, arrayBuffer)
  5806. .then((readLen: number) => {
  5807. console.info("read file data succeed");
  5808. // let buf = buffer.from(arrayBuffer, 0, readLen);
  5809. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  5810. // 检查 buf 是否为空
  5811. if (buf.length === 0) {
  5812. throw new Error("Buffer is empty after reading the file");
  5813. }
  5814. try {
  5815. // 检测文件编码
  5816. // let detectedEncoding = chardet.detect(buf);
  5817. // console.info("onecoldT Detected encoding: " + detectedEncoding);
  5818. let detectedEncoding = this.detect(arrayBuffer)
  5819. console.info("onecoldT Detected encoding: " + detectedEncoding);
  5820. // 使用检测到的编码解码,解决中文乱码问题
  5821. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  5822. console.info("onecoldT Detected textDecoder: " + textDecoder);
  5823. let fileContent = textDecoder.decode(buf);
  5824. console.info(`onecoldT The content of file1: ${fileContent}`);
  5825. //解密
  5826. if (isJiaMi) {
  5827. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  5828. }
  5829. console.info(`onecold The content of file2: ${fileContent}`);
  5830. this.lyricContent = fileContent
  5831. // 将文件内容按行分割成字符串数组
  5832. let lines = fileContent.split('\n').map(line => line.trim());
  5833. console.info(`onecold The content of file: ${fileContent}`);
  5834. // 3.解析歌词
  5835. let lyric = this.parser.parse(lines);
  5836. // 4.设置歌词
  5837. this.lyricController.setLyric(lyric);
  5838. this.lyricControllerXF.setLyric(lyric)
  5839. this.lyricControllerSingle.setLyric(lyric)
  5840. this.showSingleLyric = true
  5841. console.info(`The content of file: ${fileContent}`);
  5842. } catch (chardetError) {
  5843. console.error("chardet.detect failed with error: " + chardetError.message);
  5844. this.lyricController.setLyric(null);
  5845. this.lyricControllerXF.setLyric(null)
  5846. this.lyricControllerSingle.setLyric(null)
  5847. }
  5848. })
  5849. .catch((err: BusinessError) => {
  5850. this.lyricController.setLyric(null)
  5851. this.lyricControllerXF.setLyric(null)
  5852. this.lyricControllerSingle.setLyric(null)
  5853. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  5854. })
  5855. .catch((err: Error) => {
  5856. this.lyricController.setLyric(null)
  5857. this.lyricControllerXF.setLyric(null)
  5858. this.lyricControllerSingle.setLyric(null)
  5859. console.error("read file 2 data failed with error message: " + err.message);
  5860. })
  5861. .finally(() => {
  5862. fs.closeSync(file);
  5863. });
  5864. } catch (error) {
  5865. this.lyricController.setLyric(null)
  5866. this.lyricControllerSingle.setLyric(null)
  5867. this.lyricControllerXF.setLyric(null)
  5868. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  5869. }
  5870. }
  5871. detect(data: ArrayBuffer): string {
  5872. //创建检测对象
  5873. let detector: UniversalDetector = new UniversalDetector();
  5874. // 传入检测数据并实时判断编码格式
  5875. detector.handleData(data, 0, data.byteLength);
  5876. // 标记检测数据 读取结束
  5877. detector.dataEnd();
  5878. // 获取检测结果
  5879. let detected: string = detector.getDetectedCharset();
  5880. // 释放资源
  5881. detector.reset();
  5882. return detected;
  5883. }
  5884. //初始化悬浮歌词的自定义设置
  5885. initPipLyricSetting() {
  5886. this.lyricControllerXF
  5887. .setTextSize(this.currentLyricSize)
  5888. .setCacheSize(4)
  5889. .setTextColor("#DDDDDD")
  5890. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  5891. .setEmptyHint("")
  5892. .setAnimationDuration(1000)
  5893. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  5894. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  5895. this.setBlurDegree(this.blurDegreePip, true)
  5896. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  5897. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  5898. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  5899. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  5900. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  5901. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  5902. this.lyricControllerXF.setHightLightCenter(true)
  5903. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  5904. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  5905. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  5906. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  5907. if (this.pipBgIndex === 0) {
  5908. if (this.cover) {
  5909. this.pipBg = this.cover
  5910. } else {
  5911. this.pipBg = this.imageColor
  5912. }
  5913. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  5914. }
  5915. }
  5916. //根据item返回歌词内容
  5917. async getLyricContent(item: VideoItem): Promise<string> {
  5918. try {
  5919. let filePath = item.filePath;
  5920. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  5921. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  5922. let isJiaMi = false;
  5923. let realLyricPath = lyricPath;
  5924. if (FileUtil.accessSync(jiaMilyricPath)) {
  5925. isJiaMi = true;
  5926. realLyricPath = jiaMilyricPath;
  5927. console.info("onecold 找到加密本地歌词");
  5928. } else {
  5929. console.info("onecold 找到本地歌词");
  5930. }
  5931. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_WRITE);
  5932. let arrayBuffer = new ArrayBuffer(4096);
  5933. const readLen = await fs.read(file.fd, arrayBuffer);
  5934. console.info("read file data succeed");
  5935. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  5936. if (buf.length === 0) {
  5937. throw new Error("Buffer is empty after reading the file");
  5938. }
  5939. // let detectedEncoding = chardet.detect(buf);
  5940. let detectedEncoding = this.detect(arrayBuffer)
  5941. console.info("Detected encoding: " + detectedEncoding);
  5942. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  5943. let fileContent = textDecoder.decode(buf);
  5944. console.info(`onecold The content of file1: ${fileContent}`);
  5945. if (isJiaMi) {
  5946. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  5947. }
  5948. console.info(`onecold The content of file2: ${fileContent}`);
  5949. fs.closeSync(file);
  5950. return fileContent;
  5951. } catch (error) {
  5952. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  5953. return '';
  5954. }
  5955. }
  5956. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  5957. if (StrUtil.isEmpty(filePath)) {
  5958. return
  5959. }
  5960. try {
  5961. //将content进行加密
  5962. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  5963. let lyricContent = ''
  5964. if (isJiaMi) {
  5965. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  5966. } else {
  5967. lyricContent = content
  5968. }
  5969. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  5970. // 清空文件内容
  5971. await fileIo.truncate(file.fd, 0);
  5972. await fileIo.write(file.fd, lyricContent);
  5973. await fileIo.close(file);
  5974. console.log('onecold lyric file Data saved successfully.');
  5975. } catch (error) {
  5976. console.error('onecold lyric file Failed to save data:', error);
  5977. }
  5978. }
  5979. /**
  5980. * Get largest proportion color of an image.
  5981. */
  5982. getImageColor() {
  5983. if (!this.context) {
  5984. return;
  5985. }
  5986. let bg = Utility.getMusisBg()
  5987. this.imageLabel = bg
  5988. ColorConversion.setSysBarLightBackground(true);
  5989. this.context.resourceManager.getMediaContent(bg)
  5990. .then((value: Uint8Array) => {
  5991. let buffer = value.buffer as ArrayBuffer;
  5992. image.createImageSource(buffer).createPixelMap().then((pixelMap) => {
  5993. effectKit.createColorPicker(pixelMap, (error, colorPicker) => {
  5994. if (error) {
  5995. Logger.error('Failed to create color picker.');
  5996. } else {
  5997. let color = colorPicker.getLargestProportionColor();
  5998. let colorArr = ColorConversion.dealColor(color.red, color.green, color.blue);
  5999. this.imageColor = `rgba(${colorArr[0]}, ${colorArr[1]}, ${colorArr[2]}, 1)`;
  6000. }
  6001. })
  6002. let headFilter = effectKit.createEffect(pixelMap);
  6003. if (headFilter !== null) {
  6004. headFilter.blur(15);
  6005. headFilter.getEffectPixelMap().then((value) => {
  6006. this.imageLabelBg = value;
  6007. })
  6008. }
  6009. })
  6010. .catch((error: BusinessError) => {
  6011. Logger.error(`${error.code} + ${error.message}`)
  6012. })
  6013. })
  6014. .catch((error: BusinessError) => {
  6015. Logger.error(`${error.code} + ${error.message}`)
  6016. })
  6017. }
  6018. setImageColor(cover: string) {
  6019. if (!this.context) {
  6020. return;
  6021. }
  6022. if (cover === undefined) {
  6023. return;
  6024. }
  6025. ImageUtil.imagePathToPixelMap(cover).then((value) => {
  6026. let headFilter = effectKit.createEffect(value);
  6027. if (headFilter !== null) {
  6028. headFilter.blur(15);
  6029. headFilter.getEffectPixelMap().then((value) => {
  6030. this.imageLabelBg = value;
  6031. })
  6032. }
  6033. }).catch((error: BusinessError) => {
  6034. Logger.error(`${error.code} + ${error.message}`)
  6035. })
  6036. }
  6037. setImageColor2(cover: string) {
  6038. if (!this.context) {
  6039. return;
  6040. }
  6041. if (cover === undefined) {
  6042. return;
  6043. }
  6044. LogUtils.getInstance().LOGI("setImageColor2--> cover ==" + cover);
  6045. ImageUtils.getImageDealData(getContext(this), cover, this.videoUrl).then((data) => {
  6046. this.imageColor = data.imageColor;
  6047. if (data.blurPixelMap) {
  6048. this.imageLabelBg = data.blurPixelMap;
  6049. }
  6050. })
  6051. }
  6052. // 定义开始旋转的方法
  6053. // 定时器用于一百毫秒执行一次旋转角度
  6054. @State timer: number = 0
  6055. @State rotateAngle: number = 0
  6056. //封面旋转动画
  6057. animationRoFun() {
  6058. if (this.isPlaying && !this.isCoverRectangle) {
  6059. this.timer = setInterval(() => {
  6060. this.rotateAngle += 1
  6061. }, 100)
  6062. this.startRotation()
  6063. } else {
  6064. clearInterval(this.timer)
  6065. this.stopRotation()
  6066. }
  6067. }
  6068. // 定义开始旋转的方法
  6069. startRotation() {
  6070. if (this.isPlaying) {
  6071. animateTo({
  6072. duration: 777,
  6073. iterations: 1,
  6074. curve: Curve.Linear
  6075. }, () => {
  6076. this.rotateAngle2 = 0
  6077. })
  6078. }
  6079. }
  6080. // 回调,暂停和播放按钮回调,下一首和上一首
  6081. playChange() {
  6082. // if(this.isCoverRectangle){
  6083. // return
  6084. // }
  6085. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  6086. this.setIsPlaying(true)
  6087. this.animationState = AnimationStatus.Running
  6088. } else {
  6089. this.setIsPlaying(false)
  6090. this.animationState = AnimationStatus.Paused
  6091. }
  6092. }
  6093. // 定义停止旋转的方法
  6094. stopRotation() {
  6095. if (this.isCoverRectangle) {
  6096. this.rotateAngle = 0
  6097. } else {
  6098. //唱针以左上角为点选择逆时针40度
  6099. animateTo({
  6100. duration: 1000,
  6101. curve: Curve.Linear,
  6102. iterations: 1,
  6103. }, () => {
  6104. this.rotateAngle2 = -40;
  6105. });
  6106. }
  6107. }
  6108. @Builder
  6109. private LyricsTopItem() {
  6110. Row() {
  6111. Stack() {
  6112. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  6113. .height(55)
  6114. .width(55)
  6115. .alt(this.imageLabel)
  6116. .borderRadius(8)
  6117. .clickEffect({ level: ClickEffectLevel.HEAVY })
  6118. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  6119. }
  6120. .width('18%')
  6121. Column() {
  6122. Column() {
  6123. Text(this.name)
  6124. .fontSize(16)
  6125. .maxLines(1)
  6126. .fontWeight(FontWeight.Bolder)
  6127. .fontColor(this.currentLyricColor)
  6128. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  6129. Row() {
  6130. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  6131. .fontSize(13)
  6132. .fontWeight(FontWeight.Bold)
  6133. .padding({ top: 8 })
  6134. .fontColor(this.currentLyricColor)
  6135. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  6136. Blank()
  6137. }
  6138. }
  6139. .height('100%')
  6140. .width('100%')
  6141. .justifyContent(FlexAlign.Center)
  6142. .alignItems(HorizontalAlign.Start)
  6143. }
  6144. .height('100%')
  6145. .width('65%')
  6146. Column() {
  6147. Image($r('app.media.lyric'))
  6148. .width(28)
  6149. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6150. .margin({ right: 30 })
  6151. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6152. .onClick(() => {
  6153. this.isLyricSetting = !this.isLyricSetting;
  6154. })
  6155. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  6156. height: this.isCoverOpacity() ? '95%' : '88%',
  6157. dragBar: true,
  6158. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6159. showClose: true,
  6160. blurStyle: BlurStyle.Thin,
  6161. backgroundColor: Color.Transparent,
  6162. // title: { title: $r('app.string.lyric_setting') }
  6163. })
  6164. }
  6165. .width('18%')
  6166. }
  6167. .width('82%')
  6168. .height(58)
  6169. .justifyContent(FlexAlign.SpaceBetween)
  6170. }
  6171. //歌词显示
  6172. @Builder
  6173. PlayerLyrics() {
  6174. Column() {
  6175. Column() {
  6176. this.LyricsTopItem()
  6177. }
  6178. .height(this.isPuraWP() ? 15 : 58)
  6179. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  6180. Visibility.None : Visibility.Visible)
  6181. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  6182. .width("100%")
  6183. Column() {
  6184. LyricView2({
  6185. controller: this.lyricController,
  6186. enableSeek: true,
  6187. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  6188. seekLineColor: "#80ffffff", // 滑动定位线颜色
  6189. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  6190. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  6191. if (!this.isPlaying) {
  6192. this.startPlayOrResumePlay()
  6193. } else {
  6194. this.isSeekTo = true;
  6195. this.mDestroyPage = false;
  6196. this.showLoadIng();
  6197. this.seekTo(position + "");
  6198. this.isSeekTo = false;
  6199. }
  6200. return true
  6201. }
  6202. })
  6203. .width("100%")
  6204. .layoutWeight(1)
  6205. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  6206. if (this.isPhoneLan()) {
  6207. Column() {
  6208. this.playCenterView()
  6209. }
  6210. .margin({ bottom: 20, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  6211. }
  6212. }
  6213. .position({
  6214. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  6215. (this.isPuraWP() ? 58 : 99)
  6216. })
  6217. .justifyContent(FlexAlign.Center)
  6218. .height(this.isCoverOpacity() ? '95%' : '80%')
  6219. }
  6220. }
  6221. @Builder
  6222. SingleLyricView() {
  6223. Column() {
  6224. Column() {
  6225. LyricView2({
  6226. controller: this.lyricControllerSingle,
  6227. enableSeek: false,
  6228. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  6229. seekLineColor: "#80ffffff", // 滑动定位线颜色
  6230. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  6231. })
  6232. }
  6233. .height(66)
  6234. .margin({ bottom: 20 })
  6235. }
  6236. }
  6237. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  6238. @Builder
  6239. BottomControl() {
  6240. Column() {
  6241. //播放 暂停,下一首,上一首
  6242. this.playCenterView()
  6243. //播放进度条
  6244. this.playProgressView()
  6245. }
  6246. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 100) }) // 将 固定在底部
  6247. }
  6248. //播放控制上一首 下一首 暂停和播放
  6249. @Builder
  6250. playCenterView() {
  6251. Row() {
  6252. Row({ space: 20 }) {
  6253. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6254. //更多功能
  6255. Image($r('app.media.menu'))
  6256. .width(24)
  6257. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  6258. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  6259. height: this.isCoverOpacity() ? '95%' : '93%',
  6260. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6261. dragBar: true,
  6262. showClose: true,
  6263. blurStyle: BlurStyle.Thin,
  6264. backgroundColor: Color.Transparent,
  6265. })
  6266. }
  6267. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6268. .backgroundColor(Color.Transparent)
  6269. .onClick(() => {
  6270. this.isShowMoreView = !this.isShowMoreView;
  6271. })
  6272. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6273. Image($r('app.media.ic_previous'))
  6274. .width(33)
  6275. .clickEffect({ level: ClickEffectLevel.HEAVY })
  6276. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6277. }
  6278. .onClick(async () => {
  6279. this.playPrevious()
  6280. })
  6281. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6282. .backgroundColor(Color.Transparent)
  6283. .margin({ left: 5 })
  6284. }
  6285. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6286. Column() {
  6287. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  6288. (this.isCircleBtn ? $r('app.media.hm_pause') : $r('app.media.ic_public_play'))
  6289. : (this.isCircleBtn ? $r('app.media.hm_play2') : $r('app.media.ic_public_pause')))
  6290. .width(this.isPhoneLan() ? 48 : 60)
  6291. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6292. .fillColor(Color.White)
  6293. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6294. .onClick(async () => {
  6295. this.playOrPause()
  6296. })
  6297. }
  6298. }
  6299. .backgroundColor(Color.Transparent)
  6300. .layoutWeight(1)
  6301. .margin({ left: 38, right: 38 })
  6302. Row({ space: 20 }) {
  6303. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6304. Image($r('app.media.ic_next'))
  6305. .width(33)
  6306. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6307. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6308. .onClick(() => {
  6309. this.playNext();
  6310. })
  6311. }
  6312. .backgroundColor(Color.Transparent)
  6313. .margin({ right: 5 })
  6314. .width(33)
  6315. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6316. //添加或取消收藏
  6317. Image(Utility.getIsFav(this.favList, this.currentSong) ?
  6318. $r('app.media.add_fac_light') : $r('app.media.add_fac'))
  6319. .width(24)
  6320. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  6321. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6322. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6323. .onClick(async () => {
  6324. if (this.currentSong) {
  6325. this.doFav(this.currentSong)
  6326. }
  6327. })
  6328. }
  6329. .backgroundColor(Color.Transparent)
  6330. .width(24)
  6331. }
  6332. // .margin({ left: 5 })
  6333. }
  6334. .width('100%')
  6335. .margin({ left: 10, right: 10, bottom: this.isCoverOpacity() ? 0 : 20 })
  6336. .justifyContent(FlexAlign.Center)
  6337. }
  6338. //播放进度条
  6339. @Builder
  6340. playProgressView() {
  6341. Row() {
  6342. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6343. Column() {
  6344. if (this.playType === 0) {
  6345. Image($r('app.media.loop'))
  6346. .width($r('app.float.control_image_width'))
  6347. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6348. } else if (this.playType === 1) {
  6349. Image($r('app.media.single'))
  6350. .width($r('app.float.control_image_width'))
  6351. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6352. } else if (this.playType === 2) {
  6353. Image($r('app.media.normal_play'))
  6354. .width($r('app.float.control_image_width'))
  6355. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6356. } else if (this.playType === 3) {
  6357. Image($r('app.media.random'))
  6358. .width($r('app.float.control_image_width'))
  6359. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6360. }
  6361. }
  6362. }
  6363. .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  6364. .animation({
  6365. duration: 666,
  6366. curve: 'ease-in-out' // 可选动画曲线
  6367. })
  6368. .backgroundColor(Color.Transparent)
  6369. .margin({ left: 20, right: 10 })
  6370. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6371. .onClick(async () => {
  6372. this.setLoopMode()
  6373. })
  6374. Text(this.currentTime)
  6375. .fontSize($r('app.float.slider_font_size'))
  6376. .fontColor(Color.White)
  6377. .margin(3)
  6378. Slider({
  6379. value: this.progressValue,
  6380. min: 0,
  6381. max: this.PROGRESS_MAX_VALUE,
  6382. step: 1,
  6383. style: SliderStyle.OutSet
  6384. })
  6385. .width('600px')
  6386. .blockColor('rgba(255,255,255,1)')
  6387. .trackColor('rgba(255,255,255,0.3)')
  6388. .selectedColor(Color.White)
  6389. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  6390. .layoutWeight(1)
  6391. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  6392. .showSteps(false)
  6393. .showTips(true)
  6394. .enabled(this.slideEnable)
  6395. .onChange((value: number, mode: SliderChangeMode) => {
  6396. // if (mode == 2) {
  6397. this.isSeekTo = true;
  6398. this.mDestroyPage = false;
  6399. this.showLoadIng();
  6400. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  6401. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  6402. this.seekTo(seekValue + "");
  6403. // this.setProgress()
  6404. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  6405. this.isSeekTo = false;
  6406. // }
  6407. })
  6408. Text(this.totalTime)
  6409. .fontSize($r('app.float.slider_font_size'))
  6410. .fontColor(Color.White)
  6411. .margin(3)
  6412. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  6413. //播放列表
  6414. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6415. Image($r('app.media.hm_playlist'))
  6416. .width($r('app.float.control_image_width'))
  6417. .fillColor(Color.White)
  6418. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6419. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  6420. height: '95%',
  6421. dragBar: true,
  6422. showClose: true,
  6423. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6424. blurStyle: BlurStyle.Thin,
  6425. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  6426. title: {
  6427. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  6428. + `(${this.songList.length}首)`
  6429. }
  6430. })
  6431. }
  6432. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  6433. .animation({
  6434. duration: 666,
  6435. curve: 'ease-in-out' // 可选动画曲线
  6436. })
  6437. .backgroundColor(Color.Transparent)
  6438. .margin({ right: 20, left: 10 })
  6439. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6440. .onClick(() => {
  6441. this.isShowSheetView = !this.isShowSheetView;
  6442. if (this.isPlayListBgGrass) {
  6443. this.isFrontWhite = true
  6444. } else {
  6445. this.isFrontWhite = false
  6446. }
  6447. setTimeout(() => {
  6448. this.playListScroller.scrollToIndex(this.curIndex, true, ScrollAlign.CENTER)
  6449. }, 123)
  6450. })
  6451. }
  6452. //x5的竖屏模式需要99%
  6453. .width(this.isPhonePortrait() ? '93.4%'
  6454. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  6455. .height(this.isPhoneLan() ? 25 : 33)
  6456. .animation({
  6457. duration: 666,
  6458. curve: 'ease-in-out' // 可选动画曲线
  6459. })
  6460. }
  6461. isBigScreen() {
  6462. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  6463. return true
  6464. }
  6465. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  6466. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  6467. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  6468. return false
  6469. } else {
  6470. return true
  6471. }
  6472. return false
  6473. }
  6474. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  6475. @State isCoverRectangle: boolean = false
  6476. @State isCoverTop: boolean = true
  6477. // 添加控制缩放的状态变量
  6478. @State scaleValueImage: number = 1
  6479. @Builder
  6480. CoverInfo() {
  6481. Column() {
  6482. //如果是方形,判断是不是封面在顶部,如果不是顶部,显示musicNameInfo, 如果是圆形显示musicNameInfo
  6483. if (this.isCoverRectangle) {
  6484. if (!this.isCoverTop) {
  6485. this.musicNameInfo(false)
  6486. }
  6487. } else {
  6488. this.musicNameInfo(false)
  6489. }
  6490. Stack() {
  6491. // 唱片旋转效果
  6492. Image($r('app.media.ic_music_disc'))
  6493. .width(245)
  6494. .height(245)
  6495. .margin({ right: 20, left: 20 })
  6496. .aspectRatio(1)
  6497. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  6498. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  6499. .borderRadius('100%')
  6500. .align(Alignment.Center)
  6501. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  6502. .rotate({
  6503. angle: this.rotateAngle,
  6504. centerX: "50%",
  6505. centerY: "50%",
  6506. })
  6507. .animation({
  6508. duration: 100,
  6509. curve: Curve.Linear
  6510. })
  6511. .shadow({
  6512. radius: 30,
  6513. color: this.randomColor
  6514. })
  6515. Column() {
  6516. if (this.isCoverTop && !this.isCoverOpacity() && this.isCoverRectangle) {
  6517. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)// .height(this.isCoverOpacity() ? 250 : this.isCoverRectangle ? 320 : 162)
  6518. .width(this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '86%')
  6519. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  6520. .alt(this.imageLabel)
  6521. .margin({ right: 8, left: 8, top: 8 })
  6522. .aspectRatio(1)
  6523. .opacity(this.opacityValueImage)
  6524. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  6525. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  6526. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  6527. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  6528. .align(Alignment.Center)//
  6529. .clip(true)
  6530. .rotate({
  6531. x: 0,
  6532. y: 0,
  6533. z: 1,
  6534. angle: this.rotateAngle
  6535. })
  6536. .onClick(() => {
  6537. this.getImageColor()
  6538. })
  6539. this.musicNameInfo(false)
  6540. } else {
  6541. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  6542. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:220):(this.isCoverOpacity() ? 250 : this.isCoverRectangle ? 320 : 162))
  6543. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  6544. .alt(this.imageLabel)
  6545. .margin({ right: 20, left: 20 })
  6546. .aspectRatio(1)
  6547. .opacity(this.opacityValueImage)
  6548. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  6549. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  6550. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  6551. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  6552. .align(Alignment.Center)//
  6553. .clip(true)
  6554. .rotate({
  6555. x: 0,
  6556. y: 0,
  6557. z: 1,
  6558. angle: this.rotateAngle
  6559. })
  6560. .onClick(() => {
  6561. this.getImageColor()
  6562. })
  6563. if (this.isPhoneLan()) {
  6564. Text(this.name)
  6565. .fontSize(18)
  6566. .fontWeight(FontWeight.Bold)
  6567. .margin({ top: 13 })
  6568. .textOverflow({ overflow: TextOverflow.Ellipsis })
  6569. .maxLines(1)
  6570. .width('99%')
  6571. .textAlign(TextAlign.Center)
  6572. .fontColor(Color.White)
  6573. }
  6574. }
  6575. }
  6576. // 唱针以左上角为点选择逆时针40度
  6577. Image($r('app.media.ic_music_cover_hand'))
  6578. .height(130)
  6579. .margin({ bottom: 220, top: 0 })
  6580. .align(Alignment.Top)
  6581. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  6582. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  6583. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  6584. Column({ space: 8 }) {
  6585. Text(this.name)
  6586. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  6587. .fontWeight(FontWeight.Bold)
  6588. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6589. .maxLines(1)
  6590. .width('48%')
  6591. .textAlign(TextAlign.Center)
  6592. .fontColor(Color.White)
  6593. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  6594. Text(this.artist)
  6595. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  6596. .fontColor(Color.White)
  6597. .fontWeight(FontWeight.Bold)
  6598. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  6599. }
  6600. .justifyContent(FlexAlign.Start)
  6601. .zIndex(1)
  6602. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  6603. }
  6604. .margin({
  6605. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  6606. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  6607. top: this.isCoverOpacity() ? 0 : 20
  6608. })
  6609. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  6610. this.SingleLyricView()
  6611. }
  6612. if (this.isPhoneLan()) {
  6613. Column() {
  6614. this.playProgressView()
  6615. }
  6616. .position({ left: 40, bottom: 48 })
  6617. } else {
  6618. this.BottomControl()
  6619. }
  6620. }
  6621. .width(CommonConstants.FULL_PERCENT)
  6622. .clip(true)
  6623. }
  6624. @Builder
  6625. private musicNameInfo(isHidden: boolean) {
  6626. Column({ space: 8 }) {
  6627. Text(this.name)
  6628. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22)
  6629. .fontWeight(FontWeight.Bold)
  6630. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6631. .maxLines(1)
  6632. .width('99%')
  6633. .textAlign(TextAlign.Center)
  6634. .fontColor(Color.White)
  6635. Text(this.artist + ' ' + this.currentSong?.album)
  6636. .fontSize(this.isCoverOpacity() ? 12 : 15)
  6637. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6638. .fontColor(Color.White)
  6639. .textAlign(TextAlign.Center)
  6640. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  6641. .width('99%')
  6642. .maxLines(1)
  6643. }
  6644. .margin({ top: this.isCoverOpacity() ? 20 : isHidden ? 40 : 20 })
  6645. .zIndex(1)
  6646. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  6647. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  6648. }
  6649. @Builder
  6650. private PlayTitle() {
  6651. Row() {
  6652. Row() {
  6653. Image($r('app.media.ic_back_down'))
  6654. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  6655. .hitTestBehavior(HitTestMode.Transparent)
  6656. Text(this.name + ' ' + this.artist)
  6657. .fontColor(Color.White)
  6658. .fontSize($r('app.float.title_font_size'))
  6659. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6660. .maxLines(1)
  6661. .visibility(Visibility.None)
  6662. .margin({ left: 2, right: 30 })
  6663. }
  6664. .layoutWeight(1)
  6665. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6666. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  6667. .onClick(() => {
  6668. this.isShowPlay = false;
  6669. })
  6670. Column() {
  6671. AVCastPicker({
  6672. normalColor: Color.White,
  6673. onStateChange: this.onStateVastChange
  6674. })
  6675. .width(24)
  6676. .height(24)
  6677. }
  6678. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  6679. }
  6680. .width(PlayConstants.ROW_WIDTH)
  6681. }
  6682. @Builder
  6683. lyricSettingSheet(isPip: boolean) {
  6684. Scroll() {
  6685. this.lyricSetting(isPip)
  6686. }
  6687. .width('100%')
  6688. .height('100%')
  6689. }
  6690. @Builder
  6691. lyricSetting(isPip: boolean) {
  6692. Column() {
  6693. // 时间调节模块
  6694. if (!isPip) {
  6695. this.BuildTimeControls()
  6696. }
  6697. // 字号控制模块
  6698. this.BuildFontControls(isPip)
  6699. }
  6700. }
  6701. // 歌词时间偏移状态
  6702. @State timeOffset: number = 0.0
  6703. @State currentLyricColor: string = '#FFFFFF'
  6704. @State currentLyricColorPip: string = '#FFFFFF'
  6705. @State currentHighLightLyricColor: string = '#FF4081'
  6706. @State currentHighLightLyricColorPip: string = '#FF4081'
  6707. // 歌词字号状态
  6708. @State currentLyricSize: number = 20
  6709. @State currentLyricSizePip: number = 20
  6710. // 高亮歌词放大倍数
  6711. @State currentHightLyricSize: number = 1.2
  6712. @State currentHightLyricSizePip: number = 1.2
  6713. @State currentLyricLineSpace: number = 10
  6714. @State currentLyricLineSpacePip: number = 10
  6715. @State currentLyricAlignMode: number = 1
  6716. @State currentLyricAlignModePip: number = 1
  6717. @State blurDegree: number = 2
  6718. @State blurDegreePip: number = 2
  6719. @State isShowSelectColor: boolean = false
  6720. @State isShowHLSelectColor: boolean = false
  6721. @State isShowPipBgSelectColor: boolean = false
  6722. @State pipLyWidth: number = 330
  6723. @State pipLyHeight: number = 120
  6724. // 构建颜色选择器
  6725. @Builder
  6726. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  6727. Row({ space: 10 }) {
  6728. HSBColorPicker({
  6729. color: '#FFFFFF',
  6730. radius: 8,
  6731. layout: HSBColorPickerLayout.COLUMN,
  6732. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  6733. '#fa7105'],
  6734. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  6735. this.changeLyricColor(value, isPip, isBGPip)
  6736. })
  6737. .height(250)
  6738. .layoutWeight(1)
  6739. .padding(25)
  6740. }
  6741. .width('66%')
  6742. }
  6743. @State isOpenPip: boolean = false
  6744. @State pipBgIndex: number = 0
  6745. // 构建字号控制器
  6746. @Builder
  6747. BuildFontControls(isPip: boolean) {
  6748. Column() {
  6749. if (isPip) {
  6750. Column() {
  6751. Row() {
  6752. Text('悬浮歌词')
  6753. .margin({ left: 18 })
  6754. .fontSize(15)
  6755. .fontColor(Color.White)
  6756. .fontWeight(480)
  6757. .layoutWeight(1)
  6758. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  6759. .selectedColor(this.themeColor)
  6760. .switchPointColor(Color.White)
  6761. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6762. .margin({ right: 18 })
  6763. .onChange((checked: boolean) => {
  6764. this.isOpenPip = checked;
  6765. if (this.isOpenPip) {
  6766. this.startPip()
  6767. } else {
  6768. this.stopPip()
  6769. }
  6770. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  6771. })
  6772. .width(50)
  6773. .height(30);
  6774. }
  6775. .height(55)
  6776. }
  6777. .backgroundColor(Color.Transparent)
  6778. .borderRadius(15)
  6779. .margin({
  6780. left: 30,
  6781. right: 30,
  6782. top: 0,
  6783. bottom: 20
  6784. })
  6785. .padding(0)
  6786. .border({
  6787. color: Color.White,
  6788. width: 1.8
  6789. })
  6790. }
  6791. Row() {
  6792. Text(`歌词居中:`)
  6793. .fontSize(14)
  6794. .fontColor(Color.White)
  6795. .margin({ left: 2 })
  6796. Row() {
  6797. ForEach(['居中', '居左'], (size: string, index: number) => {
  6798. Button(size)
  6799. .width(60)
  6800. .height(28)
  6801. .fontSize(12)
  6802. .fontColor('#FFFFFF')
  6803. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  6804. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  6805. .border({
  6806. color: (!isPip && this.currentLyricAlignMode === index) ||
  6807. (isPip && this.currentLyricAlignModePip === index) ?
  6808. '#007DFF' : '#DDDDDD',
  6809. width: 1.8
  6810. })
  6811. .onClick(() => {
  6812. this.setLyricAlignMode(index, isPip)
  6813. })
  6814. .margin({ left: 10, right: 8 })
  6815. })
  6816. }
  6817. .width('76%')
  6818. Blank()
  6819. }
  6820. .margin({
  6821. top: 10,
  6822. bottom: 10,
  6823. right: 20,
  6824. left: 20
  6825. })
  6826. if (isPip) {
  6827. Row() {
  6828. Text(`悬浮背景:`)
  6829. .fontSize(14)
  6830. .fontColor(Color.White)
  6831. Select([
  6832. { value: CommonConstants.PIP_LYRIC_BG[0] },
  6833. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  6834. .font({ size: 13, weight: FontWeight.Medium })
  6835. .fontColor(Color.White)
  6836. .margin({ left: 10 })
  6837. .selected(this.pipBgIndex)
  6838. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  6839. .onSelect(async (_index: number, text?: string | undefined) => {
  6840. this.pipBgIndex = _index
  6841. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  6842. if (this.pipBgIndex === 0) {
  6843. if (this.cover) {
  6844. this.pipBg = this.cover
  6845. } else {
  6846. this.pipBg = this.imageColor
  6847. }
  6848. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  6849. } else {
  6850. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  6851. }
  6852. })
  6853. Column() {
  6854. }
  6855. .backgroundColor(this.pipBg)
  6856. .margin({ left: 10, right: 10 })
  6857. .borderRadius(20)
  6858. .height(28)
  6859. .width(28)
  6860. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6861. Row() {
  6862. SymbolGlyph($r('sys.symbol.paintbrush'))
  6863. .fontColor([Color.White])
  6864. .effectStrategy(1)
  6865. Text(`选择颜色`)
  6866. .fontSize(13)
  6867. .margin({ left: 10 })
  6868. .fontColor(Color.White)
  6869. }
  6870. }
  6871. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  6872. .backgroundColor(Color.Transparent)
  6873. .border({
  6874. color: '#FFFFFF',
  6875. radius: 20,
  6876. width: 1.8
  6877. })
  6878. .height(36)
  6879. .width(110)
  6880. .onClick(() => {
  6881. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  6882. })
  6883. .bindPopup(this.isShowPipBgSelectColor, {
  6884. builder: this.SelectColor(false, isPip, true),
  6885. placement: Placement.Top,
  6886. mask: { color: '#33000000' },
  6887. enableArrow: false, //是否显示箭头
  6888. showInSubWindow: false,
  6889. onStateChange: (e) => {
  6890. if (!e.isVisible) {
  6891. this.isShowPipBgSelectColor = false
  6892. }
  6893. }
  6894. })
  6895. }
  6896. .width('76%')
  6897. .margin({ bottom: 5, right: 45, left: 20 })
  6898. }
  6899. if (!isPip) {
  6900. Row() {
  6901. Text(`高亮居中:`)
  6902. .fontSize(14)
  6903. .fontColor(Color.White)
  6904. Column() {
  6905. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  6906. .selectedColor(this.themeColor)
  6907. .switchPointColor(Color.White)
  6908. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6909. .onChange((checked: boolean) => {
  6910. this.isHightLightCenter = checked;
  6911. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  6912. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  6913. })
  6914. .width(50)
  6915. .height(30)
  6916. .alignSelf(ItemAlign.Start)
  6917. .margin({ left: 12 })
  6918. Blank()
  6919. }
  6920. .width('76%')
  6921. }
  6922. .margin({
  6923. left: 20,
  6924. right: 15,
  6925. top: 10,
  6926. bottom: 10
  6927. })
  6928. }
  6929. Row() {
  6930. Text(`歌词颜色:`)
  6931. .fontSize(14)
  6932. .fontColor(Color.White)
  6933. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  6934. .fontSize(15)
  6935. .fontColor(Color.White)
  6936. .margin({ left: 12, right: 12 })
  6937. Column() {
  6938. }
  6939. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  6940. .margin({ right: 12 })
  6941. .borderRadius(20)
  6942. .height(28)
  6943. .width(28)
  6944. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6945. Row() {
  6946. SymbolGlyph($r('sys.symbol.paintbrush'))
  6947. .fontColor([Color.White])
  6948. .effectStrategy(1)
  6949. Text(`选择颜色`)
  6950. .fontSize(13)
  6951. .margin({ left: 10 })
  6952. .fontColor(Color.White)
  6953. }
  6954. }
  6955. .backgroundColor(Color.Transparent)
  6956. .border({
  6957. color: '#FFFFFF',
  6958. radius: 20,
  6959. width: 1.8
  6960. })
  6961. .height(36)
  6962. .width(110)
  6963. .onClick(() => {
  6964. this.isShowSelectColor = !this.isShowSelectColor
  6965. })
  6966. .bindPopup(this.isShowSelectColor, {
  6967. builder: this.SelectColor(false, isPip),
  6968. placement: Placement.Top,
  6969. mask: { color: '#33000000' },
  6970. enableArrow: false, //是否显示箭头
  6971. showInSubWindow: false,
  6972. onStateChange: (e) => {
  6973. if (!e.isVisible) {
  6974. this.isShowSelectColor = false
  6975. }
  6976. }
  6977. })
  6978. }
  6979. .width('76%')
  6980. .margin({
  6981. top: 10,
  6982. bottom: 10,
  6983. right: 45,
  6984. left: 20
  6985. })
  6986. Row() {
  6987. Text(`高亮颜色:`)
  6988. .fontSize(14)
  6989. .fontColor(Color.White)
  6990. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  6991. .fontSize(15)
  6992. .fontColor(Color.White)
  6993. .margin({ left: 12, right: 12 })
  6994. Column() {
  6995. }
  6996. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  6997. .margin({ right: 12 })
  6998. .borderRadius(20)
  6999. .height(28)
  7000. .width(28)
  7001. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7002. Row() {
  7003. SymbolGlyph($r('sys.symbol.paintbrush'))
  7004. .fontColor([Color.White])
  7005. .effectStrategy(1)
  7006. Text(`选择颜色`)
  7007. .fontSize(13)
  7008. .margin({ left: 10 })
  7009. .fontColor(Color.White)
  7010. }
  7011. }
  7012. .backgroundColor(Color.Transparent)
  7013. .border({
  7014. color: '#FFFFFF',
  7015. radius: 20,
  7016. width: 1.8
  7017. })
  7018. .height(36)
  7019. .width(110)
  7020. .onClick(() => {
  7021. this.isShowHLSelectColor = !this.isShowHLSelectColor
  7022. })
  7023. .bindPopup(this.isShowHLSelectColor, {
  7024. builder: this.SelectColor(true, isPip),
  7025. placement: Placement.Top,
  7026. mask: { color: '#33000000' },
  7027. enableArrow: false, //是否显示箭头
  7028. showInSubWindow: false,
  7029. onStateChange: (e) => {
  7030. if (!e.isVisible) {
  7031. this.isShowHLSelectColor = false
  7032. }
  7033. }
  7034. })
  7035. }
  7036. .width('76%')
  7037. .margin({
  7038. top: 10,
  7039. bottom: 10,
  7040. right: 45,
  7041. left: 20
  7042. })
  7043. if (isPip) {
  7044. Row() {
  7045. Text(`显示宽度:`)
  7046. .fontSize(14)
  7047. .fontColor(Color.White)
  7048. Slider({
  7049. value: this.pipLyWidth,
  7050. min: 10,
  7051. max: 800,
  7052. step: 1,
  7053. style: SliderStyle.OutSet
  7054. })
  7055. .blockColor(this.themeColor)
  7056. .trackColor($r('app.color.speed_text_color'))
  7057. .selectedColor(Color.White)
  7058. .trackThickness(6)
  7059. .onChange((value: number) => {
  7060. this.pipLyWidth = value
  7061. if (this.pipController) {
  7062. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  7063. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  7064. }
  7065. })
  7066. .width('76%')
  7067. }
  7068. .margin({
  7069. left: 20,
  7070. right: 15,
  7071. top: 5,
  7072. bottom: 5
  7073. })
  7074. Row() {
  7075. Text(`显示高度:`)
  7076. .fontSize(14)
  7077. .fontColor(Color.White)
  7078. Slider({
  7079. value: this.pipLyHeight,
  7080. min: 10,
  7081. max: 1000,
  7082. step: 1,
  7083. style: SliderStyle.OutSet
  7084. })
  7085. .blockColor(this.themeColor)
  7086. .trackColor($r('app.color.speed_text_color'))
  7087. .selectedColor(Color.White)
  7088. .trackThickness(6)
  7089. .onChange((value: number) => {
  7090. this.pipLyHeight = value
  7091. if (this.pipController) {
  7092. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  7093. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  7094. }
  7095. })
  7096. .width('76%')
  7097. }
  7098. .margin({
  7099. left: 20,
  7100. right: 15,
  7101. top: 5,
  7102. bottom: 5
  7103. })
  7104. }
  7105. Row() {
  7106. Text(`歌词字号:`)
  7107. .fontSize(14)
  7108. .fontColor(Color.White)
  7109. Slider({
  7110. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  7111. min: 12,
  7112. max: 30,
  7113. step: 0.1,
  7114. style: SliderStyle.OutSet
  7115. })
  7116. .blockColor(this.themeColor)
  7117. .trackColor($r('app.color.speed_text_color'))
  7118. .selectedColor(Color.White)
  7119. .trackThickness(6)
  7120. .onChange((value: number) => {
  7121. this.setLyricTextSize(value, isPip)
  7122. })
  7123. .width('76%')
  7124. }
  7125. .margin({
  7126. left: 20,
  7127. right: 15,
  7128. top: 5,
  7129. bottom: 5
  7130. })
  7131. Row() {
  7132. Text(`高亮倍数:`)
  7133. .fontSize(14)
  7134. .fontColor(Color.White)
  7135. Slider({
  7136. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  7137. min: 1,
  7138. max: 2,
  7139. step: 0.1,
  7140. style: SliderStyle.OutSet
  7141. })
  7142. .blockColor(this.themeColor)
  7143. .trackColor($r('app.color.speed_text_color'))
  7144. .selectedColor(Color.White)
  7145. .trackThickness(6)
  7146. .onChange((value: number) => {
  7147. this.setHighLyricTextSize(value, isPip)
  7148. })
  7149. .width('76%')
  7150. }
  7151. .margin({
  7152. left: 20,
  7153. right: 15,
  7154. top: 5,
  7155. bottom: 5
  7156. })
  7157. Row() {
  7158. Text(`歌词间隙:`)
  7159. .fontSize(14)
  7160. .fontColor(Color.White)
  7161. Slider({
  7162. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  7163. min: 0,
  7164. max: 100,
  7165. step: 1,
  7166. style: SliderStyle.OutSet
  7167. })
  7168. .blockColor(this.themeColor)
  7169. .trackColor($r('app.color.speed_text_color'))
  7170. .selectedColor(Color.White)
  7171. .trackThickness(6)
  7172. .onChange((value: number) => {
  7173. this.setLyricLineSpace(value, isPip)
  7174. })
  7175. .width('76%')
  7176. }
  7177. .margin({
  7178. left: 20,
  7179. right: 15,
  7180. top: 5,
  7181. bottom: 5
  7182. })
  7183. //取值间隔为100,默认为400,取值越大,字体越粗
  7184. Row() {
  7185. Text(`歌词字重:`)
  7186. .fontSize(14)
  7187. .fontColor(Color.White)
  7188. Slider({
  7189. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  7190. min: 100,
  7191. max: 900,
  7192. step: 100,
  7193. style: SliderStyle.OutSet
  7194. })
  7195. .blockColor(this.themeColor)
  7196. .trackColor($r('app.color.speed_text_color'))
  7197. .selectedColor(Color.White)
  7198. .trackThickness(6)
  7199. .onChange((value: number) => {
  7200. if (isPip) {
  7201. this.lyricTextWeightPip = value
  7202. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  7203. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  7204. } else {
  7205. this.lyricTextWeight = value
  7206. this.lyricController.setTextWeight(this.lyricTextWeight)
  7207. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  7208. }
  7209. })
  7210. .width('76%')
  7211. }
  7212. .margin({
  7213. left: 20,
  7214. right: 15,
  7215. top: 5,
  7216. bottom: 5
  7217. })
  7218. if (!isPip) {
  7219. Row() {
  7220. Text(`歌词模糊:`)
  7221. .fontSize(14)
  7222. .fontColor(Color.White)
  7223. Slider({
  7224. value: isPip ? this.blurDegreePip : this.blurDegree,
  7225. min: 0,
  7226. max: 5,
  7227. step: 0.1,
  7228. style: SliderStyle.OutSet
  7229. })
  7230. .blockColor(this.themeColor)
  7231. .trackColor($r('app.color.speed_text_color'))
  7232. .selectedColor(Color.White)
  7233. .trackThickness(6)
  7234. .onChange((value: number) => {
  7235. this.setBlurDegree(value, isPip)
  7236. })
  7237. .width('76%')
  7238. }
  7239. .margin({
  7240. left: 20,
  7241. right: 15,
  7242. top: 5,
  7243. bottom: 15
  7244. })
  7245. }
  7246. Row() {
  7247. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  7248. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  7249. }
  7250. .justifyContent(FlexAlign.Center)
  7251. .margin({ top: 3, bottom: 10 })
  7252. }
  7253. }
  7254. private setBlurDegree(index: number, isPip: boolean) {
  7255. if (isPip) {
  7256. this.blurDegreePip = index
  7257. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  7258. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  7259. } else {
  7260. this.blurDegree = index
  7261. this.lyricController.setBlurDegree(this.blurDegree)
  7262. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  7263. }
  7264. }
  7265. private setLyricAlignMode(index: number, isPip: boolean) {
  7266. if (isPip) {
  7267. this.currentLyricAlignModePip = index
  7268. if (this.currentLyricAlignModePip === 1) {
  7269. this.lyricControllerXF.setAlignMode("left")
  7270. } else {
  7271. this.lyricControllerXF.setAlignMode("center")
  7272. }
  7273. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  7274. } else {
  7275. this.currentLyricAlignMode = index
  7276. if (this.currentLyricAlignMode === 1) {
  7277. this.lyricController.setAlignMode("left")
  7278. } else {
  7279. this.lyricController.setAlignMode("center")
  7280. }
  7281. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  7282. }
  7283. }
  7284. private setLyricTextSize(index: number, isPip: boolean) {
  7285. if (isPip) {
  7286. this.currentLyricSizePip = index
  7287. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  7288. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  7289. } else {
  7290. this.currentLyricSize = index
  7291. this.lyricController.setTextSize(this.currentLyricSize)
  7292. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  7293. }
  7294. }
  7295. private setHighLyricTextSize(scale: number, isPip: boolean) {
  7296. if (isPip) {
  7297. this.currentHightLyricSizePip = scale
  7298. this.lyricControllerXF
  7299. .setHighlightScale(this.currentHightLyricSizePip)
  7300. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  7301. } else {
  7302. this.currentHightLyricSize = scale
  7303. this.lyricController
  7304. .setHighlightScale(this.currentHightLyricSize)
  7305. PreferencesUtil.putSync('HighLyricTextSize', scale)
  7306. }
  7307. }
  7308. private setLyricLineSpace(index: number, isPip: boolean) {
  7309. if (isPip) {
  7310. this.currentLyricLineSpacePip = index
  7311. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  7312. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  7313. } else {
  7314. this.currentLyricLineSpace = index
  7315. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  7316. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  7317. }
  7318. }
  7319. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  7320. LogUtil.info('onecold isBG = ' + isBG)
  7321. if (isBG) { //如果是设置悬浮背景
  7322. this.pipBg = color
  7323. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  7324. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  7325. return
  7326. }
  7327. if (isPip) {
  7328. this.currentLyricColorPip = color
  7329. this.lyricControllerXF
  7330. .setTextColor(this.currentLyricColorPip)
  7331. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  7332. } else {
  7333. this.currentLyricColor = color
  7334. this.lyricController
  7335. .setTextColor(this.currentLyricColor)
  7336. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  7337. }
  7338. }
  7339. private changeLyricHightLightColor(color: string, isPip: boolean) {
  7340. if (isPip) {
  7341. this.currentHighLightLyricColorPip = color
  7342. this.lyricControllerXF
  7343. .setHighlightColor(this.currentHighLightLyricColorPip)
  7344. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  7345. } else {
  7346. this.currentHighLightLyricColor = color
  7347. this.lyricController
  7348. .setHighlightColor(this.currentHighLightLyricColor)
  7349. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  7350. }
  7351. }
  7352. // 构建时间控制器
  7353. @Builder
  7354. BuildTimeControls() {
  7355. Column() {
  7356. // 时间显示
  7357. Text(this.getTimeText())
  7358. .fontSize(18)
  7359. .fontColor(Color.White)
  7360. .margin({ bottom: 10 })
  7361. Row() {
  7362. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  7363. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  7364. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  7365. }
  7366. .justifyContent(FlexAlign.Center)
  7367. }
  7368. .margin({ top: 12, bottom: 8 })
  7369. }
  7370. // 精度按钮组件
  7371. @Builder
  7372. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  7373. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7374. Column() {
  7375. Image(icon)
  7376. .width(28)
  7377. .margin({ bottom: 5 })
  7378. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  7379. Text(label)
  7380. .fontSize(12)
  7381. .fontColor('#FFFFFF')
  7382. }
  7383. }
  7384. .backgroundColor(Color.Transparent)
  7385. .enabled(!this.isButtonDisabled(step))
  7386. .onClick(() => this.handlePrecisionAdjust(step))
  7387. .padding(5)
  7388. .width(66)
  7389. .height(66)
  7390. .margin({ left: 18, right: 18 })
  7391. .border({
  7392. color: '#FFFFFF',
  7393. width: 1.8
  7394. })
  7395. }
  7396. private handlePrecisionAdjust(step: number) {
  7397. if (step === 0) {
  7398. this.timeOffset = 0
  7399. return
  7400. }
  7401. // 精度处理:保留1位小数
  7402. const newOffset = Number((this.timeOffset + step).toFixed(5))
  7403. // 边界保护(±15.0秒)
  7404. if (newOffset < -30.0 || newOffset > 30.0) {
  7405. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  7406. return
  7407. }
  7408. // 状态更新
  7409. this.timeOffset = newOffset
  7410. }
  7411. // 按钮禁用逻辑
  7412. private isButtonDisabled(step: number): boolean {
  7413. const futureOffset = this.timeOffset + step
  7414. return (futureOffset < -30.0) || (futureOffset > 30.0)
  7415. }
  7416. // 时间显示文本升级
  7417. private getTimeText(): string {
  7418. const absValue = Math.abs(this.timeOffset)
  7419. return this.timeOffset === 0
  7420. ? '歌词时间已重置'
  7421. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  7422. }
  7423. // 导入 本地歌词 搜索歌词
  7424. @Builder
  7425. pushLyricButton(icon: Resource, step: number, label: string) {
  7426. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7427. Row() {
  7428. Image(icon)
  7429. .width(14)
  7430. .margin({ left: 13 })
  7431. Text(label)
  7432. .fontSize(12)
  7433. .margin({ left: 6 })
  7434. .fontColor('#FFFFFF')
  7435. }
  7436. }
  7437. .onClick(() => {
  7438. switch (step) {
  7439. case 0:
  7440. this.callFilePickerSelectFileForLyric()
  7441. break;
  7442. case 1:
  7443. //判断是不是赞助会员
  7444. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  7445. this.isLyricSetting = false
  7446. this.showTipsDialog()
  7447. return
  7448. }
  7449. if (StrUtil.isNotEmpty(this.videoUrl)) {
  7450. ToastUtil.showToast('正在获取')
  7451. this.isLyricSetting = false
  7452. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  7453. this.initLyric(lyricPath, true);
  7454. }
  7455. break;
  7456. }
  7457. })
  7458. .padding(5)
  7459. .width(110)
  7460. .backgroundColor(Color.Transparent)
  7461. .height(40)
  7462. .margin({ left: 6, right: 6 })
  7463. .border({
  7464. color: '#FFFFFF',
  7465. radius: 20,
  7466. width: 1.8
  7467. })
  7468. }
  7469. showVipDialog() {
  7470. DialogHelper.showCustomContentDialog({
  7471. dialogId: 'vip',
  7472. title: "友情提示",
  7473. autoCancel: false, //点击遮障层时,不关闭弹窗
  7474. backCancel: true, //点击返回键,不关闭弹窗
  7475. contentBuilder: () => {
  7476. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  7477. },
  7478. buttons: [],
  7479. })
  7480. }
  7481. //去赞助的自定义内容
  7482. @Builder
  7483. customVipBuilder(content: string) {
  7484. Column() {
  7485. Text(content)
  7486. .fontColor(Color.Gray)
  7487. .fontSize(16)
  7488. .alignSelf(ItemAlign.Start)
  7489. .margin({ bottom: 15 })
  7490. .fontSize(16)
  7491. Row() {
  7492. Button('取消')
  7493. .fontColor(Color.White)
  7494. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  7495. .height(50)
  7496. .layoutWeight(1)
  7497. .stateEffect(true)
  7498. .margin({ right: 6 })
  7499. .onClick(() => {
  7500. DialogHelper.closeDialog('vip'); //关闭弹框
  7501. })
  7502. Button('开通')
  7503. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  7504. .layoutWeight(1)
  7505. .height(50)
  7506. .backgroundColor(this.themeColor)
  7507. .stateEffect(true)
  7508. .margin({ left: 6 })
  7509. .onClick(() => {
  7510. DialogHelper.closeDialog('vip'); //关闭弹框
  7511. this.isShowPlay = false
  7512. this.mType = 1 //跳转到用户中心
  7513. // router.pushUrl({
  7514. // url: 'pages/VipPage'
  7515. // }, router.RouterMode.Single);
  7516. })
  7517. }
  7518. }
  7519. .width("100%")
  7520. .padding(10)
  7521. }
  7522. showTipsDialog() {
  7523. DialogHelper.showCustomContentDialog({
  7524. dialogId: 'tips',
  7525. title: "友情提示",
  7526. autoCancel: false, //点击遮障层时,不关闭弹窗
  7527. backCancel: true, //点击返回键,不关闭弹窗
  7528. contentBuilder: () => {
  7529. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  7530. },
  7531. buttons: [],
  7532. })
  7533. }
  7534. @Builder
  7535. customTipsBuilder(content: string) {
  7536. Column() {
  7537. Text(content)
  7538. .fontColor(Color.Gray)
  7539. .fontSize(16)
  7540. .alignSelf(ItemAlign.Start)
  7541. .margin({ bottom: 15 })
  7542. .fontSize(16)
  7543. Row() {
  7544. Button('取消')
  7545. .fontColor(Color.White)
  7546. .backgroundColor(this.themeColor)
  7547. .height(50)
  7548. .layoutWeight(1)
  7549. .stateEffect(true)
  7550. .margin({ right: 6 })
  7551. .onClick(() => {
  7552. DialogHelper.closeDialog('tips'); //关闭弹框
  7553. })
  7554. Button('跳转')
  7555. .fontColor(Color.White)//
  7556. .layoutWeight(1)
  7557. .height(50)
  7558. .backgroundColor(this.themeColor)
  7559. .stateEffect(true)
  7560. .margin({ left: 6 })
  7561. .onClick(() => {
  7562. DialogHelper.closeDialog('tips'); //关闭弹框
  7563. this.isShowPlay = false
  7564. this.mType = 3
  7565. // router.pushUrl({
  7566. // url: 'pages/SettingPage'
  7567. // }, router.RouterMode.Single);
  7568. })
  7569. }
  7570. }
  7571. .width("100%")
  7572. .padding(10)
  7573. }
  7574. @Builder
  7575. PlayMoreSheet() {
  7576. Column() {
  7577. this.MoreList()
  7578. }
  7579. .width('100%')
  7580. .height('100%')
  7581. }
  7582. @Builder
  7583. MoreList() {
  7584. Scroll() {
  7585. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  7586. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  7587. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7588. Row() {
  7589. if (more.id === 3&&this.currentSong) {
  7590. Image(more.image)
  7591. .width(24)
  7592. .height(24)
  7593. .margin({ left: 10, right: 10 })
  7594. Text(more.title)
  7595. .fontSize(16)
  7596. .fontColor(Color.White)
  7597. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  7598. height: this.isCoverOpacity() ? '95%' : '95%',
  7599. dragBar: true,
  7600. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7601. showClose: true,
  7602. blurStyle: BlurStyle.Thin,
  7603. backgroundColor: Color.Transparent,
  7604. title: { title: '歌曲信息' }
  7605. })
  7606. } else if (more.id === 15 && this.currentSong) { //编辑信息
  7607. Image(more.image)
  7608. .width(24)
  7609. .height(24)
  7610. .margin({ left: 10, right: 10 })
  7611. Text(more.title)
  7612. .fontSize(16)
  7613. .fontColor(Color.White)
  7614. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  7615. height: this.isCoverOpacity() ? '95%' : '93%',
  7616. dragBar: true,
  7617. showClose: true,
  7618. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7619. // blurStyle:BlurStyle.Thin,
  7620. // backgroundColor:Color.Transparent,
  7621. title: { title: '编辑信息' }
  7622. })
  7623. } else if (more.id === 5) { //定时关闭
  7624. Image(more.image)
  7625. .width(24)
  7626. .height(24)
  7627. .margin({ left: 10, right: 10 })
  7628. Text(more.title)
  7629. .fontSize(16)
  7630. .fontColor(Color.White)
  7631. .onClick(() => {
  7632. this.doMore(more.id)
  7633. })
  7634. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  7635. height: this.isCoverOpacity() ? '95%' : '95%',
  7636. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7637. dragBar: true,
  7638. showClose: true,
  7639. title: { title: $r('app.string.time_close') }
  7640. })
  7641. } else if (more.id === 2) { //歌词设置
  7642. Image(more.image)
  7643. .width(24)
  7644. .height(24)
  7645. .margin({ left: 10, right: 10 })
  7646. Text(more.title)
  7647. .fontSize(16)
  7648. .fontColor(Color.White)
  7649. } else if (more.id === 16) { //悬浮歌词设置
  7650. Image(more.image)
  7651. .width(24)
  7652. .height(24)
  7653. .margin({ left: 10, right: 10 })
  7654. Text(more.title)
  7655. .fontSize(16)
  7656. .fontColor(Color.White)
  7657. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  7658. height: this.isCoverOpacity() ? '95%' : '95%',
  7659. dragBar: true,
  7660. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7661. showClose: true,
  7662. blurStyle: BlurStyle.Thin,
  7663. backgroundColor: Color.Transparent,
  7664. title: { title: '悬浮歌词' }
  7665. })
  7666. } else if (more.id === 11) {
  7667. Image(more.image)
  7668. .width(24)
  7669. .height(24)
  7670. .margin({ left: 10, right: 10 })
  7671. Text(more.title)
  7672. .fontSize(16)
  7673. .fontColor(Color.White)
  7674. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  7675. height: this.isCoverOpacity() ? '95%' : '60%',
  7676. dragBar: true,
  7677. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7678. showClose: true,
  7679. blurStyle: BlurStyle.Thin,
  7680. backgroundColor: Color.Transparent,
  7681. title: { title: '跳过头尾' }
  7682. })
  7683. } else if (more.id === 12) { //投播
  7684. AVCastPicker({
  7685. customPicker: (): void => this.TPImageBuilder(more),
  7686. onStateChange: (state) => {
  7687. if (state == AVCastPickerState.STATE_APPEARING) {
  7688. console.log(' The picker starts showing.');
  7689. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  7690. console.log(' The picker finishes presenting.');
  7691. }
  7692. },
  7693. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  7694. sessionType: 'video'
  7695. })
  7696. .id('AVCastPicker')
  7697. } else {
  7698. Image(more.image)
  7699. .width(24)
  7700. .height(24)
  7701. .margin({ left: 10, right: 10 })
  7702. .onClick(() => {
  7703. this.doMore(more.id)
  7704. })
  7705. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  7706. .fontSize(16)
  7707. .fontColor(Color.White)
  7708. .onClick(() => {
  7709. this.doMore(more.id)
  7710. })
  7711. Select([//倍速
  7712. { value: '0.25x' },
  7713. { value: '0.5x' },
  7714. { value: '0.75x' },
  7715. { value: '1x' },
  7716. { value: '1.25x' },
  7717. { value: '1.5x' },
  7718. { value: '1.75x' },
  7719. { value: '2x' },
  7720. { value: '3x' }])
  7721. .font({ size: 16, weight: FontWeight.Medium })
  7722. .fontColor($r('sys.color.white'))
  7723. .margin({ left: 25 })
  7724. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  7725. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  7726. .value(Utility.optimizedFormat(this.playSpeed))
  7727. .onSelect(async (_index: number, text?: string | undefined) => {
  7728. let speed = parseFloat(text?.replace('x', '') || '1');
  7729. if (!CommonConstants.video_speed_list.includes(speed)) {
  7730. speed = 1;
  7731. }
  7732. this.playSpeed = speed
  7733. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  7734. })
  7735. Slider({
  7736. value: this.volume,
  7737. min: 0,
  7738. max: 1,
  7739. step: 0.1,
  7740. style: SliderStyle.OutSet
  7741. })
  7742. .margin({ left: 18, right: 8 })
  7743. .blockColor(this.themeColor)
  7744. .trackColor($r('app.color.speed_text_color'))
  7745. .selectedColor(Color.White)
  7746. .trackThickness(9)
  7747. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  7748. .onChange((value: number) => {
  7749. this.volume = value;
  7750. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  7751. PreferencesUtil.putSync('DefalutVolume',this.volume)
  7752. })
  7753. .layoutWeight(1)
  7754. Blank()
  7755. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  7756. .selectedColor(this.themeColor)
  7757. .switchPointColor(Color.White)
  7758. .margin({ right: 15 })
  7759. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7760. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  7761. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  7762. if (more.id == 6) {
  7763. this.isMusicMemoryPlay = checked;
  7764. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  7765. if (this.isMusicMemoryPlay) {
  7766. ToastUtil.showToast('记忆播放已开启')
  7767. } else {
  7768. ToastUtil.showToast('记忆播放已关闭')
  7769. }
  7770. }
  7771. })
  7772. .width(48)
  7773. .height(24);
  7774. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  7775. .selectedColor(this.themeColor)
  7776. .switchPointColor(Color.White)
  7777. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7778. .margin({ right: 15 })
  7779. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  7780. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  7781. if (more.id == 7) {
  7782. this.isMusicBGCover = checked;
  7783. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  7784. if (this.isMusicBGCover) {
  7785. ToastUtil.showToast('播放背景随音乐封面已开启')
  7786. } else {
  7787. ToastUtil.showToast('播放背景随音乐封面已关闭')
  7788. }
  7789. }
  7790. })
  7791. .width(48)
  7792. .height(24);
  7793. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  7794. .selectedColor(this.themeColor)
  7795. .switchPointColor(Color.White)
  7796. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7797. .margin({ right: 15 })
  7798. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  7799. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  7800. if (more.id == 8) {
  7801. this.isSavePlayMode = checked;
  7802. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  7803. if (this.isSavePlayMode) {
  7804. ToastUtil.showToast('保存播放模式已开启')
  7805. } else {
  7806. ToastUtil.showToast('保存播放模式已关闭')
  7807. }
  7808. }
  7809. })
  7810. .width(48)
  7811. .height(24);
  7812. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  7813. .selectedColor(this.themeColor)
  7814. .switchPointColor(Color.White)
  7815. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7816. .margin({ right: 15 })
  7817. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  7818. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  7819. if (more.id == 13) {
  7820. this.isCoverRectangle = checked;
  7821. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  7822. if (this.isCoverRectangle) {
  7823. ToastUtil.showToast('封面方形已开启')
  7824. this.animationRoFun()
  7825. } else {
  7826. ToastUtil.showToast('封面圆形已开启')
  7827. this.animationRoFun()
  7828. }
  7829. }
  7830. })
  7831. .width(48)
  7832. .height(24);
  7833. }
  7834. }
  7835. .width('100%')
  7836. .height(45)
  7837. .padding(15)
  7838. .backgroundColor(Color.Transparent)
  7839. .borderRadius(12)
  7840. .margin({ bottom: 6 })
  7841. }
  7842. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  7843. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  7844. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  7845. .backgroundColor(Color.Transparent)
  7846. .onClick(() => {
  7847. this.doMore(more.id)
  7848. })
  7849. });
  7850. }
  7851. .width('100%')
  7852. .padding(16)
  7853. }.margin({ bottom: 18 })
  7854. }
  7855. @Builder
  7856. TPImageBuilder(more: MoreItem): void {
  7857. Row() {
  7858. Image($r('app.media.tuoping'))
  7859. .width(22)
  7860. .height(22)
  7861. .margin({ left: 10, right: 10 })
  7862. Text(more.title)
  7863. .fontSize(16)
  7864. .fontColor(Color.White)
  7865. }
  7866. .width('100%')
  7867. .layoutWeight(1)
  7868. .alignItems(VerticalAlign.Center)
  7869. .justifyContent(FlexAlign.Start)
  7870. }
  7871. private moreItems: MoreItem[] = [
  7872. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  7873. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  7874. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  7875. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  7876. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  7877. { id: 15, image: $r('app.media.rename2'), title: '编辑信息' },
  7878. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  7879. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  7880. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  7881. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  7882. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  7883. { id: 4, image: $r('app.media.share2'), title: '分享' },
  7884. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  7885. { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  7886. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  7887. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  7888. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  7889. ];
  7890. @State isShowMoreView: boolean = false;
  7891. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  7892. @State isShowTimeCloseMore: boolean = false
  7893. @State isShowDetailMore: boolean = false
  7894. @State isMusicBGCover: boolean = true
  7895. @State isSavePlayMode: boolean = true
  7896. @State isLyricSetting: boolean = false
  7897. @State isJumpSetting: boolean = false
  7898. @State isShowEdit: boolean = false
  7899. @State showPipLyric: boolean = false
  7900. async setRingTone() {
  7901. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  7902. return
  7903. }
  7904. // 确定后的逻辑
  7905. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  7906. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  7907. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  7908. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  7909. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  7910. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  7911. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  7912. , this.videoUrl, this.name).then(res => {
  7913. LogUtil.info('onecold setFlag :' + res);
  7914. });
  7915. }
  7916. doMore(moreId: number) {
  7917. switch (moreId) {
  7918. case 2: //歌词
  7919. this.isLyricSetting = !this.isLyricSetting;
  7920. this.isShowMoreView = false
  7921. break;
  7922. case 3: //详情
  7923. this.isShowDetailMore = !this.isShowDetailMore;
  7924. break;
  7925. case 4: //分享
  7926. if (this.currentSong !== undefined) {
  7927. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  7928. }
  7929. this.isShowMoreView = false
  7930. break;
  7931. case 5: //定时关闭
  7932. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  7933. break;
  7934. case 10: //设为铃声
  7935. this.setRingTone()
  7936. this.isShowMoreView = false
  7937. break;
  7938. case 11: //跳过头尾
  7939. this.isJumpSetting = !this.isJumpSetting;
  7940. break;
  7941. case 13: //倍速
  7942. break;
  7943. case 14: //搜索封面
  7944. if (this.currentSong !== undefined) {
  7945. this.doSearchCover(this.currentSong)
  7946. }
  7947. this.isShowMoreView = false
  7948. break;
  7949. case 15: //编辑信息
  7950. this.isShowEdit = !this.isShowEdit;
  7951. break;
  7952. case 16: //悬浮歌词
  7953. this.showPipLyric = !this.showPipLyric;
  7954. break;
  7955. case 17: //横屏模式
  7956. if (this.isLandscape) {
  7957. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  7958. } else {
  7959. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  7960. }
  7961. this.isShowMoreView = false
  7962. break;
  7963. }
  7964. }
  7965. /**
  7966. * 切换横竖屏
  7967. *
  7968. */
  7969. setOrientation(orientation: number) {
  7970. if (this.windowClass) {
  7971. this.windowClass.setPreferredOrientation(orientation).then(() => {
  7972. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  7973. }).catch((err: BusinessError) => {
  7974. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  7975. });
  7976. }
  7977. }
  7978. /**
  7979. * 画中画功能(悬浮歌词功能)
  7980. *
  7981. */
  7982. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  7983. pipController?: PiPWindow.PiPController;
  7984. navigationId: string = '';
  7985. @State curState: string = '';
  7986. @State curError: ResourceStr = '';
  7987. @State pipBg: string = '#E8E8E8'
  7988. @State buttonAction: string = '';
  7989. //开启画中画功能
  7990. async startPip() {
  7991. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  7992. if (!this.pipController) {
  7993. await this.createPipController();
  7994. }
  7995. if (!this.pipController) {
  7996. Logger.info(`[${TAG}] pipController create error`);
  7997. return;
  7998. }
  7999. await this.pipController.startPiP();
  8000. }
  8001. async stopPip() {
  8002. if (!this.pipController) {
  8003. Logger.info(`[${TAG}] pipController is not exist`);
  8004. return;
  8005. }
  8006. this.isOpenPip = false
  8007. await this.pipController.stopPiP();
  8008. }
  8009. async createPipController() {
  8010. this.pipController = await PiPWindow.create({
  8011. context: getContext(this),
  8012. componentController: this.xcomponentController,
  8013. navigationId: this.navigationId,
  8014. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  8015. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  8016. customUIController: this.nodeController,
  8017. });
  8018. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  8019. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  8020. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  8021. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  8022. this.onStateChange(state, reason);
  8023. });
  8024. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  8025. this.onActionEvent(event, status);
  8026. });
  8027. }
  8028. destroyPipController() {
  8029. if (!this.pipController) {
  8030. return;
  8031. }
  8032. this.pipController.off('stateChange');
  8033. this.pipController.off('controlPanelActionEvent');
  8034. this.pipController = undefined;
  8035. }
  8036. onStateChange(state: PiPWindow.PiPState, reason: string) {
  8037. switch (state) {
  8038. case PiPWindow.PiPState.ABOUT_TO_START:
  8039. this.curState = 'ABOUT_TO_START';
  8040. this.curError = $r('app.string.current_error_hint');
  8041. break;
  8042. case PiPWindow.PiPState.STARTED:
  8043. this.curState = 'STARTED';
  8044. this.curError = $r('app.string.current_error_hint');
  8045. break;
  8046. case PiPWindow.PiPState.ABOUT_TO_STOP:
  8047. this.curState = 'ABOUT_TO_STOP';
  8048. this.curError = $r('app.string.current_error_hint');
  8049. break;
  8050. case PiPWindow.PiPState.STOPPED:
  8051. this.curState = 'STOPPED';
  8052. this.curError = $r('app.string.current_error_hint');
  8053. this.stopPip()
  8054. this.destroyPipController()
  8055. break;
  8056. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  8057. this.curState = 'ABOUT_TO_RESTORE';
  8058. this.curError = $r('app.string.current_error_hint');
  8059. break;
  8060. case PiPWindow.PiPState.ERROR:
  8061. this.curState = 'ERROR';
  8062. this.curError = reason;
  8063. break;
  8064. default:
  8065. break;
  8066. }
  8067. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  8068. }
  8069. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  8070. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  8071. switch (event) {
  8072. case 'playbackStateChanged':
  8073. if (status === 0) {
  8074. this.pause();
  8075. } else {
  8076. this.startPlayOrResumePlay();
  8077. }
  8078. break;
  8079. case 'nextVideo':
  8080. // 切换到下一个视频
  8081. this.playNext()
  8082. break;
  8083. case 'previousVideo':
  8084. // 切换到上一个视频
  8085. this.playPrevious()
  8086. break;
  8087. case 'previousVideo':
  8088. // 切换到上一个视频
  8089. this.playPrevious()
  8090. break;
  8091. default:
  8092. }
  8093. this.buttonAction = event + `-status:${status}`;
  8094. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  8095. }
  8096. /**
  8097. * 画中画功能(悬浮歌词功能)结束
  8098. *
  8099. */
  8100. doSearchCover(item: VideoItem) {
  8101. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  8102. this.isShowMoreView = false
  8103. this.showTipsDialog()
  8104. return
  8105. }
  8106. if (item !== undefined) {
  8107. let artist = item?.artist
  8108. if (StrUtil.isEmpty(artist) || artist === undefined) {
  8109. artist = ''
  8110. }
  8111. this.searchCover(item, item.name, artist)
  8112. }
  8113. }
  8114. searchCover(item: VideoItem, title: string, artist: string) {
  8115. NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  8116. LogUtil.debug("onecold res =" + res)
  8117. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  8118. if (item.filePath == this.currentSong?.filePath) {
  8119. this.cover = res
  8120. if (this.currentSong) {
  8121. this.currentSong.pixelMapPath = res
  8122. }
  8123. }
  8124. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  8125. if (success) {
  8126. this.doUpdateData()
  8127. console.log(" onecold 更新音乐封面成功,数据库已同步");
  8128. } else {
  8129. console.error(" onecold 更新音乐封面数据库失败原因: " + error);
  8130. }
  8131. });
  8132. LogUtil.debug("onecold this.cover =" + this.cover)
  8133. }
  8134. })
  8135. }
  8136. @State jumpTopTime: number = 0
  8137. @State jumpEndTime: number = 0
  8138. @State isOpenJump: boolean = false
  8139. @Builder
  8140. JumpTopEndSheet() {
  8141. Scroll() {
  8142. Column() {
  8143. Column() {
  8144. Text('仅对本播放列表有效')
  8145. .fontSize(16)
  8146. .fontColor($r('app.color.text_color'))
  8147. // 跳过头尾
  8148. Column() {
  8149. Row() {
  8150. Text('跳过片头:')
  8151. .fontSize(16)
  8152. .fontColor($r('app.color.text_color'))
  8153. Text(this.jumpTopTime + 's')
  8154. .fontSize(16)
  8155. .fontColor($r('app.color.text_color'))
  8156. }
  8157. .margin({ bottom: 5 })
  8158. Row() {
  8159. Slider({
  8160. value: this.jumpTopTime,
  8161. min: 0,
  8162. max: 120,
  8163. step: 1,
  8164. style: SliderStyle.OutSet
  8165. })
  8166. .blockColor(this.themeColor)
  8167. .trackColor($r('app.color.speed_text_color'))
  8168. .selectedColor(Color.White)
  8169. .trackThickness(8)
  8170. .onChange((value: number) => {
  8171. this.jumpTopTime = value;
  8172. })
  8173. .width('85%')
  8174. }
  8175. .alignItems(VerticalAlign.Top)
  8176. }
  8177. .margin({ top: 10, bottom: 10 })
  8178. // 跳过头尾
  8179. Column() {
  8180. Row() {
  8181. Text('跳过片尾:')
  8182. .fontSize(16)
  8183. .fontColor($r('app.color.text_color'))
  8184. Text(this.jumpEndTime + 's')
  8185. .fontSize(16)
  8186. .fontColor($r('app.color.text_color'))
  8187. }
  8188. .margin({ bottom: 5 })
  8189. Row() {
  8190. Slider({
  8191. value: this.jumpEndTime,
  8192. min: 0,
  8193. max: 120,
  8194. step: 1,
  8195. style: SliderStyle.OutSet
  8196. })
  8197. .blockColor(this.themeColor)
  8198. .trackColor($r('app.color.speed_text_color'))
  8199. .selectedColor(Color.White)
  8200. .trackThickness(8)
  8201. .onChange((value: number) => {
  8202. this.jumpEndTime = value;
  8203. })
  8204. .width('85%')
  8205. }
  8206. .alignItems(VerticalAlign.Top)
  8207. }
  8208. .margin({ top: 10, bottom: 10 })
  8209. Row() {
  8210. Button('保存设置')
  8211. .fontColor(Color.White)
  8212. .layoutWeight(1)
  8213. .height(40)
  8214. .width(80)
  8215. .backgroundColor(this.themeColor)
  8216. .stateEffect(true)
  8217. .margin({ left: 0, bottom: 20 })
  8218. .onClick(async () => {
  8219. if (!Utility.isNoble()) {
  8220. this.isJumpSetting = false
  8221. this.isShowMoreView = false
  8222. this.showVipDialog()
  8223. return
  8224. }
  8225. if (this.currentSong === undefined) {
  8226. return
  8227. }
  8228. if (this.modeType === 0) {
  8229. let parentPath = FileUtil.getParentPath(this.videoUrl)
  8230. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  8231. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  8232. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  8233. } else if (this.modeType === 1) { //媒体库
  8234. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  8235. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  8236. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  8237. } else if (this.modeType === 2) { //艺术家
  8238. if (this.currentSong?.artist) {
  8239. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  8240. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  8241. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  8242. }
  8243. } else if (this.modeType === 3) { //专辑
  8244. if (this.currentSong?.album) {
  8245. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  8246. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  8247. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  8248. }
  8249. }
  8250. ToastUtil.showShort("保存成功")
  8251. this.isJumpSetting = false
  8252. })
  8253. }
  8254. .margin({
  8255. left: 38,
  8256. right: 38,
  8257. top: 10,
  8258. bottom: 10
  8259. })
  8260. .width(120)
  8261. .height(50)
  8262. }
  8263. }
  8264. }
  8265. .width('100%')
  8266. .height('100%')
  8267. }
  8268. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  8269. private onStateVastChange(state: AVCastPickerState) {
  8270. if (state == AVCastPickerState.STATE_APPEARING) {
  8271. console.log('The picker starts showing.');
  8272. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  8273. console.log('The picker finishes presenting.');
  8274. }
  8275. }
  8276. private showSelectLyric() {
  8277. DialogHelper.showActionSheetDialog({
  8278. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  8279. // sheets: ["本地歌词", "搜索歌词"],
  8280. sheets: [
  8281. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  8282. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  8283. ],
  8284. maskColor: Color.Transparent,
  8285. backgroundColor: $r('app.color.bg_card'),
  8286. transition: AnimationHelper.transitionInDown(666),
  8287. onAction: (index) => {
  8288. switch (index) {
  8289. case 0:
  8290. this.callFilePickerSelectFileForLyric()
  8291. break;
  8292. case 1:
  8293. if (StrUtil.isNotEmpty(this.videoUrl)) {
  8294. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  8295. this.initLyric(lyricPath);
  8296. }
  8297. break;
  8298. }
  8299. }
  8300. })
  8301. }
  8302. // 拉起picker选择文件管理器
  8303. async callFilePickerSelectFileForLyric(): Promise<void> {
  8304. try {
  8305. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  8306. DocumentSelectOptions.maxSelectNumber = 1
  8307. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  8308. let documentPicker = new picker.DocumentViewPicker();
  8309. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  8310. Logger.info(TAG,
  8311. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  8312. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  8313. this.saveVideoDatasLyric(DocumentSelectResult)
  8314. }
  8315. }).catch((err: BusinessError) => {
  8316. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  8317. });
  8318. } catch (err) {
  8319. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  8320. }
  8321. }
  8322. async saveVideoDatasLyric(uris: string[]) {
  8323. if (ArrayUtil.isEmpty(uris)) {
  8324. return
  8325. }
  8326. let newUris: string[] = [];
  8327. for (let i = 0; i < uris.length; i++) {
  8328. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  8329. Logger.info(TAG, 'filePath uri: ' + filePath);
  8330. newUris.push(filePath)
  8331. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  8332. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  8333. fileIo.copyFileSync(file.fd, file2.fd)
  8334. fileIo.closeSync(file);
  8335. fileIo.closeSync(file2);
  8336. this.initLyric(filePath)
  8337. }
  8338. }
  8339. private initDelayPlay(context: object) {
  8340. this.mContext = context;
  8341. }
  8342. startPipLyric() {
  8343. if (this.pipController) {
  8344. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  8345. PiPWindow.PiPControlStatus.PLAY);
  8346. }
  8347. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  8348. if (this.isOpenPip) {
  8349. this.startPip()
  8350. } else {
  8351. this.stopPip()
  8352. }
  8353. }
  8354. private startPlayOrResumePlay() {
  8355. this.startPipLyric()
  8356. this.mDestroyPage = false;
  8357. this.animationState = AnimationStatus.Running
  8358. LogUtils.getInstance().LOGI("startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  8359. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  8360. this.stopProgressTask();
  8361. this.startProgressTask();
  8362. this.play(this.videoUrl.toString());
  8363. }
  8364. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  8365. this.mIjkMediaPlayer.start();
  8366. this.setProgress()
  8367. this.CONTROL_PlayStatus = PlayStatus.PLAY
  8368. }
  8369. this.setIsPlaying(true)
  8370. this.updateSessionPlayState(true)
  8371. this.watchStatus();
  8372. this.updateLastPlayTimeStr(this.videoUrl)
  8373. // 广播状态变化到卡片
  8374. this.broadcastPlayerState();
  8375. }
  8376. updateLastPlayTimeStr(filePath: string) {
  8377. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  8378. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  8379. if (success) {
  8380. this.getHistoryList(false)
  8381. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  8382. } else {
  8383. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  8384. }
  8385. });
  8386. }
  8387. private completionNum(num: number): string | number {
  8388. if (num < 10) {
  8389. return '0' + num;
  8390. } else {
  8391. return num;
  8392. }
  8393. }
  8394. private stringForTime(timeMs: number): string {
  8395. let totalSeconds: number | string = (timeMs / 1000);
  8396. let newSeconds: number | string = totalSeconds % 60;
  8397. let minutes: number | string = (totalSeconds / 60) % 60;
  8398. let hours: number | string = totalSeconds / 3600;
  8399. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  8400. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  8401. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  8402. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  8403. if (this.isCurrentTime) {
  8404. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  8405. this.oldSeconds = newSeconds
  8406. } else {
  8407. newSeconds = this.oldSeconds
  8408. }
  8409. }
  8410. newSeconds = this.completionNum(newSeconds);
  8411. if (hours > 0) {
  8412. return hours + ":" + minutes + ":" + newSeconds;
  8413. } else {
  8414. return minutes + ":" + newSeconds;
  8415. }
  8416. }
  8417. private setProgress() {
  8418. let position = this.mIjkMediaPlayer.getCurrentPosition();
  8419. let duration = this.mIjkMediaPlayer.getDuration();
  8420. let pos = 0;
  8421. if (duration > 0) {
  8422. this.slideEnable = true;
  8423. let curPercent = position / duration;
  8424. pos = curPercent * 100;
  8425. if (pos > this.PROGRESS_MAX_VALUE) {
  8426. this.progressValue = this.PROGRESS_MAX_VALUE
  8427. } else {
  8428. this.progressValue = pos;
  8429. }
  8430. }
  8431. // LogUtils.getInstance()
  8432. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  8433. this.totalTime = this.stringForTime(duration);
  8434. if (position > duration) {
  8435. position = duration;
  8436. }
  8437. this.isCurrentTime = true;
  8438. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  8439. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  8440. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  8441. this.currentTime = this.stringForTime(position);
  8442. this.isCurrentTime = false
  8443. if (this.mIjkMediaPlayer.isPlaying()) {
  8444. this.randomColor =
  8445. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  8446. // 判断是否播放到结束时间
  8447. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  8448. if (position >= duration - this.jumpEndTime * 1000) {
  8449. this.playNext()
  8450. }
  8451. }
  8452. } else {
  8453. this.randomColor = 'rbg(0,0,0)'
  8454. }
  8455. // 节流广播进度更新到卡片
  8456. this.broadcastProgressIfNeeded();
  8457. }
  8458. private startProgressTask() {
  8459. let that = this;
  8460. this.updateProgressTimer = setInterval(() => {
  8461. //LogUtils.getInstance().LOGI("startProgressTask");
  8462. if (!that.mDestroyPage) {
  8463. that.setProgress();
  8464. }
  8465. }, 300);
  8466. }
  8467. private stopProgressTask() {
  8468. LogUtils.getInstance().LOGI("stopProgressTask");
  8469. clearInterval(this.updateProgressTimer);
  8470. }
  8471. private showLoadIng() {
  8472. this.loadingVisible = Visibility.Visible;
  8473. this.replayVisible = Visibility.None;
  8474. }
  8475. private hideLoadIng() {
  8476. this.loadingVisible = Visibility.None;
  8477. this.replayVisible = Visibility.None;
  8478. }
  8479. private showRePlay() {
  8480. this.loadingVisible = Visibility.None;
  8481. this.replayVisible = Visibility.Visible;
  8482. }
  8483. private async play(url: string) {
  8484. let that = this;
  8485. that.showLoadIng();
  8486. //设置XComponent回调的context
  8487. if (!!this.mContext) {
  8488. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  8489. }
  8490. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  8491. this.mIjkMediaPlayer.reset();
  8492. }
  8493. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  8494. //设置debug模式
  8495. this.mIjkMediaPlayer.setDebug(false);
  8496. //初始化配置
  8497. this.mIjkMediaPlayer.native_setup();
  8498. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  8499. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  8500. this.mIjkMediaPlayer.setVolume('1', '1');
  8501. }else{
  8502. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  8503. }
  8504. //设置视频源
  8505. this.mIjkMediaPlayer.setDataSource(url);
  8506. //设置视频源http请求头
  8507. let headers = new Map([
  8508. ["user_agent", "Mozilla/5.0 BiliDroid/7.30.0 (bbcallen@gmail.com)"],
  8509. ["referer", "https://www.bilibili.com"]
  8510. ]);
  8511. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  8512. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  8513. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  8514. // }
  8515. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  8516. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  8517. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  8518. const fileSize = await this.getFileSize(this.videoUrl);
  8519. let bufferSize = 1 * 1024 * 1024; // 默认缓冲区大小为2MB
  8520. if (fileSize > 3 * 1024 * 1024 * 1024) { // 文件大于3GB
  8521. bufferSize = 25 * 1024 * 1024; // 设置缓冲区大小为25MB
  8522. }
  8523. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  8524. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  8525. //停止预读的最小帧数
  8526. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  8527. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  8528. // 设置其他缓冲相关选项
  8529. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  8530. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  8531. //启动预加载
  8532. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  8533. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  8534. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  8535. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  8536. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  8537. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  8538. // 因此需要播放器丢包,才不会累积延时
  8539. // 这个和第三个参数packet-buffering无关。
  8540. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  8541. // 无限制收流
  8542. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  8543. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  8544. // 屏幕常亮
  8545. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  8546. // 设置超时
  8547. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  8548. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  8549. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  8550. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  8551. // 变速播放
  8552. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  8553. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  8554. let Speed = this.mIjkMediaPlayer.getSpeed()
  8555. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  8556. //是否开启循环播放
  8557. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  8558. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  8559. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  8560. if (height === 0) {
  8561. return;
  8562. }
  8563. const va = width / height;
  8564. const vpa = that.videoParentAspectRatio;
  8565. if (vpa > va) {
  8566. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  8567. } else {
  8568. that.videoWidth = '100%';
  8569. }
  8570. if (width && height) {
  8571. that.videoAspectRatio = width / height;
  8572. }
  8573. LogUtils.getInstance()
  8574. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  8575. that.hideLoadIng();
  8576. }
  8577. }
  8578. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  8579. let mOnPreparedListener: OnPreparedListener = {
  8580. onPrepared: async () => {
  8581. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  8582. try {
  8583. // this.cover = this.songList[this.curIndex].pixelMapPath
  8584. // this.artist = this.songList[this.curIndex].artist
  8585. // this.videoUrl = this.songList[this.curIndex].filePath
  8586. let isBgCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  8587. if (isBgCover && this.cover !== undefined && StrUtil.isNotEmpty(this.cover)) {
  8588. this.setImageColor2(this.cover)
  8589. } else {
  8590. this.getImageColor();
  8591. }
  8592. //保存碰一碰分享的当前的歌曲
  8593. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  8594. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  8595. await this.initLyric(lyricPath);
  8596. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  8597. this.avSessionController.initAvSession(false);
  8598. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  8599. this.setAvSessionListener();
  8600. this.updateSessionPlayState(true)
  8601. this.setCurrentPlayMode()
  8602. }, 500)
  8603. let timeoutPlay = 0
  8604. if (StrUtil.isNotEmpty(this.videoUrl) &&
  8605. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  8606. timeoutPlay = 1000
  8607. }
  8608. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  8609. if (this.modeType === 0) { //文件夹
  8610. let parentPath = FileUtil.getParentPath(this.videoUrl)
  8611. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  8612. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  8613. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  8614. } else if (this.modeType === 1) { //媒体库
  8615. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  8616. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  8617. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  8618. } else if (this.modeType === 2) { //艺术家
  8619. if (this.currentSong?.artist) {
  8620. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  8621. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  8622. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  8623. }
  8624. } else if (this.modeType === 3) { //专辑
  8625. if (this.currentSong?.album) {
  8626. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  8627. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  8628. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  8629. }
  8630. }
  8631. this.duration = this.mIjkMediaPlayer.getDuration()
  8632. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  8633. if (this.mIjkMediaPlayer != null) {
  8634. if (this.jumpTopTime * 1000 <= this.duration) {
  8635. // 调用 seekTo 方法,跳到指定时间
  8636. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  8637. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  8638. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  8639. }
  8640. }, timeoutPlay)
  8641. } else {
  8642. // 提示用户无法跳过
  8643. ToastUtil.showToast('跳过时间超过视频时长');
  8644. }
  8645. }
  8646. } else {
  8647. this.jumpTopTime = 0
  8648. this.jumpEndTime = 0
  8649. console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  8650. console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  8651. console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  8652. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  8653. //记忆播放(每一首都会记忆播放)
  8654. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  8655. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  8656. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  8657. this.restorePlaybackPosition() //读取播放记忆功能
  8658. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  8659. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  8660. this.restorePlaybackPosition() //读取播放记忆功能
  8661. }
  8662. this.isFirstStartPlay = false
  8663. }, timeoutPlay)
  8664. } else {
  8665. this.isFirstStartPlay = false
  8666. }
  8667. }
  8668. this.saveLastPlayList()
  8669. } catch (error) {
  8670. let err: BusinessError = error as BusinessError;
  8671. console.error('onecold failed with err: ' + JSON.stringify(err));
  8672. }
  8673. }
  8674. }
  8675. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  8676. let mOnTimedTextListener: OnTimedTextListener = {
  8677. onTimedText: () => {
  8678. }
  8679. }
  8680. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  8681. let mOnCompletionListener: OnCompletionListener = {
  8682. onCompletion: () => {
  8683. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  8684. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  8685. this.playNext()
  8686. } else if (this.playType == 1) { //1:单片重复播放
  8687. this.CONTROL_PlayStatus = PlayStatus.INIT
  8688. that.startPlayOrResumePlay();
  8689. } else if (this.playType == 2) { //2:正常播放,单曲播完
  8690. that.showRePlay();
  8691. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  8692. that.progressValue = this.PROGRESS_MAX_VALUE;
  8693. that.slideEnable = false;
  8694. that.stop();
  8695. // ToastUtil.showToast('开始重新播放')
  8696. } else if (this.playType == 3) { //3:随机播放
  8697. this.randomPlay()
  8698. }
  8699. }
  8700. }
  8701. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  8702. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  8703. onBufferingUpdate: (percent: number) => {
  8704. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  8705. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  8706. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  8707. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  8708. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  8709. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  8710. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  8711. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  8712. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  8713. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  8714. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  8715. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  8716. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  8717. let Looping = this.mIjkMediaPlayer.isLooping()
  8718. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  8719. }
  8720. }
  8721. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  8722. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  8723. onSeekComplete: () => {
  8724. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  8725. that.startPlayOrResumePlay();
  8726. }
  8727. }
  8728. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  8729. let mOnInfoListener: OnInfoListener = {
  8730. onInfo: (what: number, extra: number) => {
  8731. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  8732. that.hideLoadIng();
  8733. }
  8734. }
  8735. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  8736. let mOnErrorListener: OnErrorListener = {
  8737. onError: (what: number, extra: number) => {
  8738. this.stopProgressTask();
  8739. LogUtils.getInstance().LOGI("OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  8740. that.hideLoadIng();
  8741. if (StrUtil.isNotEmpty(this.videoUrl) && !FileUtil.accessSync(this.videoUrl)) {
  8742. ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
  8743. } else {
  8744. ToastUtil.showToast(getContext()
  8745. .resourceManager
  8746. .getStringByNameSync("Honey_the_video_is_playing_errant_The_system_is_wandering"))
  8747. }
  8748. }
  8749. }
  8750. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  8751. this.mIjkMediaPlayer.setMessageListener();
  8752. this.mIjkMediaPlayer.prepareAsync();
  8753. this.mIjkMediaPlayer.start();
  8754. }
  8755. //保存最后播放的那首歌和已经对应的播放列表
  8756. saveLastPlayList() {
  8757. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  8758. PreferencesUtil.putSync('LastMusicList', this.songList)
  8759. }
  8760. // 清空播放记录
  8761. clearVideoHistory() {
  8762. this.table.clearPlayHistory((success: boolean, error?: string) => {
  8763. if (success) {
  8764. this.historyList = [];
  8765. this.updateListData(this.historyList)
  8766. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  8767. ToastUtil.showToast('清空播放记录成功')
  8768. } else {
  8769. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  8770. }
  8771. });
  8772. }
  8773. public async setAvSessionListener() {
  8774. if (!this.avSessionController) {
  8775. return;
  8776. }
  8777. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  8778. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  8779. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  8780. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  8781. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  8782. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  8783. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  8784. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  8785. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  8786. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  8787. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  8788. }
  8789. setLoopMode() {
  8790. let itype = this.playType + 1
  8791. if (itype >= 4) {
  8792. this.playType = 0
  8793. ToastUtil.showToast('连续播放')
  8794. } else if (itype === 1) {
  8795. this.playType = 1
  8796. ToastUtil.showToast('单曲循环')
  8797. } else if (itype === 2) {
  8798. this.playType = 2
  8799. ToastUtil.showToast('单曲播完')
  8800. } else if (itype === 3) {
  8801. this.playType = 3
  8802. ToastUtil.showToast('随机播放')
  8803. } else if (itype === 0) {
  8804. this.playType = 0
  8805. ToastUtil.showToast('连续播放')
  8806. }
  8807. PreferencesUtil.putSync('musicPlayType', this.playType)
  8808. this.setCurrentPlayMode()
  8809. }
  8810. private sessionSetLoopModeCallback = (mode: number) => {
  8811. if (this.mIjkMediaPlayer != null) {
  8812. ToastUtil.showToast('当前播放模式:' + mode)
  8813. Logger.info('onecold 当前播放模式= ' + mode)
  8814. let hmPlayMode = mode + 1
  8815. if (hmPlayMode >= 4) {
  8816. hmPlayMode = 0
  8817. }
  8818. if (hmPlayMode === 1) {
  8819. this.playType = 1
  8820. ToastUtil.showToast('单曲循环')
  8821. } else if (hmPlayMode === 0) {
  8822. this.playType = 2
  8823. ToastUtil.showToast('单曲播完')
  8824. } else if (hmPlayMode === 3) {
  8825. this.playType = 3
  8826. ToastUtil.showToast('随机播放')
  8827. } else if (hmPlayMode === 2) {
  8828. this.playType = 0
  8829. ToastUtil.showToast('连续播放')
  8830. }
  8831. PreferencesUtil.putSync('musicPlayType', this.playType)
  8832. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  8833. let playBackState: avSession.AVPlaybackState = {
  8834. loopMode: hmPlayMode,
  8835. };
  8836. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  8837. console.info(`set setLoopMode AVPlaybackState successfully`);
  8838. }).catch((err: BusinessError) => {
  8839. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  8840. });
  8841. }
  8842. }
  8843. setCurrentPlayMode() {
  8844. if (!this.avSessionController) {
  8845. return;
  8846. }
  8847. let mLoopMode = 0
  8848. switch (this.playType) {
  8849. case 0:
  8850. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  8851. break;
  8852. case 1:
  8853. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  8854. break;
  8855. case 2:
  8856. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  8857. break;
  8858. case 3:
  8859. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  8860. break;
  8861. }
  8862. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  8863. let playBState: avSession.AVPlaybackState = {
  8864. loopMode: mLoopMode,
  8865. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  8866. };
  8867. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  8868. console.info(`set setLoopMode AVPlaybackState successfully`);
  8869. }).catch((err: BusinessError) => {
  8870. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  8871. });
  8872. }
  8873. private sessionToggleFavoriteCallback = (assetId: string) => {
  8874. if (this.mIjkMediaPlayer != null && this.currentSong) {
  8875. console.info(`on toggleFavorite `);
  8876. // 应用收到收藏命令,进行收藏处理。
  8877. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  8878. this.doFav(this.currentSong)
  8879. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  8880. let playbackState: avSession.AVPlaybackState = {
  8881. isFavorite: !this.isFac,
  8882. };
  8883. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  8884. console.info(`SetAVPlaybackState successfully`);
  8885. }).catch((err: BusinessError) => {
  8886. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  8887. });
  8888. }
  8889. }
  8890. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  8891. device: avSession.OutputDeviceInfo) => {
  8892. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  8893. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  8894. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  8895. await this.startCasting();
  8896. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  8897. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  8898. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  8899. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  8900. if (device) {
  8901. this.endCasting();
  8902. }
  8903. }
  8904. };
  8905. private async startCasting() {
  8906. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  8907. this.setPlaybackStateChangeListener();
  8908. this.pause();
  8909. this.initQueueItem();
  8910. this.prepare();
  8911. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  8912. refToIsCasting?.set(true);
  8913. this.castSeek = true;
  8914. this.isCastPlaying = true;
  8915. }
  8916. async changeCasting() {
  8917. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  8918. this.initQueueItem();
  8919. this.prepare();
  8920. this.setPlaybackStateChangeListener();
  8921. this.isCastPlaying = true;
  8922. this.castSeek = true;
  8923. }
  8924. public endCasting() {
  8925. this.avSessionController.getAvSession()?.stopCasting();
  8926. this.stopCast();
  8927. this.isCastPlaying = false;
  8928. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  8929. refToIsCasting?.set(false);
  8930. this.pause();
  8931. this.setIsPlaying(false);
  8932. // if (this.curIndex === this.curSource.index) {
  8933. // this.play
  8934. // this.seek(this.currentTime * 1000);
  8935. // this.setIsPlaying(true);
  8936. // } else {
  8937. // this.pauseVideo();
  8938. // this.setIsPlaying(false);
  8939. // }
  8940. }
  8941. public setIsPlaying(isPlayer: boolean) {
  8942. this.isPlaying = isPlayer;
  8943. }
  8944. private setPlaybackStateChangeListener(): void {
  8945. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  8946. this.castController?.on('endOfStream', this.reloadCasting);
  8947. this.castController?.on('playNext', this.playNextCallback);
  8948. this.castController?.on('playPrevious', this.playPreviousCallback);
  8949. }
  8950. private updateSessionPlayState(isPlay: boolean): void {
  8951. // if(!this.isBgPlayOpen)
  8952. // return
  8953. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  8954. this.setAVSessionPlayState({
  8955. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  8956. position: {
  8957. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  8958. updateTime: new Date().getTime()
  8959. }
  8960. });
  8961. }
  8962. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  8963. this.avSessionController.setAvSessionPlayState(playbackState)
  8964. }
  8965. private positionChange(position: number) {
  8966. this.currentTime2 = position / 1000;
  8967. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  8968. }
  8969. private playDurationChange(duration: number) {
  8970. this.duration = duration;
  8971. this.durationTime = Math.floor(this.duration / 1000);
  8972. this.durationStringTime = secondToTime((this.durationTime));
  8973. }
  8974. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  8975. const duration = playbackState?.extras?.duration;
  8976. if (typeof duration === 'number') {
  8977. this.playDurationChange(duration as number);
  8978. }
  8979. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  8980. this.positionChange(playbackState?.position?.elapsedTime);
  8981. }
  8982. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  8983. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  8984. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  8985. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  8986. this.isCastPlaying = false;
  8987. }
  8988. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  8989. this.isCastPlaying = true;
  8990. }
  8991. };
  8992. private reloadCasting = async () => {
  8993. let item = this.songList[this.curIndex];
  8994. let uri = fileUri.getUriFromPath(item.filePath);
  8995. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  8996. // description.startPosition = 0;
  8997. this.castItem = {
  8998. itemId: this.curIndex,
  8999. description: {
  9000. assetId: item.filePath,
  9001. title: item.name,
  9002. artist: '',
  9003. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  9004. // mediaUri: item.filePath,
  9005. fdSrc: {
  9006. fd: file.fd
  9007. },
  9008. // 该字段大写,音频'AUDIO',视频'VIDEO'
  9009. mediaType: 'VIDEO',
  9010. mediaSize: item.videoSize,
  9011. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  9012. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  9013. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  9014. duration: this.duration,
  9015. // albumCoverUri: 'https://www.example.jpeg',
  9016. // albumTitle: '《ExampleAlbum》',
  9017. appName: this.appName,
  9018. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  9019. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  9020. }
  9021. };
  9022. this.prepare();
  9023. this.isCastPlaying = true;
  9024. };
  9025. public playNextCallback = (): void => {
  9026. this.playNext()
  9027. };
  9028. public playPreviousCallback = (): void => {
  9029. this.playPrevious()
  9030. };
  9031. async prepare() {
  9032. await this.castController?.prepare(this.castItem);
  9033. await this.castController?.start(this.castItem);
  9034. }
  9035. public initQueueItem() {
  9036. let item = this.songList[this.curIndex];
  9037. let time = this.currentTime;
  9038. let uri = fileUri.getUriFromPath(item.filePath);
  9039. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  9040. this.castItem = {
  9041. itemId: this.curIndex,
  9042. description: {
  9043. assetId: item.filePath,
  9044. title: item.name,
  9045. artist: '',
  9046. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  9047. fdSrc: {
  9048. fd: file.fd
  9049. },
  9050. // 该字段大写,音频'AUDIO',视频'VIDEO'
  9051. mediaType: 'AUDIO',
  9052. mediaSize: item.videoSize,
  9053. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  9054. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  9055. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  9056. duration: this.duration,
  9057. // albumCoverUri: 'https://www.example.jpeg',
  9058. // albumTitle: '《ExampleAlbum》',
  9059. appName: this.appName,
  9060. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  9061. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  9062. }
  9063. };
  9064. }
  9065. async stopCast() {
  9066. try {
  9067. this.castController?.off('playbackStateChange');
  9068. this.castController?.off('endOfStream');
  9069. this.castController?.off('playNext');
  9070. this.castController?.off('playPrevious');
  9071. this.castController?.off('error');
  9072. } catch (error) {
  9073. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  9074. }
  9075. }
  9076. private sessionPlayCallback = (): void => {
  9077. this.playOrPause()
  9078. };
  9079. private sessionPauseCallback = (): void => {
  9080. this.playOrPause()
  9081. };
  9082. private playOrPause() {
  9083. if (!this.debounce()) {
  9084. return;
  9085. }
  9086. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  9087. this.pause();
  9088. } else {
  9089. this.startPlayOrResumePlay();
  9090. this.playChange()
  9091. }
  9092. }
  9093. private sessionPlayNextCallback = (): void => {
  9094. this.playNext()
  9095. };
  9096. private sessionPlayPreviousCallback = (): void => {
  9097. this.playPrevious()
  9098. };
  9099. private sessionStopCallback = (): void => {
  9100. this.stop()
  9101. };
  9102. private sessionFastForwardCallback = (time?: number) => {
  9103. if (!time) {
  9104. return;
  9105. }
  9106. if (this.mIjkMediaPlayer != null) {
  9107. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  9108. let seeTime = curPosition + time * 1000;
  9109. // 限制 seekValue 在合法范围内
  9110. if (seeTime < 0) {
  9111. seeTime = 0;
  9112. } else if (seeTime > this.duration) {
  9113. seeTime = this.duration;
  9114. }
  9115. Logger.info('onecold seeTime= ' + seeTime)
  9116. this.setSeekToActionProgress(seeTime)
  9117. this.seekTo(seeTime + "")
  9118. }
  9119. };
  9120. /**
  9121. * Gesture method onActionUpdate.
  9122. *
  9123. * @param event Gesture event.手势拖动设置快进和后退
  9124. */
  9125. private setSeekToActionProgress(position: number) {
  9126. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  9127. let duration = this.mIjkMediaPlayer.getDuration();
  9128. let pos = 0;
  9129. if (duration > 0) {
  9130. this.slideEnable = true;
  9131. let curPercent = position / duration;
  9132. pos = curPercent * 100;
  9133. if (pos > this.PROGRESS_MAX_VALUE) {
  9134. this.progressValue = this.PROGRESS_MAX_VALUE
  9135. } else {
  9136. this.progressValue = pos;
  9137. }
  9138. }
  9139. // LogUtils.getInstance()
  9140. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  9141. this.totalTime = this.stringForTime(duration);
  9142. if (position > duration) {
  9143. position = duration;
  9144. }
  9145. this.isCurrentTime = true;
  9146. this.currentTime = this.stringForTime(position);
  9147. this.isCurrentTime = false
  9148. }
  9149. private sessionRewindCallback = (time?: number) => {
  9150. if (!time) {
  9151. return;
  9152. }
  9153. if (this.mIjkMediaPlayer != null) {
  9154. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  9155. let seeTime = curPosition - time * 1000;
  9156. // 限制 seekValue 在合法范围内
  9157. if (seeTime < 0) {
  9158. seeTime = 0;
  9159. } else if (seeTime > this.duration) {
  9160. seeTime = this.duration;
  9161. }
  9162. Logger.info('onecold seeTime= ' + seeTime)
  9163. this.setSeekToActionProgress(seeTime)
  9164. this.seekTo(seeTime + "")
  9165. }
  9166. };
  9167. private sessionSeekCallback = (seekTime: number) => {
  9168. if (this.mIjkMediaPlayer != null) {
  9169. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  9170. this.seekTo(seekTime + "")
  9171. }
  9172. };
  9173. private async getFileSize(filePath: string): Promise<number> {
  9174. try {
  9175. const stat = await fs.stat(filePath);
  9176. return stat.size;
  9177. } catch (err) {
  9178. console.error('Failed to get file size: ' + err.message);
  9179. return 0;
  9180. }
  9181. }
  9182. private pause() {
  9183. if (this.mIjkMediaPlayer.isPlaying()) {
  9184. this.savePlaybackPosition();
  9185. this.mIjkMediaPlayer.pause();
  9186. this.setProgress();
  9187. this.mDestroyPage = true;
  9188. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  9189. this.updateSessionPlayState(false)
  9190. this.playChange()
  9191. if (this.pipController) {
  9192. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  9193. PiPWindow.PiPControlStatus.PAUSE);
  9194. }
  9195. // 广播状态变化到卡片
  9196. this.broadcastPlayerState();
  9197. }
  9198. }
  9199. private stop() {
  9200. this.savePlaybackPosition();
  9201. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9202. this.mIjkMediaPlayer.stop();
  9203. this.mIjkMediaPlayer.release();
  9204. this.stopProgressTask();
  9205. this.updateSessionPlayState(false)
  9206. this.playChange()
  9207. this.watchStatus();
  9208. // 广播状态变化到卡片
  9209. this.broadcastPlayerState();
  9210. }
  9211. //保持记忆播放功能
  9212. private savePlaybackPosition() {
  9213. if (this.mIjkMediaPlayer != null) {
  9214. const position = this.mIjkMediaPlayer.getCurrentPosition();
  9215. // ToastUtil.showToast('保存记忆播放 = ' + position)
  9216. const duration = this.mIjkMediaPlayer.getDuration();
  9217. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  9218. // 如果播放位置接近视频末尾,则保存 position 为 0
  9219. const playbackPosition = (duration - position < threshold) ? 0 : position;
  9220. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  9221. }
  9222. }
  9223. //获取记忆播放功能
  9224. private restorePlaybackPosition() {
  9225. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  9226. // ToastUtil.showToast('position = ' + position)
  9227. if (this.mIjkMediaPlayer != null && position > 0) {
  9228. // ToastUtil.showToast('seekTo = ' + position)
  9229. this.seekTo(position + "");
  9230. }
  9231. }
  9232. private seekTo(value: string) {
  9233. if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  9234. ToastUtil.showToast('wma格式不支持拖动快进。')
  9235. return
  9236. }
  9237. this.mIjkMediaPlayer.seekTo(value);
  9238. // this.startPlayOrResumePlay()
  9239. // 在这里恢复计时器状态
  9240. this.setProgress()
  9241. // this.startProgressTask();
  9242. }
  9243. // 添加到下一首播放
  9244. private addToNextPlay(song: VideoItem) {
  9245. if (!this.debounce()) {
  9246. return;
  9247. }
  9248. if (this.currentSong) {
  9249. if (this.currentSong === song) {
  9250. ToastUtil.showToast('当前已经在播放这首歌了!')
  9251. return
  9252. }
  9253. }
  9254. // 如果未开始播放或队列为空
  9255. if (this.curIndex === -1 || this.songList.length === 0) {
  9256. this.songList = [song];
  9257. this.curIndex = 0;
  9258. this.doPlay(song)
  9259. return;
  9260. }
  9261. // 插入到当前索引+1的位置
  9262. const insertPos = this.curIndex + 1;
  9263. this.songList.splice(insertPos, 0, song);
  9264. this.songList = [...this.songList]; // 触发状态更新
  9265. this.sonDataSource.pushArrayData(this.songList)
  9266. ToastUtil.showToast('已添加至下一首播放')
  9267. }
  9268. //下一个
  9269. private playNext() {
  9270. if (!this.debounce()) {
  9271. return;
  9272. }
  9273. if (this.playType == 3) { //3:随机播放
  9274. this.randomPlay()
  9275. return;
  9276. }
  9277. if (ArrayUtil.isNotEmpty(this.songList)) {
  9278. if (this.curIndex == this.songList.length - 1) {
  9279. this.curIndex = 0;
  9280. } else {
  9281. this.curIndex++;
  9282. }
  9283. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9284. this.stop();
  9285. this.currentSong = this.songList[this.curIndex]
  9286. this.videoUrl = this.songList[this.curIndex].filePath;
  9287. this.artist = this.songList[this.curIndex].artist
  9288. this.name = this.songList[this.curIndex].name
  9289. //this.cover = this.songList[this.curIndex].pixelMapPath
  9290. this.changeImageAnimation()
  9291. // 确保广播歌曲变化到卡片
  9292. setTimeout(() => {
  9293. this.broadcastPlayerState();
  9294. }, 200);
  9295. }
  9296. }
  9297. changeImageAnimation() {
  9298. if(this.openSkipSongAnimate){
  9299. // 第一步:淡出动画
  9300. this.getUIContext()?.animateTo({
  9301. duration: 500,
  9302. curve: Curve.EaseOut,
  9303. }, () => {
  9304. this.opacityValueImage = 0.1;
  9305. if(this.isCoverRectangle){
  9306. this.scaleValueImage = 0.88
  9307. }
  9308. });
  9309. // 第二步:切换图片后淡入
  9310. setTimeout(() => {
  9311. this.cover = this.songList[this.curIndex].pixelMapPath
  9312. this.getUIContext()?.animateTo({
  9313. duration: 500,
  9314. curve: Curve.EaseIn,
  9315. }, () => {
  9316. this.opacityValueImage = 1;
  9317. this.scaleValueImage = 1 // 图标恢复到原始大小
  9318. this.startPlayOrResumePlay()
  9319. });
  9320. }, 500);
  9321. }else{
  9322. this.cover = this.songList[this.curIndex].pixelMapPath
  9323. this.startPlayOrResumePlay()
  9324. // 广播歌曲变化到卡片
  9325. setTimeout(() => {
  9326. this.broadcastPlayerState();
  9327. }, 200);
  9328. }
  9329. }
  9330. // 存储已播放的歌曲索引
  9331. private playedIndices: Set<number> = new Set();
  9332. //随机播放
  9333. private randomPlay() {
  9334. // if (!this.debounce()) {
  9335. // return;
  9336. // }
  9337. if (ArrayUtil.isNotEmpty(this.songList)) {
  9338. if (this.songList.length > 3) {
  9339. // 如果所有歌曲都播放过一次,清空已播放索引集合
  9340. if (this.playedIndices.size === this.songList.length) {
  9341. this.playedIndices.clear();
  9342. }
  9343. // 随机选择一个未播放的歌曲索引
  9344. let newIndex: number;
  9345. // 添加超时机制防止无限循环
  9346. let attempt = 0;
  9347. const maxAttempts = 100; // 根据需求调整
  9348. do {
  9349. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  9350. attempt++;
  9351. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  9352. if (attempt >= maxAttempts) {
  9353. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  9354. newIndex = Math.floor(Math.random() * this.songList.length);
  9355. }
  9356. this.curIndex = newIndex;
  9357. this.playedIndices.add(newIndex);
  9358. } else {
  9359. // 当歌曲数量小于或等于3时,直接播放下一首
  9360. if (this.curIndex == this.songList.length - 1) {
  9361. this.curIndex = 0;
  9362. } else {
  9363. this.curIndex++;
  9364. }
  9365. }
  9366. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9367. this.stop();
  9368. this.currentSong = this.songList[this.curIndex];
  9369. this.videoUrl = this.songList[this.curIndex].filePath;
  9370. this.name = this.songList[this.curIndex].name;
  9371. this.artist = this.songList[this.curIndex].artist
  9372. // this.cover = this.songList[this.curIndex].pixelMapPath
  9373. this.changeImageAnimation()
  9374. }
  9375. }
  9376. private playIndex(index: number) {
  9377. if (!this.debounce()) {
  9378. return;
  9379. }
  9380. if (ArrayUtil.isNotEmpty(this.songList)) {
  9381. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9382. this.stop();
  9383. this.currentSong = this.songList[this.curIndex]
  9384. this.videoUrl = this.songList[index].filePath;
  9385. this.name = this.songList[index].name
  9386. this.artist = this.songList[this.curIndex].artist
  9387. this.curIndex = index;
  9388. this.changeImageAnimation()
  9389. }
  9390. }
  9391. //上一个
  9392. private playPrevious() {
  9393. if (!this.debounce()) {
  9394. return;
  9395. }
  9396. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  9397. this.randomModePlayFromHistory()
  9398. return;
  9399. }
  9400. if (this.curIndex == 0) {
  9401. this.curIndex = this.songList.length - 1;
  9402. } else {
  9403. this.curIndex--;
  9404. }
  9405. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9406. this.stop();
  9407. this.currentSong = this.songList[this.curIndex]
  9408. this.videoUrl = this.songList[this.curIndex].filePath;
  9409. this.name = this.songList[this.curIndex].name
  9410. this.artist = this.songList[this.curIndex].artist
  9411. this.startPlayOrResumePlay()
  9412. // 广播歌曲变化到卡片
  9413. setTimeout(() => {
  9414. this.broadcastPlayerState();
  9415. }, 200);
  9416. this.changeImageAnimation()
  9417. }
  9418. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  9419. private randomModePlayFromHistory() {
  9420. if (this.historyList.length >= 2) {
  9421. // 播放历史记录的第二首
  9422. const prevSong = this.historyList[1];
  9423. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  9424. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9425. this.stop();
  9426. this.currentSong = prevSong;
  9427. this.videoUrl = prevSong.filePath;
  9428. this.cover = prevSong.pixelMapPath
  9429. this.artist = prevSong.artist
  9430. this.name = prevSong.name;
  9431. this.startPlayOrResumePlay();
  9432. } else {
  9433. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  9434. if (this.curIndex === 0) {
  9435. this.curIndex = this.songList.length - 1;
  9436. } else {
  9437. this.curIndex--;
  9438. }
  9439. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9440. this.stop();
  9441. this.currentSong = this.songList[this.curIndex];
  9442. this.videoUrl = this.songList[this.curIndex].filePath;
  9443. this.artist = this.songList[this.curIndex].artist
  9444. this.name = this.songList[this.curIndex].name;
  9445. this.changeImageAnimation()
  9446. }
  9447. }
  9448. debounce() {
  9449. const delay = 600;
  9450. let cur = new Date().getTime();
  9451. if (cur - this.last > delay) {
  9452. this.last = cur;
  9453. return true;
  9454. }
  9455. return false;
  9456. }
  9457. /**
  9458. * Sets whether the screen is a constant based on the playback status.
  9459. */
  9460. watchStatus() {
  9461. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  9462. if (this.windowClass) {
  9463. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  9464. this.windowClass.setWindowKeepScreenOn(true);
  9465. } else {
  9466. this.windowClass.setWindowKeepScreenOn(false);
  9467. }
  9468. }
  9469. }
  9470. /**
  9471. * Volume gesture method onActionStart.
  9472. *
  9473. * @param event Gesture event.
  9474. */
  9475. private customDialogComponentIdMM: number = 0
  9476. @Builder
  9477. customDialogComponentMM() {
  9478. Column() {
  9479. Row() {
  9480. Blank()
  9481. Text('验证密码')
  9482. .fontSize(22)
  9483. .fontColor($r('app.color.pri_bg'))
  9484. .margin({ top: 18 })
  9485. Blank()
  9486. Image($r('app.media.close'))
  9487. .fillColor(Color.White)
  9488. .margin({ top: 18, right: 18 })
  9489. .width(20)
  9490. .onClick(() => {
  9491. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  9492. })
  9493. }
  9494. .width('100%') // 使Row占据整个宽度
  9495. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  9496. Verify({
  9497. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  9498. });
  9499. }.height('60%')
  9500. .backgroundColor($r('app.color.index_background'))
  9501. .justifyContent(FlexAlign.SpaceBetween)
  9502. }
  9503. private handleVerifyCompleted(isSuccess: boolean) {
  9504. if (isSuccess) {
  9505. console.log('验证成功');
  9506. // 在这里处理验证成功后的逻辑
  9507. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  9508. this.currentPath = this.lockPath
  9509. this.getSortedFiles(this.currentPath)
  9510. } else {
  9511. // console.log('验证失败');
  9512. ToastUtil.showToast('验证失败')
  9513. }
  9514. }
  9515. private showVerifyDialog() {
  9516. promptAction.openCustomDialog({
  9517. transition: TransitionEffect.asymmetric(
  9518. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  9519. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  9520. ,
  9521. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  9522. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  9523. ),
  9524. builder: () => {
  9525. this.customDialogComponentMM()
  9526. },
  9527. isModal: true,
  9528. autoCancel: true,
  9529. maskColor: Color.Transparent,
  9530. alignment: DialogAlignment.Bottom,
  9531. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  9532. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  9533. console.log("dialog onWillDismiss")
  9534. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  9535. dismissDialogAction.dismiss()
  9536. }
  9537. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  9538. dismissDialogAction.dismiss()
  9539. }
  9540. }
  9541. }).then((dialogId: number) => {
  9542. this.customDialogComponentIdMM = dialogId
  9543. })
  9544. }
  9545. //左滑操作 移动文件 重命名 删除等操作
  9546. @Builder
  9547. DeleteButton(item: VideoItem, index: number, filePath: string) {
  9548. Row() {
  9549. //加入收藏
  9550. Button() {
  9551. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  9552. .fillColor(Color.White)
  9553. .width(20)
  9554. }
  9555. .width(40)
  9556. .height(40)
  9557. .type(ButtonType.Circle)
  9558. .backgroundColor(this.themeColor)
  9559. .margin(5)
  9560. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  9561. .onClick(() => {
  9562. if (item) {
  9563. this.doFav(item)
  9564. }
  9565. })
  9566. //加入下一首播放
  9567. Button() {
  9568. Image($r('app.media.next_to_play'))
  9569. .fillColor(Color.White)
  9570. .width(20)
  9571. }
  9572. .width(40)
  9573. .height(40)
  9574. .type(ButtonType.Circle)
  9575. .backgroundColor(this.themeColor)
  9576. .margin(5)
  9577. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  9578. .onClick(() => {
  9579. this.addToNextPlay(item);
  9580. })
  9581. //复制文件
  9582. Button() {
  9583. Image($r('app.media.copy'))
  9584. .fillColor(Color.White)
  9585. .width(20)
  9586. }
  9587. .width(40)
  9588. .height(40)
  9589. .type(ButtonType.Circle)
  9590. .backgroundColor(this.themeColor)
  9591. .margin(5)
  9592. .id(filePath + 'copy')
  9593. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  9594. .onClick(() => {
  9595. this.showCopyDialog(false, item, index, filePath + 'copy');
  9596. })
  9597. //移动文件
  9598. Button() {
  9599. Image($r('app.media.cut'))
  9600. .fillColor(Color.White)
  9601. .width(20)
  9602. }
  9603. .width(40)
  9604. .height(40)
  9605. .type(ButtonType.Circle)
  9606. .backgroundColor(this.themeColor)
  9607. .margin(5)
  9608. .id(filePath)
  9609. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  9610. .onClick(() => {
  9611. this.showCutDialog(false, item, index, filePath);
  9612. })
  9613. Button() {
  9614. Image($r('app.media.cut_current'))
  9615. .fillColor(Color.White)
  9616. .width(20)
  9617. }
  9618. .width(40)
  9619. .height(40)
  9620. .type(ButtonType.Circle)
  9621. .backgroundColor(this.themeColor)
  9622. .margin(5)
  9623. .id(filePath + 'current')
  9624. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  9625. (this.isHasDir ? Visibility.Visible : Visibility.None))
  9626. .onClick(() => {
  9627. this.showCutDialog(true, item, index, filePath + 'current');
  9628. })
  9629. //重命名
  9630. Button() {
  9631. Image($r('app.media.rename2'))
  9632. .fillColor(Color.White)
  9633. .width(20)
  9634. }
  9635. .width(40)
  9636. .height(40)
  9637. .type(ButtonType.Circle)
  9638. .backgroundColor(this.themeColor)
  9639. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  9640. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  9641. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  9642. .margin(5)
  9643. .onClick(() => {
  9644. this.showReNameDialog(item, index + '', filePath)
  9645. })
  9646. Button() {
  9647. Image($r('app.media.delete2'))
  9648. .fillColor(Color.White)
  9649. .width(20)
  9650. }
  9651. .width(40)
  9652. .height(40)
  9653. .type(ButtonType.Circle)
  9654. .backgroundColor(this.themeColor)
  9655. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  9656. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  9657. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  9658. .margin(5)
  9659. .onClick(() => {
  9660. this.showWarnIsDeleteFile(item, index + '', filePath)
  9661. })
  9662. Button() {
  9663. Image($r('app.media.share2'))
  9664. .fillColor(Color.White)
  9665. .width(20)
  9666. }
  9667. .width(40)
  9668. .height(40)
  9669. .type(ButtonType.Circle)
  9670. .backgroundColor(this.themeColor)
  9671. .margin(5)
  9672. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  9673. .onClick(() => {
  9674. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  9675. })
  9676. }
  9677. }
  9678. /**
  9679. * 穿山甲banner广告
  9680. */
  9681. // private declare bannerAd: CSJNativeExpressAd;
  9682. // @State private status: string = "未加载"
  9683. // @State private isShowAd: boolean = false
  9684. // private declare mAdSlot: AdSlot;
  9685. // private mBiddingAdm = '' //服务端bidding才需要设置
  9686. // private expressLoadAdListener: NativeExpressAdListener = {
  9687. // /**
  9688. // * 加载失败的回调
  9689. // *
  9690. // * @param code
  9691. // * @param message
  9692. // */
  9693. // onError: (code: number, message: string) => {
  9694. // console.error("加载广告失败,code=" + code + ",message=" + message);
  9695. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  9696. // },
  9697. //
  9698. // /**
  9699. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  9700. // *
  9701. // * @param ads 返回的广告列表
  9702. // */
  9703. //
  9704. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  9705. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  9706. // if (ads && ads.length > 0) {
  9707. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  9708. // ad.setExpressInteractionListener({
  9709. // /**
  9710. // *广告的点击回调
  9711. // * @param type 广告的交互类型
  9712. // */
  9713. // onAdClicked: (type: number) => {
  9714. // console.log("BannerExpressAdPage==onAdClicked......");
  9715. // },
  9716. //
  9717. // /**
  9718. // * 广告的展示回调 每个广告仅回调一次
  9719. // * @param type 广告的交互类型
  9720. // */
  9721. // onAdShow: (type: number) => {
  9722. // console.log("BannerExpressAdPage==onAdShow......");
  9723. // },
  9724. //
  9725. // /**
  9726. // * 模板渲染失败
  9727. // */
  9728. // onRenderFail: (code: number, msg: string) => {
  9729. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  9730. // },
  9731. //
  9732. // /**
  9733. // * 模板渲染成功
  9734. // * @param width 返回view的宽 单位 vp
  9735. // * @param height 返回view的高 单位 vp
  9736. // */
  9737. // onRenderSuccess: (width: number, height: number) => {
  9738. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  9739. // this.bannerAd = ad;
  9740. // this.status = "广告加载完成待展示";
  9741. //
  9742. // this.showBannerAd()
  9743. // }
  9744. // })
  9745. // //渲染广告
  9746. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  9747. // this.setDislikeCallback(ad); //设置dislike
  9748. // ad.render(this.getUIContext())
  9749. // this.status = "广告加载中...";
  9750. // });
  9751. // }
  9752. // }
  9753. // }
  9754. //
  9755. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  9756. // ad.setDislikeCallback({
  9757. // /**
  9758. // * dislike show
  9759. // */
  9760. // onShow: () => {
  9761. // console.log("BannerExpressAdPage==dislike......show");
  9762. // },
  9763. //
  9764. // /**
  9765. // * @param position 选择的位置
  9766. // * @param value 选择的内容
  9767. // * @param enforceRemove 是否强制关闭广告
  9768. // */
  9769. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  9770. // this.isShowAd = false;
  9771. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  9772. // ",enforce=" + enforceRemove);
  9773. // },
  9774. //
  9775. // /**
  9776. // * 点击取消
  9777. // */
  9778. // onCancel: () => {
  9779. // console.log("BannerExpressAdPage==dislike......onCancel");
  9780. // }
  9781. //
  9782. // })
  9783. // }
  9784. /**
  9785. * 加载Banner广告
  9786. */
  9787. loadBannerAd(rit: string) {
  9788. // if (Utility.isNoble()) {
  9789. // return
  9790. // }
  9791. // if (!Utility.isPassInstallTime(2)) {
  9792. // return
  9793. // }
  9794. // this.isShowAd = false;
  9795. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  9796. // this.mAdSlot = new AdSlotBuilder()
  9797. // .setCodeId(rit)
  9798. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  9799. // .setAdCount(1)
  9800. // .setBidAdm(this.mBiddingAdm)
  9801. // .build()
  9802. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  9803. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  9804. // this.status = "广告加载中..."
  9805. }
  9806. /**
  9807. * 展示Banner广告
  9808. */
  9809. // showBannerAd() {
  9810. // if (!this.bannerAd) {
  9811. // return
  9812. // }
  9813. // this.isShowAd = true
  9814. // this.status = "已展示"
  9815. // }
  9816. /**
  9817. * 穿山甲广告代码结束
  9818. */
  9819. /**
  9820. * 初始化卡片事件监听器
  9821. */
  9822. private async initWidgetEventListener(): Promise<void> {
  9823. try {
  9824. // 创建订阅信息
  9825. const subscribeInfo: commonEventManager.CommonEventSubscribeInfo = {
  9826. events: [
  9827. WIDGET_CONTROL_EVENT,
  9828. WIDGET_REQUEST_STATE_EVENT
  9829. ]
  9830. };
  9831. // 创建订阅者
  9832. this.widgetEventSubscriber = await commonEventManager.createSubscriber(subscribeInfo);
  9833. // 订阅事件
  9834. await commonEventManager.subscribe(this.widgetEventSubscriber, (err, data: commonEventManager.CommonEventData) => {
  9835. if (!err) {
  9836. this.handleWidgetEvent(data);
  9837. } else {
  9838. LogUtils.getInstance().error(`Widget event subscription error: ${JSON.stringify(err)}`);
  9839. }
  9840. });
  9841. // 初始化AvSession卡片监听器
  9842. this.initAvSessionWidgetListener();
  9843. LogUtils.getInstance().LOGI('Widget event listener initialized successfully');
  9844. } catch (error) {
  9845. LogUtils.getInstance().error(`Failed to initialize widget event listener: ${error}`);
  9846. }
  9847. }
  9848. /**
  9849. * 初始化AvSession卡片监听器
  9850. */
  9851. private initAvSessionWidgetListener(): void {
  9852. try {
  9853. // 注册AvSession状态变化监听器,用于同步卡片状态
  9854. this.avSessionWidgetListener.addStateListener((widgetData) => {
  9855. // AvSession状态变化时,自动广播到卡片
  9856. this.broadcastAvSessionStateToWidget(widgetData);
  9857. });
  9858. LogUtils.getInstance().LOGI('AvSession widget listener initialized successfully');
  9859. } catch (error) {
  9860. LogUtils.getInstance().error(`Failed to initialize AvSession widget listener: ${error}`);
  9861. }
  9862. }
  9863. /**
  9864. * 广播AvSession状态到卡片
  9865. */
  9866. private broadcastAvSessionStateToWidget(widgetData: WidgetData): void {
  9867. try {
  9868. // 广播播放状态变化
  9869. const statePublishInfo: commonEventManager.CommonEventPublishData = {
  9870. data: JSON.stringify(widgetData)
  9871. };
  9872. commonEventManager.publish(PLAYER_STATE_CHANGED_EVENT, statePublishInfo, (err) => {
  9873. if (err) {
  9874. LogUtils.getInstance().error(`Failed to broadcast AvSession state: ${JSON.stringify(err)}`);
  9875. } else {
  9876. LogUtils.getInstance().LOGI('AvSession state broadcasted to widget successfully');
  9877. }
  9878. });
  9879. // 如果有歌曲信息变化,也广播歌曲变化事件
  9880. if (widgetData.currentSong) {
  9881. const songPublishInfo: commonEventManager.CommonEventPublishData = {
  9882. data: JSON.stringify({ currentSong: widgetData.currentSong })
  9883. };
  9884. commonEventManager.publish(PLAYER_SONG_CHANGED_EVENT, songPublishInfo, (err) => {
  9885. if (err) {
  9886. LogUtils.getInstance().error(`Failed to broadcast song change: ${JSON.stringify(err)}`);
  9887. }
  9888. });
  9889. }
  9890. // 如果有进度信息变化,也广播进度变化事件
  9891. if (widgetData.progress) {
  9892. const progressPublishInfo: commonEventManager.CommonEventPublishData = {
  9893. data: JSON.stringify(widgetData.progress)
  9894. };
  9895. commonEventManager.publish(PLAYER_PROGRESS_CHANGED_EVENT, progressPublishInfo, (err) => {
  9896. if (err) {
  9897. LogUtils.getInstance().error(`Failed to broadcast progress change: ${JSON.stringify(err)}`);
  9898. }
  9899. });
  9900. }
  9901. } catch (error) {
  9902. LogUtils.getInstance().error(`Failed to broadcast AvSession state to widget: ${error}`);
  9903. }
  9904. }
  9905. /**
  9906. * 处理卡片事件
  9907. */
  9908. private handleWidgetEvent(eventData: commonEventManager.CommonEventData): void {
  9909. try {
  9910. LogUtils.getInstance().LOGI(`Received widget event: ${eventData.event}, data: ${eventData.data}`);
  9911. if (eventData.event === WIDGET_CONTROL_EVENT) {
  9912. // 处理控制命令
  9913. this.handleWidgetControlCommand(eventData.data || '{}');
  9914. } else if (eventData.event === WIDGET_REQUEST_STATE_EVENT) {
  9915. // 处理状态请求
  9916. this.handleWidgetStateRequest();
  9917. }
  9918. } catch (error) {
  9919. LogUtils.getInstance().error(`Failed to handle widget event: ${error}`);
  9920. }
  9921. }
  9922. /**
  9923. * 处理卡片控制命令
  9924. */
  9925. private handleWidgetControlCommand(dataStr: string): void {
  9926. try {
  9927. const eventData = JSON.parse(dataStr) as EventData;
  9928. LogUtils.getInstance().LOGI(`Processing widget command: ${eventData.command}`);
  9929. switch (eventData.command) {
  9930. case WidgetCommand.PLAY_PAUSE:
  9931. this.playOrPause();
  9932. break;
  9933. case WidgetCommand.NEXT_SONG:
  9934. this.playNext();
  9935. break;
  9936. case WidgetCommand.PREV_SONG:
  9937. this.playPrevious();
  9938. break;
  9939. case WidgetCommand.SEEK_TO:
  9940. if (eventData.params && eventData.params.percentage !== undefined) {
  9941. this.handleWidgetSeekTo(eventData.params.percentage);
  9942. }
  9943. break;
  9944. case WidgetCommand.OPEN_APP:
  9945. // 应用已经在运行,不需要额外操作
  9946. LogUtils.getInstance().LOGI('Widget requested to open app - already running');
  9947. break;
  9948. case WidgetCommand.OPEN_PLAYER:
  9949. // 应用已经在运行,可以切换到播放页面
  9950. this.handleWidgetOpenPlayer();
  9951. break;
  9952. default:
  9953. LogUtils.getInstance().warn(`Unknown widget command: ${eventData.command}`);
  9954. break;
  9955. }
  9956. // 命令处理完成后,广播状态更新
  9957. setTimeout(() => {
  9958. this.broadcastPlayerState();
  9959. }, 100);
  9960. } catch (error) {
  9961. LogUtils.getInstance().error(`Failed to handle widget control command: ${error}`);
  9962. }
  9963. }
  9964. /**
  9965. * 处理卡片状态请求
  9966. */
  9967. private handleWidgetStateRequest(): void {
  9968. try {
  9969. LogUtils.getInstance().LOGI('Processing widget state request');
  9970. this.broadcastPlayerState();
  9971. } catch (error) {
  9972. LogUtils.getInstance().error(`Failed to handle widget state request: ${error}`);
  9973. }
  9974. }
  9975. /**
  9976. * 处理卡片进度跳转
  9977. */
  9978. private handleWidgetSeekTo(percentage: number): void {
  9979. try {
  9980. if (this.mIjkMediaPlayer && this.duration > 0) {
  9981. const targetPosition = (percentage / 100) * this.duration;
  9982. this.seekTo(targetPosition.toString());
  9983. LogUtils.getInstance().LOGI(`Widget seek to: ${percentage}% (${targetPosition}ms)`);
  9984. // 延迟广播状态更新,确保seekTo操作完成
  9985. setTimeout(() => {
  9986. this.broadcastPlayerState();
  9987. }, 300);
  9988. }
  9989. } catch (error) {
  9990. LogUtils.getInstance().error(`Failed to handle widget seek: ${error}`);
  9991. }
  9992. }
  9993. /**
  9994. * 处理卡片打开播放器请求
  9995. */
  9996. private handleWidgetOpenPlayer(): void {
  9997. try {
  9998. // 如果当前不在播放页面,切换到播放页面
  9999. if (!this.isShowPlay) {
  10000. this.isShowPlay = true;
  10001. LogUtils.getInstance().LOGI('Widget opened player page');
  10002. }
  10003. } catch (error) {
  10004. LogUtils.getInstance().error(`Failed to handle widget open player: ${error}`);
  10005. }
  10006. }
  10007. /**
  10008. * 节流广播进度更新
  10009. */
  10010. private broadcastProgressIfNeeded(): void {
  10011. const now = Date.now();
  10012. if (now - this.lastProgressBroadcastTime >= this.PROGRESS_BROADCAST_INTERVAL) {
  10013. this.lastProgressBroadcastTime = now;
  10014. this.broadcastPlayerProgress();
  10015. }
  10016. }
  10017. /**
  10018. * 广播播放进度到卡片
  10019. */
  10020. private broadcastPlayerProgress(): void {
  10021. try {
  10022. const currentPos = this.mIjkMediaPlayer?.getCurrentPosition() || 0;
  10023. const progressData: PlayProgress = {
  10024. currentPosition: currentPos,
  10025. duration: this.duration || 0,
  10026. percentage: this.duration > 0 ? (currentPos / this.duration) * 100 : 0,
  10027. currentTimeText: this.currentTime || '00:00',
  10028. totalTimeText: this.totalTime || '00:00'
  10029. };
  10030. // 广播播放进度变化
  10031. const publishInfo: commonEventManager.CommonEventPublishData = {
  10032. data: JSON.stringify(progressData)
  10033. };
  10034. commonEventManager.publish(PLAYER_PROGRESS_CHANGED_EVENT, publishInfo, (err) => {
  10035. if (err) {
  10036. LogUtils.getInstance().error(`Failed to broadcast player progress: ${JSON.stringify(err)}`);
  10037. } else {
  10038. LogUtils.getInstance().LOGI(`Progress broadcasted: ${progressData.percentage.toFixed(1)}%`);
  10039. }
  10040. });
  10041. } catch (error) {
  10042. LogUtils.getInstance().error(`Failed to broadcast player progress: ${error}`);
  10043. }
  10044. }
  10045. /**
  10046. * 强制更新卡片状态(用于测试和调试)
  10047. */
  10048. public forceUpdateWidgetState(): void {
  10049. LogUtils.getInstance().LOGI('Force updating widget state...');
  10050. LogUtils.getInstance().LOGI(`Current state: PlayStatus=${this.CONTROL_PlayStatus}, songTitle=${this.name}, curIndex=${this.curIndex}, songListLength=${this.songList.length}`);
  10051. this.broadcastPlayerState();
  10052. }
  10053. /**
  10054. * 广播播放器状态到卡片
  10055. */
  10056. private broadcastPlayerState(): void {
  10057. try {
  10058. LogUtils.getInstance().LOGI(`Broadcasting player state: CONTROL_PlayStatus=${this.CONTROL_PlayStatus}, PlayStatus.PLAY=${PlayStatus.PLAY}, PlayStatus.PAUSE=${PlayStatus.PAUSE}`);
  10059. const playState: PlayState = {
  10060. isPlaying: this.CONTROL_PlayStatus === PlayStatus.PLAY,
  10061. isPaused: this.CONTROL_PlayStatus === PlayStatus.PAUSE,
  10062. isLoading: this.CONTROL_PlayStatus === PlayStatus.LOADING
  10063. };
  10064. LogUtils.getInstance().LOGI(`PlayState created: isPlaying=${playState.isPlaying}, isPaused=${playState.isPaused}, isLoading=${playState.isLoading}`);
  10065. const currentSong: SongInfo = {
  10066. id: this.currentSong?.id || '',
  10067. title: this.name || '暂无播放',
  10068. artist: this.artist || '未知艺术家',
  10069. album: this.currentSong?.album || '未知专辑',
  10070. coverImagePath: this.cover || '',
  10071. duration: this.duration || 0
  10072. };
  10073. const progress: PlayProgress = {
  10074. currentPosition: this.mIjkMediaPlayer?.getCurrentPosition() || 0,
  10075. duration: this.duration || 0,
  10076. percentage: this.duration > 0 ? ((this.mIjkMediaPlayer?.getCurrentPosition() || 0) / this.duration) * 100 : 0,
  10077. currentTimeText: this.stringForTime(this.mIjkMediaPlayer?.getCurrentPosition() || 0),
  10078. totalTimeText: this.stringForTime(this.duration || 0)
  10079. };
  10080. const hasNext = this.curIndex < this.songList.length - 1;
  10081. const hasPrevious = this.curIndex > 0;
  10082. // 添加详细的按钮状态日志
  10083. LogUtils.getInstance().LOGI(`Button state calculation: curIndex=${this.curIndex}, songListLength=${this.songList.length}, hasNext=${hasNext}, hasPrevious=${hasPrevious}`);
  10084. const playlist: PlaylistState = {
  10085. hasNext: hasNext,
  10086. hasPrevious: hasPrevious,
  10087. currentIndex: this.curIndex,
  10088. totalCount: this.songList.length
  10089. };
  10090. // 添加调试日志
  10091. LogUtils.getInstance().LOGI(`Widget playlist state: curIndex=${this.curIndex}, songListLength=${this.songList.length}, hasNext=${hasNext}, hasPrevious=${hasPrevious}`);
  10092. // 创建完整的WidgetData对象
  10093. const widgetData: WidgetData = {
  10094. playState: playState,
  10095. currentSong: currentSong,
  10096. progress: progress,
  10097. playlist: playlist,
  10098. config: {
  10099. size: 'medium',
  10100. theme: 'auto',
  10101. showProgress: true,
  10102. showCover: true
  10103. }
  10104. };
  10105. // 更新AvSession监听器的数据
  10106. this.avSessionWidgetListener.updateWidgetData(widgetData);
  10107. // 直接通过全局服务更新卡片数据(解决跨进程通信问题)
  10108. try {
  10109. interface GlobalWidgetServiceInstance {
  10110. updateWidgetData(data: WidgetData): void;
  10111. }
  10112. interface GlobalWidgetServiceClass {
  10113. getInstance(): GlobalWidgetServiceInstance;
  10114. }
  10115. interface GlobalWidgetServiceModule {
  10116. GlobalWidgetService: GlobalWidgetServiceClass;
  10117. }
  10118. import('../common/widget/GlobalWidgetService').then((module: GlobalWidgetServiceModule) => {
  10119. const globalWidgetService = module.GlobalWidgetService.getInstance();
  10120. globalWidgetService.updateWidgetData(widgetData);
  10121. LogUtils.getInstance().LOGI('Global widget service updated successfully');
  10122. }).catch((error: Error) => {
  10123. LogUtils.getInstance().error(`Failed to import GlobalWidgetService: ${error}`);
  10124. });
  10125. } catch (error) {
  10126. LogUtils.getInstance().error(`Direct widget update failed: ${error}`);
  10127. }
  10128. const stateData: PlayerStateBroadcastData = {
  10129. playState: playState,
  10130. currentSong: currentSong,
  10131. progress: progress,
  10132. playlist: playlist
  10133. };
  10134. // 广播播放状态变化
  10135. const publishInfo: commonEventManager.CommonEventPublishData = {
  10136. data: JSON.stringify(stateData)
  10137. };
  10138. commonEventManager.publish(PLAYER_STATE_CHANGED_EVENT, publishInfo, (err) => {
  10139. if (err) {
  10140. LogUtils.getInstance().error(`Failed to broadcast player state: ${JSON.stringify(err)}`);
  10141. } else {
  10142. LogUtils.getInstance().LOGI(`Player state broadcasted successfully: hasNext=${hasNext}, hasPrevious=${hasPrevious}, songTitle=${currentSong.title}`);
  10143. }
  10144. });
  10145. // 单独广播进度更新事件
  10146. const progressPublishInfo: commonEventManager.CommonEventPublishData = {
  10147. data: JSON.stringify(progress)
  10148. };
  10149. commonEventManager.publish(PLAYER_PROGRESS_CHANGED_EVENT, progressPublishInfo, (err) => {
  10150. if (err) {
  10151. LogUtils.getInstance().error(`Failed to broadcast progress: ${JSON.stringify(err)}`);
  10152. }
  10153. });
  10154. } catch (error) {
  10155. LogUtils.getInstance().error(`Failed to broadcast player state: ${error}`);
  10156. }
  10157. }
  10158. }
  10159. //视频气泡窗口的布局
  10160. @Builder
  10161. function customPopupBuilder(dataBu: BubbleBean) {
  10162. List() {
  10163. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  10164. ListItem() {
  10165. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10166. Row() {
  10167. Column() {
  10168. Image(dataBu.imageRes[index])
  10169. .height(28)
  10170. .fillColor(dataBu.color)
  10171. .alignSelf(ItemAlign.Center)
  10172. }
  10173. .width(32)
  10174. Text(item)
  10175. .padding({
  10176. top: 10,
  10177. bottom: 10,
  10178. right: 10,
  10179. left: 10
  10180. })
  10181. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  10182. .textAlign(TextAlign.Start)
  10183. .width("100%")
  10184. }
  10185. }
  10186. .backgroundColor($r('app.color.settings_background_main'))
  10187. .margin({ top: 6, bottom: 6 })
  10188. }
  10189. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  10190. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  10191. TransitionEffect.scale({ x: 0, y: 0 })))
  10192. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  10193. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  10194. .onClick(() => {
  10195. dataBu.onItemClick?.(index)
  10196. })
  10197. })
  10198. }
  10199. .width(120)
  10200. .divider({
  10201. strokeWidth: 1,
  10202. color: "#22FFFFFF"
  10203. })
  10204. }
  10205. // Function to calculate a hash for the file list
  10206. function simpleHash(fileList: string[]): string {
  10207. let hash = 0;
  10208. const str = fileList.join(',');
  10209. for (let i = 0; i < str.length; i++) {
  10210. const char = str.charCodeAt(i);
  10211. hash = (hash << 5) - hash + char;
  10212. hash |= 0; // Convert to 32bit integer
  10213. }
  10214. return hash.toString();
  10215. }
  10216. interface MoreItem {
  10217. id: number;
  10218. image: Resource;
  10219. title: string;
  10220. }
  10221. //视频气泡窗口的布局
  10222. @Builder
  10223. function cutPopupBuilder(dataBu: BubbleBean) {
  10224. Column() {
  10225. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  10226. .padding({
  10227. top: 10,
  10228. bottom: 10,
  10229. right: 10,
  10230. left: 10
  10231. })
  10232. .textAlign(TextAlign.Start)
  10233. .width(160)
  10234. .fontWeight(666)
  10235. .fontSize(16)
  10236. List() {
  10237. ForEach(dataBu.data, (item: string, index: number) => {
  10238. ListItem() {
  10239. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10240. Row() {
  10241. Column() {
  10242. Image($r('app.media.music_group'))
  10243. .height(28)
  10244. .fillColor(dataBu.color)
  10245. .alignSelf(ItemAlign.Center)
  10246. }
  10247. .width(32)
  10248. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  10249. .padding({
  10250. top: 10,
  10251. bottom: 10,
  10252. right: 10,
  10253. left: 10
  10254. })
  10255. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  10256. .fontSize(15)
  10257. }
  10258. }
  10259. .backgroundColor(Color.Transparent)
  10260. .margin({ top: 7, bottom: 7 })
  10261. }
  10262. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  10263. .animation({ duration: 500 }),
  10264. TransitionEffect.scale({ x: 0, y: 0 })))
  10265. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  10266. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  10267. .onClick(() => {
  10268. dataBu.onItemClick?.(index)
  10269. })
  10270. })
  10271. }
  10272. .width(150)
  10273. .divider({
  10274. strokeWidth: 1,
  10275. color: "#22FFFFFF"
  10276. })
  10277. }
  10278. .height(300)
  10279. .padding({
  10280. bottom: 30
  10281. })
  10282. }