LocalMusic.ets 398 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798
  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 { BusinessError, emitter } from '@kit.BasicServicesKit';
  25. import { BubbleBean } from '../viewmodel/BubbleBean';
  26. import { PopupPosition, XPopup } from '@chinalike/popup';
  27. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  28. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  29. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  30. import { MessageEvents, util, worker, ErrorEvent } from '@kit.ArkTS';
  31. import { Verify } from './Verify';
  32. import { RotatingCover } from './RotatingCover';
  33. import { PlayConstants } from '../common/constants/PlayConstants';
  34. import { effectKit } from '@kit.ArkGraphics2D';
  35. import { ColorConversion } from '../common/util/ColorConversion';
  36. import { LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  37. import { AvSessionController } from '../controller/AvSessionController';
  38. import { repairAudioMetadata, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
  39. import { FFMpegTags,Utility } from '../common/util/Utility';
  40. import {
  41. // DeviceChangeReason,
  42. IjkMediaPlayer,
  43. InterruptEvent,
  44. InterruptHintType,
  45. LogUtils,
  46. OnBufferingUpdateListener,
  47. OnCompletionListener,
  48. OnErrorListener,
  49. OnInfoListener,
  50. OnPreparedListener,
  51. OnSeekCompleteListener,
  52. OnTimedTextListener,
  53. OnVideoSizeChangedListener
  54. } from '@ohos/ijkplayer';
  55. import { PlayStatus } from '../common/PlayStatus';
  56. import fs from '@ohos.file.fs';
  57. import { image } from '@kit.ImageKit';
  58. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  59. import { UniversalDetector } from '@ohos/juniversalchardet';
  60. import { SettingPage } from '../pages/SettingPage';
  61. import { secondToTime } from '../common/util/CommUtils';
  62. import { CommonConstants2 } from '../common/util/CommonConstants2';
  63. import { hilog } from '@kit.PerformanceAnalysisKit';
  64. import { LazyDataSource } from '../common/util/LazyDataSource';
  65. import MediaTable from '../common/util/MediaTable';
  66. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  67. import ImageUtils from '../common/util/ImageUtils';
  68. import { ringtone } from '@kit.RingtoneKit';
  69. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  70. import { resourceManager } from '@kit.LocalizationKit';
  71. import { deviceInfo } from '@kit.BasicServicesKit';
  72. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  73. import app from '@system.app';
  74. import { TextNodeController } from './PipLyricTextBuilder';
  75. import { IndexerView } from './IndexerView';
  76. import { KeyCode } from '@kit.InputKit';
  77. import { KnockController } from '../controller/KnockController';
  78. // import { FFmpeg, FFProgressMessageParser } from '@sj/ffmpeg';
  79. const TAG = 'LocalMusic';
  80. const DEFAULT_INDEX =
  81. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  82. 'X', 'Y', 'Z']
  83. //排序类型
  84. function getTypeOrder(type: number) {
  85. switch (type) {
  86. case CommonConstants.TYPE_IS_DIR:
  87. return 1; // First
  88. case CommonConstants.TYPE_IS_CSJAD:
  89. return 2; // Middle
  90. case CommonConstants.TYPE_LOCAL:
  91. return 3; // Last
  92. default:
  93. return 4; // Unknown types, if any, go last
  94. }
  95. }
  96. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  97. // 定义接口
  98. interface HiCarAspectRatio {
  99. ratio: number;
  100. name: string;
  101. }
  102. interface GeneratedObjectLiteralInterface_1 {
  103. assetId: string;
  104. title: string;
  105. artist: string;
  106. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  107. mediaUri: string;
  108. // 该字段大写,音频'AUDIO',视频'VIDEO'
  109. mediaType: string;
  110. mediaSize: number;
  111. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  112. startPosition: number;
  113. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  114. duration: number;
  115. albumCoverUri: string;
  116. albumTitle: string;
  117. appName: string;
  118. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  119. drmScheme: string;
  120. }
  121. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  122. const ITEM_HEIGHT: number = 58; // 列表项中高度
  123. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  124. //功能强大的音乐播放器
  125. @Preview
  126. @Component
  127. export struct LocalMusic {
  128. @State opacityValueImage: number = 1;
  129. @State tipPopup:boolean = false
  130. @Consume mType: number;
  131. @StorageProp('themeColor') themeColor: string =
  132. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  133. themeMode: number = 0;
  134. @State titleName: string = '首页'
  135. @State textStr: string = ''
  136. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  137. // private download_path: string = '';
  138. @Consume rootPath: string //音频根目录
  139. @Consume currentPath: string
  140. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  141. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  142. @State lockPath: string = ''
  143. @State favPath: string = ''
  144. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  145. @State historyPath: string = ''
  146. @State historyList: Array<VideoItem> = []
  147. @Consume isHistory: boolean
  148. static readonly HISTORY_MUSIC: string = 'music_historyList';
  149. private table: MediaTable = new MediaTable(getContext(this))
  150. @State isZero: boolean = false
  151. @State fileList: Array<string> = []
  152. @State dirList: Array<VideoItem> = []
  153. @Consume videoLocalList: Array<VideoItem>
  154. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  155. @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  156. @State artistList: Array<VideoItem> = []; //艺术家文件
  157. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  158. @State albumList: Array<VideoItem> = []; //专辑文件
  159. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  160. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  161. @State imageOpacities: number[] = [];
  162. @Consume isCanBack: boolean
  163. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  164. @State showSingleLyric: boolean = false
  165. @State sortType: number = 4 //默认排序方式
  166. @State isShowSimi: boolean = false //是否显示私密音频
  167. @State isShowFAV: boolean = true //是否显示我的收藏
  168. @State isShowTitleBar: boolean = true //是否显示分类导航条
  169. @State isShowAllBar: boolean = true //是否显示播放全部条
  170. @State isShowHistory: boolean = true //是否显示最近播放
  171. @State isCustomizeBg: boolean = false //自定义背景界面
  172. @State isGridMusic: boolean = false //是否网格布局
  173. @State isCircleBtn: boolean = false //是否圆形播放按钮
  174. @State twoFingerType: number = 3 //双支放大缩小的类型
  175. @State isScrollHide: boolean = false //是否滚动隐藏
  176. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  177. @State isStartAutoPlay: boolean = false //启动后自动播放
  178. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  179. @State isShowHeader: boolean = true
  180. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  181. @State isShowSingleLineLyric: boolean = false //是否显示播放页返回键
  182. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  183. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  184. @State isSwipe: boolean = false //listItem的左滑开关
  185. @State openSkipSongAnimate: boolean = true//切歌动画效果
  186. @State customizeBgPath: string | undefined = '';
  187. @State isDarkMode: boolean = false
  188. @State lyricTextWeight: number = 400
  189. @State lyricTextWeightPip: number = 400
  190. @State currentSwiperIndex: number = 0
  191. @State blurValue: number = 0 //背景模糊
  192. @State bgBrightness: number = 0 //背景亮度
  193. private listScroller: ListScroller = new ListScroller()
  194. private playListScroller: Scroller = new Scroller()
  195. @StorageProp('isLandscape') isLandscape: boolean = false;
  196. @StorageProp('topRectHeight') topRectHeight: number = px2vp(AppUtil.getStatusBarHeight());
  197. @StorageProp('windowWidth') windowWidth: number = 0;
  198. @StorageProp('windowHeight') windowHeight: number = 0;
  199. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  200. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  201. private UNKONWN:string = '';
  202. private listArea: Area = {
  203. width: 0,
  204. height: 0,
  205. position: {},
  206. globalPosition: {}
  207. }
  208. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  209. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  210. onColorModeChange() {
  211. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  212. if (this.isCustomizeBg) {
  213. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  214. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  215. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  216. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  217. } else {
  218. if (!this.isDarkMode) {
  219. this.titleBarModel.setTitleBarBackground(this.themeColor)
  220. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  221. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  222. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  223. } else {
  224. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  225. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  226. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  227. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  228. }
  229. }
  230. }
  231. onModeChange() {
  232. this.isFavMusic = false
  233. if (this.modeType === 2 || this.modeType === 3) {
  234. this.titleBarModel.setRightIcon(null)
  235. } else {
  236. this.titleBarModel.setRightIcon(($r('app.media.add')))
  237. }
  238. LogUtil.info('onecold onModeChange = ' + this.modeType)
  239. switch (this.modeType) {
  240. case 0:
  241. this.getSortedFiles(this.currentPath)
  242. break
  243. case 1:
  244. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  245. this.updateListData(this.mediaKuList)
  246. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  247. break
  248. case 2:
  249. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  250. this.updateListData(this.artistList)
  251. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  252. break
  253. case 3:
  254. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  255. this.updateListData(this.albumList)
  256. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  257. break
  258. }
  259. }
  260. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  261. // @StorageLink('isPlay') isPlay: boolean = false;
  262. @StorageLink('isShowPlay') isShowPlay: boolean = false;
  263. @StorageLink('songList') songList: Array<VideoItem> = [];
  264. @State translateY: number = 0;
  265. @State isShowSheet: boolean = false;
  266. @State isShowSheetView: boolean = false;
  267. @State isShowTimeCloseView: boolean = false;
  268. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  269. @StorageLink('currIndex') curIndex: number = 0;
  270. @Consume isShowDrawer: boolean;
  271. @Consume offsetX: number;
  272. @State isFac: boolean = false;
  273. @State favList: Array<VideoItem> = []
  274. @Consume isFavMusic: boolean
  275. @State isClickedPLayAll: boolean = false;
  276. private scrollerForlist: ListScroller = new ListScroller();
  277. private knockController: KnockController | undefined = undefined;
  278. imagesF: ImageFrameInfo[] = [
  279. { src: $r("app.media.app_loading0") },
  280. { src: $r("app.media.app_loading1") },
  281. { src: $r("app.media.app_loading2") },
  282. { src: $r("app.media.app_loading3") },
  283. ]
  284. @State animationState: AnimationStatus = AnimationStatus.Initial
  285. // 缓存机制
  286. private cache: Map<string, Array<VideoItem>> = new Map();
  287. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  288. // 持久化缓存
  289. private async saveCacheToStorage() {
  290. const cacheArray = Array.from(this.cache.entries());
  291. const stringCacheArray = Array.from(this.stringCache.entries());
  292. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  293. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  294. }
  295. // 载入缓存
  296. private async loadCacheFromStorage() {
  297. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  298. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  299. if (cacheString) {
  300. const cacheArray: [string, Array<VideoItem>][] = JSON.parse(cacheString);
  301. this.cache = new Map(cacheArray);
  302. }
  303. if (stringCacheString) {
  304. const stringCacheArray: [string, string][] = JSON.parse(stringCacheString);
  305. this.stringCache = new Map(stringCacheArray);
  306. }
  307. }
  308. // 查找缓存
  309. private findCache(key: string): Array<VideoItem> | undefined {
  310. return this.cache.get(key);
  311. }
  312. // 查找字符串缓存
  313. private findStringCache(key: string): string | undefined {
  314. return this.stringCache.get(key);
  315. }
  316. // 添加缓存
  317. private addCache(key: string, value: Array<VideoItem>) {
  318. this.cache.set(key, value);
  319. }
  320. // 添加字符串缓存
  321. private addStringCache(key: string, value: string) {
  322. this.stringCache.set(key, value);
  323. }
  324. // 删除缓存
  325. private deleteCache(key: string) {
  326. this.cache.delete(key);
  327. this.saveCacheToStorage()
  328. }
  329. // 删除字符串缓存
  330. private deleteStringCache(key: string) {
  331. this.stringCache.delete(key);
  332. }
  333. // 多选机制
  334. @State selectedFiles: Array<VideoItem> = [];
  335. @State isMultiSelect: boolean = false;
  336. @State isAllSelected: boolean = false;
  337. @State appName: string = ''
  338. @State isHasDir: boolean = false
  339. @State packName: string = ''
  340. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  341. @State titleBarModel: TitleBar.Model = new TitleBar.Model()
  342. .setTitleTextStyle(FontStyle.Normal)
  343. .setTitleBarStyle(TitleBar.BarStyle.TRANSPARENT)
  344. .setLeftIcon($r('app.media.menu'))
  345. .setLeftIconWidth(26)
  346. .setLeftIconHeight(26)
  347. .setTitleName('首页')
  348. .setTitleFontSize(18)
  349. .setTitleFontColor(Color.White)
  350. .setTitleBarBackground(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  351. .setTitleBarBottomLineColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  352. .setLeftTitleStateNormalStyleColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  353. .setRightIcon($r('app.media.add'))
  354. .setOnRightClickListener(() => {
  355. this.showSheelDialog()
  356. })
  357. // .setOnTitleClickListener(() => {
  358. // this.showPupDialog()
  359. // })
  360. .setOnLeftClickListener(() => {
  361. this.doSwipBack()
  362. })
  363. doSwipBack() {
  364. if (this.modeType !== 0 && this.isCanBack) {
  365. this.onModeChange()
  366. this.isCanBack = false
  367. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  368. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  369. setTimeout(() => {
  370. if (this.modeType == 2) {
  371. if (this.isGridMusic) {
  372. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  373. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  374. } else {
  375. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  376. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  377. }
  378. } else if (this.modeType == 3) {
  379. if (this.isGridMusic) {
  380. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  381. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  382. } else {
  383. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  384. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  385. }
  386. }
  387. }, 200)
  388. return
  389. }
  390. if (this.isHistory || this.isFavMusic) {
  391. this.isHistory = false
  392. this.getSortedFiles(this.currentPath)
  393. return
  394. }
  395. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  396. animateTo({ duration: 555 }, () => {
  397. // 动画闭包内控制Image组件的出现和消失
  398. this.isShowDrawer = !this.isShowDrawer
  399. this.offsetX = 0
  400. })
  401. return
  402. }
  403. //返回上一级歌单的滚动位置
  404. setTimeout(() => {
  405. if (this.modeType == 0) {
  406. if (this.isGridMusic) {
  407. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  408. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  409. } else {
  410. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  411. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  412. }
  413. }
  414. }, 300)
  415. this.currentPath = Utility.getParentDirectory(this.currentPath)
  416. Logger.info('this.currentPath2 = ' + this.currentPath)
  417. this.getSortedFiles(this.currentPath)
  418. }
  419. // 组件生命周期
  420. aboutToAppear() {
  421. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  422. this.tipPopup = !this.tipPopup
  423. PreferencesUtil.putSync('isFirstTiped',false)
  424. }
  425. this.initSetting()
  426. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  427. this.topRectHeight = px2vp(AppUtil.getStatusBarHeight());
  428. Utility.getAppName(getContext(this)).then((appName: string) => {
  429. this.appName = appName
  430. })
  431. this.packName = AppUtil.getBundleName()
  432. this.loadCacheFromStorage(); // 加载缓存
  433. this.mkDownLoadDir()
  434. let eventMusic: emitter.InnerEvent = { eventId: 2 }
  435. // 监听广播事件(打开其他应用处理)
  436. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  437. this.saveVideoDatas([eventData.data?.message], true)
  438. });
  439. //侧滑广播接收时间
  440. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: 888 }
  441. // 监听广播事件(打开其他应用处理)
  442. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  443. animateTo({ duration: 555 }, () => {
  444. this.doSwipBack()
  445. })
  446. });
  447. //ScanFilePage广播接收时间
  448. let eventScanUpdate: emitter.InnerEvent = { eventId: 101 }
  449. // 监听ScanFilePage广播事件(更新数据库)
  450. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  451. this.doUpdateData()
  452. });
  453. let eventSetting: emitter.InnerEvent = { eventId: 333 }
  454. // 监听广播事件(通用设置配置更新)
  455. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  456. this.doChangeSetting()
  457. });
  458. let event: Callback<InterruptEvent> = (event) => {
  459. LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  460. this.savePlaybackPosition()
  461. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  462. this.pause();
  463. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  464. this.startPlayOrResumePlay();
  465. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  466. this.stop();
  467. }
  468. }
  469. this.mIjkMediaPlayer.on('audioInterrupt', event);
  470. // 音频设备断连回调处理
  471. // let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  472. // LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  473. // if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  474. // this.pause();
  475. // }
  476. // }
  477. // this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  478. this.makeWorker()
  479. //折叠屏的屏幕显示模式变化
  480. display.on('foldDisplayModeChange', (data) => {
  481. this.doChangeBarHeight()
  482. });
  483. display.on('foldStatusChange', (data) => {
  484. Logger.info('onecold foldStatusChange ')
  485. });
  486. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  487. // 读取 themeMode 并同步 currentColorMode
  488. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  489. this.applyThemeMode(this.themeMode)
  490. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  491. AppStorage.setOrCreate('themeColor', themeColor);
  492. this.themeColor = themeColor;
  493. this.doChangeSetting()
  494. this.windowClass.on('windowSizeChange', (size) => {
  495. LogUtil.info('onecold windowSizeChange')
  496. this.doChangeBarHeight()
  497. let viewWidth = px2vp(size.width);
  498. let viewHeight = px2vp(size.height);
  499. if(this.isPhoneLan()){
  500. this.is_auto_hide_progress = false
  501. if(this.isHiCar()){
  502. return
  503. }
  504. setTimeout(() => {
  505. this.is_auto_hide_progress = true
  506. }, 6000)
  507. }else{
  508. this.startAutoHide()
  509. }
  510. });
  511. this.eventHub.on('onStateChange', (fg: boolean) => {
  512. if (fg && this.curState === 'STARTED') {
  513. this.stopPip();
  514. }
  515. });
  516. }
  517. startAutoHide() {
  518. if(this.isHiCar()){
  519. return
  520. }
  521. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  522. console.info('onecold startAutoHide')
  523. this.is_auto_hide_progress = false
  524. setTimeout(() => {
  525. this.is_auto_hide_progress = true
  526. }, 6000)
  527. }
  528. }
  529. applyThemeMode(mode: number) {
  530. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  531. if (mode === 1) {
  532. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  533. } else if (mode === 2) {
  534. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  535. }
  536. AppStorage.setOrCreate('currentColorMode', colorMode)
  537. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  538. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  539. AppStorage.setOrCreate('themeMode', mode)
  540. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  541. // 只有强制浅色/深色时才主动设置
  542. const context = getContext(this) as common.UIAbilityContext
  543. context.getApplicationContext().setColorMode(colorMode)
  544. }
  545. initSetting() {
  546. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  547. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  548. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  549. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, true)
  550. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  551. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  552. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  553. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  554. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  555. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  556. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  557. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  558. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  559. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 3)
  560. this.isCoverTop = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP, false)
  561. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  562. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  563. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  564. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  565. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  566. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  567. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  568. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  569. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, false)
  570. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  571. //如果是hicar连接状态,这些都是false
  572. if(this.isHiCar()){
  573. this.isShowTitleBar = false//不显示导航栏
  574. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  575. {
  576. this.isShowHeader = false//二级菜单不显示头部
  577. this.isGridMusic= false//用list不用网格
  578. this.isCoverTopBig = false
  579. }
  580. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  581. }
  582. if (this.isSavePlayMode) {
  583. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  584. }
  585. if (this.isCustomizeBg) {
  586. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  587. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  588. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  589. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  590. } else {
  591. if (!this.isDarkMode) {
  592. this.titleBarModel.setTitleBarBackground(this.themeColor)
  593. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  594. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  595. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  596. } else {
  597. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  598. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  599. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  600. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  601. }
  602. }
  603. }
  604. doChangeSetting() {
  605. this.initSetting()
  606. this.deleteCache(this.currentPath)
  607. if (this.modeType === 0) {
  608. this.getSortedFiles(this.currentPath)
  609. }
  610. }
  611. doChangeBarHeight() {
  612. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  613. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  614. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  615. this.setBarHeightNormal()
  616. }
  617. }
  618. onPageShow() {
  619. this.knockController?.immersiveListening();
  620. app.setImageCacheCount(100);
  621. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  622. app.setImageRawDataCacheSize(104857600);
  623. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  624. }
  625. //开启线程查看各个数据库
  626. makeWorker() {
  627. setTimeout(() => {
  628. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  629. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  630. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  631. // workerInstance.postMessage({
  632. // code: 1,
  633. // data1: this.context,
  634. // data2: this.rootPath,
  635. // data3: this.lockPath,
  636. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  637. // });
  638. PreferencesUtil.putSync('isFirstApp', false)
  639. } else {
  640. workerInstance.postMessage({ code: 2, data: this.context });
  641. workerInstance.postMessage({ code: 3, data: this.context });
  642. workerInstance.postMessage({ code: 4, data: this.context });
  643. this.getHistoryList(false)
  644. }
  645. }, 1000)
  646. workerInstance.onmessage = (e: MessageEvents): void => {
  647. switch (e.data.code) {
  648. case 101: //第一次扫描文件夹入库
  649. ToastUtil.showToast('刷新同步数据库成功!')
  650. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  651. this.doUpdateData()
  652. break;
  653. case 102: //查询媒体库列表
  654. this.mediaKuList = e.data.data
  655. Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
  656. Utility.doSortListAscending(this.mediaKuList)
  657. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  658. if (this.modeType === 1) {
  659. this.updateListData(this.mediaKuList)
  660. }
  661. break;
  662. case 103: //收到查询艺术家列表
  663. this.artistMap = e.data.data1;
  664. this.artistList = e.data.data2;
  665. break;
  666. case 104: //收到查询专辑列表
  667. this.albumMap = e.data.data1;
  668. this.albumList = e.data.data2
  669. //查询完毕在启动是否自动播放
  670. if (this.isStartAutoPlay) {
  671. this.startPlayOrResumePlay()
  672. }
  673. break;
  674. }
  675. };
  676. // 在调用terminate后,执行onexit
  677. workerInstance.onexit = (code) => {
  678. console.log("main thread terminate");
  679. }
  680. //若Worker处于已销毁或正在销毁等非运行状态时,调用其功能接口,会抛出相应的错误。
  681. // 使用Worker模块时,需要在主线程中注册onerror接口,否则当worker线程出现异常时会发生jscrash问题。
  682. workerInstance.onerror = (err: ErrorEvent) => {
  683. console.log("onerror" + err.message);
  684. }
  685. // let context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
  686. //碰一碰分享的监听
  687. this.knockController = KnockController.getInstance(this.context);
  688. this.knockController?.immersiveListening();
  689. }
  690. onPageHide(): void {
  691. this.knockController?.immersiveDisableListening();
  692. }
  693. @State isFirstStartPlay: boolean = false
  694. //获取download_path
  695. async mkDownLoadDir() {
  696. const documentViewPicker = new picker.DocumentViewPicker()
  697. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  698. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  699. // this.rootPath = this.download_path
  700. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  701. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  702. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  703. Logger.info('onecold rootPath = ' + this.rootPath)
  704. Logger.info('onecold lockPath = ' + this.lockPath)
  705. if (!FileUtil.accessSync(this.lockPath)) {
  706. FileUtil.mkdirSync(this.lockPath)
  707. }
  708. if (!FileUtil.accessSync(this.favPath)) {
  709. FileUtil.mkdirSync(this.favPath)
  710. }
  711. if (!FileUtil.accessSync(this.historyPath)) {
  712. FileUtil.mkdirSync(this.historyPath)
  713. }
  714. this.getSortedFiles(this.rootPath).then(() => {
  715. this.isFavMusic = false
  716. //穿山甲
  717. // this.loadBannerAd(CSJUtil.getBannerID())
  718. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  719. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  720. if (ArrayUtil.isEmpty(this.songList)) {
  721. this.songList = this.getCurFileList()
  722. } else {
  723. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  724. }
  725. if (ArrayUtil.isNotEmpty(this.songList)) {
  726. this.isFirstStartPlay = true
  727. this.sonDataSource.pushArrayData(this.songList)
  728. if (this.currentSong === undefined) {
  729. this.isFirstStartPlay = false
  730. this.currentSong = this.songList[0]
  731. }
  732. this.videoUrl = this.currentSong.filePath
  733. this.name = this.currentSong.name
  734. this.cover = this.currentSong.pixelMapPath
  735. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  736. } else {
  737. this.name = '空空如也'
  738. }
  739. })
  740. this.getFavList(false)
  741. }
  742. getFavList(isFavRefresh: boolean) {
  743. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  744. this.favList = result
  745. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  746. this.videoLocalList = this.favList
  747. this.updateListData(this.videoLocalList)
  748. }
  749. })
  750. }
  751. getHistoryList(isRefresh: boolean) {
  752. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  753. this.historyList = result
  754. // for (let i = 0; i < this.historyList.length; i++) {
  755. //
  756. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  757. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  758. // }
  759. if (isRefresh) {
  760. this.videoLocalList = this.historyList
  761. this.updateListData(this.videoLocalList, true)
  762. }
  763. })
  764. }
  765. // 组件消失生命周期
  766. aboutToDisappear() {
  767. console.info('LifeCycleComponent aboutToDisappear');
  768. this.knockController?.immersiveDisableListening();
  769. this.curIndex = 0
  770. emitter.off(2);
  771. emitter.off(101);
  772. emitter.off(888);
  773. emitter.off(333);
  774. this.mDestroyPage = true;
  775. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  776. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  777. this.stop();
  778. }
  779. this.mIjkMediaPlayer.off('audioInterrupt');
  780. if (workerInstance) {
  781. workerInstance.terminate();
  782. }
  783. this.stopPip();
  784. this.destroyPipController()
  785. }
  786. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean) {
  787. this.isFavMusic = false
  788. if (isWorkerPost) {
  789. workerInstance.postMessage({ code: 2, data: this.context }); //刷新媒体库列表
  790. }
  791. if (this.modeType !== 0) {
  792. return
  793. }
  794. this.isCanBack = false
  795. this.currentPath = curPath
  796. this.titleBarModel.setTitleName(getFileDirName(this.currentPath, this.rootPath))
  797. if (curPath === this.rootPath) {
  798. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  799. } else {
  800. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  801. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  802. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  803. }
  804. }
  805. // Get the current file list and calculate its hash
  806. this.fileList = FileUtil.listFileSync(curPath);
  807. const currentHash = simpleHash(this.fileList);
  808. // Check cache
  809. const cachedValue = this.findCache(curPath);
  810. Logger.info('onecold cachedValue = ' + cachedValue)
  811. const cachedHash = this.findStringCache(curPath + '_hash');
  812. const cachedDirList = this.findCache(curPath + "_dirList");
  813. if (cachedValue !== undefined) {
  814. // this.videoLocalList = cachedValue;
  815. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  816. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  817. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  818. }
  819. this.updateListData(cachedValue)
  820. }
  821. if (cachedDirList !== undefined) {
  822. this.dirList = cachedDirList
  823. }
  824. //通过当前hash值和缓存hash判断list有没有变化
  825. if (cachedValue && cachedHash === currentHash) {
  826. return;
  827. }
  828. this.fileList = FileUtil.listFileSync(curPath)
  829. let directories: Array<VideoItem> = [];
  830. let files: Array<VideoItem> = [];
  831. for (let i = 0; i < this.fileList.length; i++) {
  832. console.info(`The name of file: ${this.fileList[i]}`);
  833. let path = curPath + '/' + this.fileList[i]
  834. if (FileUtil.isDirectory(path)) {
  835. let item: VideoItem =
  836. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  837. '')
  838. if (this.isShowDir(item.name)) {
  839. directories.push(item);
  840. }
  841. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  842. // Utility.doSortListAscending(directories)
  843. } else {
  844. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  845. let item: VideoItem =
  846. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  847. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  848. files.push(item);
  849. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  850. // this.doSortListAscending(files)
  851. }
  852. }
  853. }
  854. }
  855. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  856. if (this.currentPath !== this.lockPath) {
  857. files = result;
  858. }
  859. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  860. Utility.doSortListAscending(files)
  861. if (this.currentPath === this.rootPath) {
  862. this.dirList = directories
  863. this.addCache(curPath + "_dirList", this.dirList);
  864. }
  865. //插入广告先注释掉
  866. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  867. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  868. // directories.push(adItem)
  869. // }
  870. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  871. this.videoLocalList = directories.concat(files);
  872. this.updateListData(this.videoLocalList)
  873. if (ArrayUtil.isNotEmpty(files)) {
  874. if (this.currentPath != this.rootPath) {
  875. if (files) {
  876. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  877. }
  878. }
  879. // 缓存结果
  880. this.addCache(curPath, this.videoLocalList);
  881. await this.saveCacheToStorage(); // 保存缓存至本地存储
  882. this.addStringCache(curPath + '_hash', currentHash);
  883. }
  884. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  885. // for (let i = 0; i < this.videoLocalList.length; i++) {
  886. //
  887. // console.info(`onecold gengxin 1: ${this.videoLocalList[i].pixelMapPath}`);
  888. //
  889. // }
  890. // this.setButtonStatus()
  891. if (isOpen) {
  892. if (destPath === undefined) {
  893. // 处理 destPath 为 undefined 的情况
  894. return
  895. }
  896. if (destPath.endsWith('.lrc')) {
  897. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  898. if (StrUtil.isNotEmpty(this.videoUrl)) {
  899. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  900. this.initLyric(lyricPath);
  901. }
  902. return
  903. }
  904. let item2 = new VideoItem(Utility.getMediaNameByUri(destPath), destPath, destPath, 0, 0, '')
  905. this.doPlay(item2)
  906. this.isShowPlay = true
  907. }
  908. });
  909. }
  910. //扫描文件夹入库
  911. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  912. const files = FileUtil.listFileSync(curPath);
  913. let mediaItems: VideoItem[] = [];
  914. Logger.info('onecold scanDirectory start ')
  915. for (const file of files) {
  916. const fPath = `${curPath}/${file}`;
  917. if (fPath === this.lockPath) {
  918. Logger.info(`Skipping locked path: ${fPath}`);
  919. continue;
  920. }
  921. if (FileUtil.isDirectory(fPath)) {
  922. // Recursively scan subdirectories
  923. const subDirItems = await this.scanDirectory(fPath);
  924. mediaItems = mediaItems.concat(subDirItems);
  925. } else {
  926. Logger.info('onecold scanDirectory filePath = ' + fPath)
  927. // Process media files
  928. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  929. let mediaItem: VideoItem =
  930. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, true);
  931. mediaItems.push(mediaItem);
  932. this.table.insert(mediaItem, (id: number) => {
  933. });
  934. }
  935. }
  936. }
  937. return mediaItems;
  938. }
  939. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  940. animateTo({ duration: 888 }, () => {
  941. this.opacityItem = 0;
  942. });
  943. setTimeout(() => {
  944. this.videoLocalList = mList;
  945. if (!noSort) {
  946. if (this.modeType === 0 || this.modeType === 1) {
  947. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  948. this.doSortType(this.sortType)
  949. }
  950. }
  951. this.dataSource.pushArrayData(this.videoLocalList)
  952. animateTo({ duration: 888 }, () => {
  953. this.opacityItem = 1;
  954. });
  955. this.setButtonStatus()
  956. }, 200);
  957. }
  958. //排序模式和多选模式
  959. showPupDialog() {
  960. if (this.modeType === 2 || this.modeType === 3) {
  961. this.titleBarModel.setRightIcon(null)
  962. } else {
  963. this.titleBarModel.setRightIcon(($r('app.media.add')))
  964. }
  965. let dataBean = new BubbleBean()
  966. dataBean.data = ["首页", "媒体库", "艺术家", "专辑", "同步数据"]
  967. dataBean.color = this.themeColor
  968. dataBean.modeType = this.modeType
  969. dataBean.imageRes =
  970. [$r('app.media.home_press'), $r('app.media.kp_music'), $r('app.media.music_menu'), $r('app.media.llq'),
  971. $r('app.media.refresh')]
  972. let pup: XPopup;
  973. if (this.isDarkMode) {
  974. pup = XPopup.Builder()
  975. .setPopupPosition(PopupPosition.BOTTOM)
  976. .atView('pup_positon_music')
  977. .setBackgroundColor(Color.Black)
  978. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  979. .show()
  980. } else {
  981. pup = XPopup.Builder()
  982. .setPopupPosition(PopupPosition.BOTTOM)
  983. .atView('pup_positon_music')
  984. .setBackgroundColor(Color.White)
  985. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  986. .show()
  987. }
  988. dataBean.onItemClick = (i) => {
  989. XPopup.dismissTop()
  990. switch (i) {
  991. case 0: //首页
  992. this.modeType = 0
  993. this.getSortedFiles(this.currentPath)
  994. break
  995. case 1:
  996. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  997. this.modeType = 1
  998. this.updateListData(this.mediaKuList)
  999. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  1000. break
  1001. case 2:
  1002. this.modeType = 2
  1003. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1004. this.updateListData(this.artistList)
  1005. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  1006. break
  1007. case 3:
  1008. this.modeType = 3
  1009. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1010. this.updateListData(this.albumList)
  1011. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  1012. break
  1013. case 4: //同步数据
  1014. this.asyncCurrentPathData()
  1015. break
  1016. }
  1017. }
  1018. }
  1019. getCurFileList(): Array<VideoItem> {
  1020. let files: Array<VideoItem> = [];
  1021. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1022. for (let i = 0; i < this.videoLocalList.length; i++) {
  1023. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  1024. files.push(this.videoLocalList[i]);
  1025. }
  1026. }
  1027. }
  1028. return files
  1029. }
  1030. setButtonStatus() {
  1031. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1032. this.isZero = false
  1033. } else {
  1034. this.isZero = true
  1035. }
  1036. if (this.currentPath !== this.rootPath &&
  1037. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  1038. this.isHasDir = true //不为空,说明有子文件夹
  1039. } else {
  1040. this.isHasDir = false
  1041. }
  1042. }
  1043. showRankDialog() {
  1044. if (this.modeType === 2 || this.modeType === 3) {
  1045. //动作面板
  1046. DialogHelper.showBottomSheetDialog({
  1047. title: "请选择排序模式",
  1048. maskColor: Color.Transparent,
  1049. // sheets: ["按名称升序", "按名称降序"],
  1050. sheets: [
  1051. { value: '按名称升序', fontColor: $r('app.color.text_color') },
  1052. { value: '按名称降序', fontColor: $r('app.color.text_color') },
  1053. ],
  1054. backgroundColor: $r('app.color.bg_card'),
  1055. height: '30%',
  1056. transition: AnimationHelper.transitionInDown(555),
  1057. onAction: (index) => {
  1058. switch (index) {
  1059. case 0:
  1060. Utility.doSortListAscending(this.videoLocalList)
  1061. break;
  1062. case 1:
  1063. Utility.doSortListDescending(this.videoLocalList)
  1064. break;
  1065. }
  1066. this.updateListData(this.videoLocalList)
  1067. }
  1068. })
  1069. return
  1070. }
  1071. //动作面板
  1072. DialogHelper.showBottomSheetDialog({
  1073. title: "请选择排序模式",
  1074. maskColor: Color.Transparent,
  1075. height: '75%',
  1076. // sheets: ["按艺术家升序", "按艺术家降序", "按专辑升序", "按专辑降序", "按名称升序", "按名称降序", "按添加时间升序","按添加时间降序"],
  1077. sheets: [
  1078. { value: "按艺术家升序", fontColor: $r('app.color.text_color') },
  1079. { value: "按艺术家降序", fontColor: $r('app.color.text_color') },
  1080. { value: "按专辑升序", fontColor: $r('app.color.text_color') },
  1081. { value: "按专辑降序", fontColor: $r('app.color.text_color') },
  1082. { value: "按名称升序", fontColor: $r('app.color.text_color') },
  1083. { value: "按名称降序", fontColor: $r('app.color.text_color') },
  1084. { value: "按添加时间升序", fontColor: $r('app.color.text_color') },
  1085. { value: "按添加时间降序", fontColor: $r('app.color.text_color') },
  1086. ],
  1087. backgroundColor: $r('app.color.bg_card'),
  1088. transition: AnimationHelper.transitionInDown(555),
  1089. onAction: (index) => {
  1090. this.doSortType(index)
  1091. PreferencesUtil.put(SettingPage.SORT_TYPE, index)
  1092. this.updateListData(this.videoLocalList, true)
  1093. }
  1094. })
  1095. }
  1096. doSortType(index: number) {
  1097. switch (index) {
  1098. case 0:
  1099. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1100. // 类型排序优先级
  1101. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1102. if (typeOrder !== 0) {
  1103. return typeOrder;
  1104. }
  1105. // 处理艺术家可能为undefined的字符串比较
  1106. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1107. const artistB = b.artist?.trim() || '';
  1108. return artistA.localeCompare(artistB);
  1109. });
  1110. break;
  1111. case 1:
  1112. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1113. // 类型排序优先级
  1114. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1115. if (typeOrder !== 0) {
  1116. return typeOrder;
  1117. }
  1118. // 处理艺术家可能为undefined的字符串比较
  1119. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1120. const artistB = b.artist?.trim() || '';
  1121. return artistB.localeCompare(artistA);
  1122. });
  1123. break;
  1124. case 2:
  1125. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1126. // 类型排序优先级
  1127. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1128. if (typeOrder !== 0) {
  1129. return typeOrder;
  1130. }
  1131. // 处理专辑可能为undefined的字符串比较
  1132. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1133. const albumB = b.album?.trim() || '';
  1134. return albumA.localeCompare(albumB);
  1135. });
  1136. break;
  1137. case 3:
  1138. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1139. // 类型排序优先级
  1140. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1141. if (typeOrder !== 0) {
  1142. return typeOrder;
  1143. }
  1144. // 处理专辑可能为undefined的字符串比较
  1145. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1146. const albumB = b.album?.trim() || '';
  1147. return albumB.localeCompare(albumA);
  1148. });
  1149. break;
  1150. case 4:
  1151. Utility.doSortListAscending(this.videoLocalList)
  1152. break;
  1153. case 5:
  1154. Utility.doSortListDescending(this.videoLocalList)
  1155. break;
  1156. case 6:
  1157. this.videoLocalList.sort((a, b) => {
  1158. // First, sort by type
  1159. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1160. if (typeOrder !== 0) {
  1161. return typeOrder;
  1162. }
  1163. // If types are the same, sort by cTime in ascending order
  1164. return a.cTime.localeCompare(b.cTime);
  1165. });
  1166. break;
  1167. case 7:
  1168. this.videoLocalList.sort((a, b) => {
  1169. // First, sort by type
  1170. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1171. if (typeOrder !== 0) {
  1172. return typeOrder;
  1173. }
  1174. // If types are the same, sort by cTime in descending order
  1175. return b.cTime.localeCompare(a.cTime);
  1176. });
  1177. break;
  1178. }
  1179. }
  1180. showSheelDialog() {
  1181. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  1182. // this.showTips()
  1183. // return
  1184. // }
  1185. this.showAddDialog()
  1186. }
  1187. showAddDialog() {
  1188. if (this.modeType === 2 || this.modeType === 3) {
  1189. return
  1190. }
  1191. DialogHelper.showActionSheetDialog({
  1192. title: "请选择添加方式(建议歌词文件一起导入)",
  1193. // sheets: ["新建歌单", "手动导入", "自动导入"],
  1194. sheets: [
  1195. { value: "新建歌单", fontColor: $r('app.color.text_color') },
  1196. { value: "手动导入", fontColor: $r('app.color.text_color') },
  1197. { value: "自动导入", fontColor: $r('app.color.text_color') },
  1198. { value: "全选导入", fontColor: $r('app.color.text_color') },
  1199. ],
  1200. maskColor: Color.Transparent,
  1201. backgroundColor: $r('app.color.bg_card'),
  1202. transition: AnimationHelper.transitionInDown(555),
  1203. onAction: (index) => {
  1204. switch (index) {
  1205. case 0:
  1206. if (this.modeType === 0) {
  1207. this.showMkDialog()
  1208. } else {
  1209. ToastUtil.showToast('请切换到首页才能新建歌单!')
  1210. }
  1211. break;
  1212. case 1:
  1213. this.callFilePickerSelectFile()
  1214. break;
  1215. case 2:
  1216. this.showTips()
  1217. break;
  1218. case 3:
  1219. this.goSelectMusic()
  1220. break;
  1221. }
  1222. }
  1223. })
  1224. }
  1225. //拉起音频
  1226. goSelectMusic() {
  1227. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  1228. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  1229. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  1230. ) {
  1231. ToastUtil.showToast('暂时不支持该设备')
  1232. return
  1233. }
  1234. try {
  1235. let documentSelectOptions = new picker.DocumentSelectOptions();
  1236. documentSelectOptions.authMode = true
  1237. documentSelectOptions.multiAuthMode = true
  1238. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  1239. let documentPicker = new picker.DocumentViewPicker(this.context);
  1240. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  1241. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  1242. this.saveVideoDatas(documentSelectResult)
  1243. }
  1244. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  1245. JSON.stringify(documentSelectResult));
  1246. }).catch((err: BusinessError) => {
  1247. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  1248. });
  1249. } catch (error) {
  1250. let err: BusinessError = error as BusinessError;
  1251. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1252. }
  1253. }
  1254. async showTips() {
  1255. DialogHelper.showTipsDialog({
  1256. title: '使用提示:自动导入教程',
  1257. content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  1258. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  1259. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  1260. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  1261. onAction: (action) => {
  1262. if (action == DialogAction.TWO) {
  1263. PreferencesUtil.putSync('isFirstMusic', false)
  1264. router.pushUrl({
  1265. url: 'pages/ScanFilePage'
  1266. });
  1267. }
  1268. }
  1269. })
  1270. }
  1271. showMkDialog() {
  1272. DialogHelper.showTextInputDialog({
  1273. title: '新建歌单',
  1274. maskColor: Color.Transparent,
  1275. text: '',
  1276. transition: AnimationHelper.transitionInDown(666),
  1277. onChange: (text) => {
  1278. console.error("onChange: " + text);
  1279. },
  1280. onAction: (action, dialogId, content) => {
  1281. // ToastUtil.showToast('content = ' +content)
  1282. if (action == DialogAction.TWO) {
  1283. const newName = content
  1284. const newPath = this.currentPath + '/' + newName
  1285. FileUtil.mkdir(newPath, true).then(() => {
  1286. this.cache.delete(this.currentPath); // 删除目标路径缓存
  1287. this.getSortedFiles(this.currentPath)
  1288. }).catch((error: BusinessError) => {
  1289. console.error(error.message);
  1290. });
  1291. }
  1292. }
  1293. })
  1294. }
  1295. @State progress: number = 0;
  1296. async saveVideoDatas(uris: string[], isOpen?: boolean) {
  1297. if (ArrayUtil.isEmpty(uris)) {
  1298. return;
  1299. }
  1300. let newUris: string[] = [];
  1301. this.progress = 0
  1302. DialogHelper.showLoadingProgress({
  1303. progress: this.progress,
  1304. backCancel: false,
  1305. autoCancel: false,
  1306. loadColor: this.themeColor,
  1307. fontColor: this.themeColor
  1308. });
  1309. // 计算所有文件的总大小
  1310. let totalSize = 0;
  1311. for (let uri of uris) {
  1312. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  1313. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  1314. await fileIo.close(sourceFile.fd);
  1315. }
  1316. let totalRead = 0;
  1317. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  1318. Logger.info(TAG, 'destPath uri: ' + destPath);
  1319. for (let i = 0; i < uris.length; i++) {
  1320. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  1321. Logger.info(TAG, 'filePath uri: ' + filePath);
  1322. newUris.push(filePath);
  1323. try {
  1324. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  1325. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  1326. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  1327. const buffer = new ArrayBuffer(buffSize);
  1328. let len = await fileIo.read(sourceFile.fd, buffer);
  1329. while (len > 0) {
  1330. await fileIo.write(destFile.fd, buffer.slice(0, len));
  1331. totalRead += len;
  1332. // 计算总进度
  1333. this.progress = Math.floor((totalRead / totalSize) * 100);
  1334. DialogHelper.updateLoading('正在导入', this.progress);
  1335. len = await fileIo.read(sourceFile.fd, buffer);
  1336. }
  1337. await fileIo.close(sourceFile.fd);
  1338. await fileIo.close(destFile.fd);
  1339. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  1340. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  1341. let mediaItem: VideoItem =
  1342. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, true);
  1343. this.table.insert(mediaItem, (id: number) => {
  1344. // 删除目标路径缓存
  1345. this.cache.delete(this.currentPath);
  1346. this.getSortedFiles(this.currentPath, true, destPath, isOpen)
  1347. });
  1348. }
  1349. }
  1350. } catch (error) {
  1351. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  1352. }
  1353. }
  1354. DialogHelper.closeLoading()
  1355. this.isZero = false
  1356. // setTimeout(() => {
  1357. // // 删除目标路径缓存
  1358. // this.cache.delete(this.currentPath);
  1359. // this.getSortedFiles(this.currentPath,true,destPath,isOpen)
  1360. // }, 500);
  1361. Logger.info(TAG, 'scan select video result:' + newUris)
  1362. }
  1363. //拉起音频
  1364. // goSelectMusic(){
  1365. //
  1366. // try {
  1367. // let audioSelectOptions = new picker.AudioSelectOptions();
  1368. // let audioPicker = new picker.AudioViewPicker(this.context);
  1369. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  1370. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  1371. // this.saveVideoDatas(audioSelectResult)
  1372. // }
  1373. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  1374. // }).catch((err: BusinessError) => {
  1375. //
  1376. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  1377. // });
  1378. // } catch (error) {
  1379. // let err: BusinessError = error as BusinessError;
  1380. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1381. // }
  1382. //
  1383. //
  1384. //
  1385. // }
  1386. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  1387. if (!item) {
  1388. return undefined;
  1389. }
  1390. try {
  1391. let selectUris: Array<string> = [];
  1392. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  1393. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  1394. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  1395. photoSelectOptions.maxSelectNumber = 1;
  1396. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  1397. selectUris = photoSelectResult.photoUris;
  1398. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  1399. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  1400. console.info('file fd: ' + file.fd);
  1401. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  1402. let imagePath = this.context.filesDir + FileUtil.separator + name
  1403. imagePath = fileUri.getUriFromPath(imagePath)
  1404. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  1405. fileIo.copyFileSync(file.fd, file2.fd)
  1406. fileIo.closeSync(file);
  1407. fileIo.closeSync(file2);
  1408. if (item.filePath == this.currentSong?.filePath) {
  1409. this.cover = imagePath
  1410. }
  1411. if (item) {
  1412. item.pixelMapPath = imagePath
  1413. }
  1414. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  1415. if (success) {
  1416. this.doUpdateData()
  1417. console.log("onecold 更新音乐封面成功,数据库已同步");
  1418. } else {
  1419. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  1420. }
  1421. });
  1422. LogUtil.debug("onecold this.cover =" + this.cover)
  1423. return FileUtil.getFilePath(imagePath); // Return the image path here
  1424. } catch (err) {
  1425. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  1426. return undefined;
  1427. }
  1428. }
  1429. // 拉起picker选择文件管理器
  1430. async callFilePickerSelectFile(): Promise<void> {
  1431. try {
  1432. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  1433. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  1434. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  1435. } else {
  1436. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  1437. }
  1438. let documentPicker = new picker.DocumentViewPicker();
  1439. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  1440. Logger.info(TAG,
  1441. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  1442. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  1443. this.saveVideoDatas(DocumentSelectResult)
  1444. }
  1445. }).catch((err: BusinessError) => {
  1446. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  1447. });
  1448. } catch (err) {
  1449. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  1450. }
  1451. }
  1452. showWarnIsDeleteFile(item: VideoItem, index: string, filePath: string) {
  1453. //操作确认类弹出框
  1454. DialogHelper.showAlertDialog({
  1455. maskColor: Color.Transparent,
  1456. content: "确定要删除这个文件吗?",
  1457. backgroundColor: Color.Grey,
  1458. transition: AnimationHelper.transitionInUp(555),
  1459. onAction: (action) => {
  1460. if (action == DialogAction.ONE) {
  1461. // ToastUtil.showToast(`您点击了取消按钮`);
  1462. } else if (action == DialogAction.TWO) {
  1463. // ToastUtil.showToast(`您点击了确认按钮`);
  1464. this.doDelete(item, index + '', filePath)
  1465. }
  1466. }
  1467. })
  1468. }
  1469. //删除单个索引index的视频
  1470. doDelete(item: VideoItem, index: string, filePath: string) {
  1471. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1472. Logger.info(TAG, 'delete filePath = ' + filePath);
  1473. if (item.type === CommonConstants.TYPE_IS_DIR) {
  1474. //旧文件删除
  1475. this.table.deleteDataForParentPath(item.filePath, () => {
  1476. FileUtil.rmdir(filePath).then(() => {
  1477. this.videoLocalList.splice(Number(index), 1)
  1478. this.deleteCache(this.currentPath)
  1479. this.getSortedFiles(this.currentPath, true)
  1480. }).catch((error: BusinessError) => {
  1481. console.error(error.message);
  1482. });
  1483. });
  1484. } else {
  1485. this.table.deleteData(item, () => {
  1486. FileUtil.unlink(filePath)
  1487. .catch((error: BusinessError) => {
  1488. console.error(error.message);
  1489. // 可以根据 error.code 判断是否为"文件不存在",如需特殊处理
  1490. })
  1491. .finally(() => {
  1492. this.videoLocalList.splice(Number(index), 1)
  1493. this.deleteCache(this.currentPath)
  1494. this.getSortedFiles(this.currentPath, true)
  1495. });
  1496. });
  1497. }
  1498. }
  1499. }
  1500. //重命名的对话框
  1501. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  1502. DialogHelper.showTextInputDialog({
  1503. title: '重命名',
  1504. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  1505. maskColor: Color.Transparent,
  1506. backgroundColor: Color.Grey,
  1507. transition: AnimationHelper.transitionInDown(666),
  1508. onChange: (text) => {
  1509. console.error("onChange: " + text);
  1510. },
  1511. onAction: (action, dialogId, content) => {
  1512. // ToastUtil.showToast('content = ' +content)
  1513. if (action == DialogAction.TWO) {
  1514. const newName = content
  1515. const newPath = this.currentPath + '/' + newName
  1516. console.log("onecold item = " + item.type);
  1517. this.doReName(index, newName, filePath, newPath, item)
  1518. }
  1519. }
  1520. })
  1521. }
  1522. //剪切 移动到另个文件夹的对话框
  1523. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1524. Logger.info('onecold showCutDialog')
  1525. let mList: Array<string> = []
  1526. let rPath = this.rootPath
  1527. if (isCurrent) {
  1528. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1529. rPath = this.currentPath
  1530. } else {
  1531. mList = Utility.getNameList(this.dirList);
  1532. rPath = this.rootPath
  1533. }
  1534. let dataBean = new BubbleBean()
  1535. dataBean.data = mList
  1536. dataBean.color = this.themeColor
  1537. dataBean.onItemClick = (i) => {
  1538. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1539. Logger.info('newPath = ' + newPath)
  1540. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  1541. ToastUtil.showToast('移动成功')
  1542. this.table.deleteData(item, () => {
  1543. });
  1544. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1545. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1546. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1547. CommonConstants.TYPE_LOCAL, true);
  1548. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1549. this.table.insert(newItem, (id: number) => {
  1550. //加入数据库
  1551. });
  1552. }
  1553. this.cache.delete(this.currentPath); // 删除原路径缓存
  1554. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1555. this.getSortedFiles(this.currentPath, true)
  1556. }).catch((error: BusinessError) => {
  1557. console.error(error.message);
  1558. });
  1559. XPopup.dismissTop()
  1560. }
  1561. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1562. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1563. popupPosition = PopupPosition.TOP
  1564. }
  1565. if (index <= 3) {
  1566. popupPosition = PopupPosition.BOTTOM
  1567. }
  1568. let pup: XPopup
  1569. if (this.isDarkMode) {
  1570. pup = XPopup.Builder()
  1571. .setPopupPosition(popupPosition)
  1572. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  1573. .setBackgroundColor(Color.Black)
  1574. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1575. .show()
  1576. } else {
  1577. pup = XPopup.Builder()
  1578. .setPopupPosition(popupPosition)
  1579. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  1580. .setBackgroundColor(Color.White)
  1581. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1582. .show()
  1583. }
  1584. }
  1585. //复制 到另个文件夹的对话框
  1586. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1587. Logger.info('onecoldv showCopyDialog')
  1588. let mList: Array<string> = []
  1589. let rPath = this.rootPath
  1590. if (isCurrent) {
  1591. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1592. rPath = this.currentPath
  1593. } else {
  1594. mList = Utility.getNameList(this.dirList);
  1595. rPath = this.rootPath
  1596. }
  1597. let dataBean = new BubbleBean()
  1598. dataBean.data = mList
  1599. dataBean.isCopy = true
  1600. dataBean.color = this.themeColor
  1601. dataBean.onItemClick = (i) => {
  1602. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1603. Logger.info('newPath = ' + newPath)
  1604. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  1605. ToastUtil.showToast('复制成功')
  1606. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1607. this.getSortedFiles(this.currentPath)
  1608. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1609. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1610. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1611. CommonConstants.TYPE_LOCAL, true);
  1612. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1613. this.table.insert(newItem, (id: number) => {
  1614. //加入数据库
  1615. });
  1616. }
  1617. }).catch((error: BusinessError) => {
  1618. console.error(error.message);
  1619. });
  1620. XPopup.dismissTop()
  1621. }
  1622. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1623. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1624. popupPosition = PopupPosition.TOP
  1625. }
  1626. if (index <= 3) {
  1627. popupPosition = PopupPosition.BOTTOM
  1628. }
  1629. let pup: XPopup
  1630. if (this.isDarkMode) {
  1631. pup = XPopup.Builder()
  1632. .setPopupPosition(popupPosition)
  1633. .atView(id)
  1634. .setMaxHeight('60%')
  1635. .setBackgroundColor(Color.Black)
  1636. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1637. .show();
  1638. } else {
  1639. pup = XPopup.Builder()
  1640. .setPopupPosition(popupPosition)
  1641. .atView(id)
  1642. .setMaxHeight('60%')
  1643. .setBackgroundColor(Color.White)
  1644. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1645. .show();
  1646. }
  1647. }
  1648. //重命名索引index的视频
  1649. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  1650. FileUtil.rename(oldPath, newPath).then(async () => {
  1651. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1652. if (info.type === CommonConstants.TYPE_IS_DIR) {
  1653. //如果是文件夹先删除源数据,再添加新数据
  1654. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  1655. if (success) {
  1656. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  1657. } else {
  1658. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  1659. }
  1660. });
  1661. this.scanDirectory(newPath)
  1662. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  1663. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  1664. if (success) {
  1665. console.log(" onecold 重命名成功,数据库已同步");
  1666. } else {
  1667. console.error(" onecold 重命名数据库失败原因: " + error);
  1668. }
  1669. });
  1670. }
  1671. let mediaItem: VideoItem =
  1672. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, true);
  1673. this.videoLocalList[index] = mediaItem;
  1674. }
  1675. this.cache.delete(this.currentPath)
  1676. this.getSortedFiles(this.currentPath, true)
  1677. }).catch((error: BusinessError) => {
  1678. console.error(error.message);
  1679. });
  1680. }
  1681. build() {
  1682. Scroll() {
  1683. Column() {
  1684. if (!this.isShowCoverHeader()) {
  1685. Column() {
  1686. Line().width('100%').height('100%')
  1687. }
  1688. .height(this.topRectHeight)
  1689. .backgroundColor(this.isCustomizeBg ? Color.Transparent :
  1690. (this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor))
  1691. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  1692. TitleBar({ model: $titleBarModel })
  1693. .id('pup_positon_music')
  1694. }
  1695. Stack() {
  1696. Column() {
  1697. XComponent({
  1698. id: 'xcomponentId',
  1699. type: 'surface',
  1700. libraryname: 'ijkplayer_napi',
  1701. controller: this.xcomponentController
  1702. })
  1703. .onLoad((event?: object) => {
  1704. if (!!event) {
  1705. this.initDelayPlay(event);
  1706. }
  1707. })
  1708. .onKeyEvent((event?: KeyEvent) => {
  1709. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  1710. if (!event || event.type !== KeyType.Down) {
  1711. return;
  1712. }
  1713. //空格键 Space key controls pause/play
  1714. if (event.keyCode === KeyCode.KEYCODE_SPACE) {
  1715. this.playOrPause()
  1716. }
  1717. // Right-click to fast forward
  1718. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  1719. this.sessionFastForwardCallback(15);
  1720. }
  1721. // Left-click to rewind
  1722. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  1723. this.sessionRewindCallback(15);
  1724. }
  1725. })
  1726. .onDestroy(() => {
  1727. })
  1728. .width('100%')// .width(this.videoWidth)
  1729. .aspectRatio(this.videoAspectRatio)
  1730. }
  1731. .aspectRatio(this.videoAspectRatio)
  1732. .justifyContent(FlexAlign.Center)
  1733. .backgroundColor(Color.Transparent)
  1734. .visibility(Visibility.Hidden)
  1735. .height(CommonConstants.FULL_PERCENT)
  1736. .width(CommonConstants.FULL_PERCENT)
  1737. Stack() {
  1738. Row() {
  1739. Blank()
  1740. .layoutWeight(1)
  1741. IndexerView(
  1742. {
  1743. indexArray: DEFAULT_INDEX,
  1744. selectedIndex: this.selectedIndex,
  1745. textSize: 12,
  1746. selectedColor: "#ff419ee5",
  1747. normalColor: "#ffa0a0a0",
  1748. floatSelectedTextColor: "#ffffff",
  1749. floatSelectedViewColor: "#ff419ee5",
  1750. onIndexChanged: (index) => {
  1751. this.listScroller.scrollToIndex(index)
  1752. }
  1753. })
  1754. .width(24)
  1755. .height("50%")
  1756. }.visibility(Visibility.None)
  1757. Column() {
  1758. if (!this.isShowCoverHeader()) {
  1759. this.tabTitle()
  1760. }
  1761. if (this.isGridMusic) {
  1762. this.getGridView()
  1763. } else {
  1764. this.getListView()
  1765. }
  1766. if (this.modeType == 0) {
  1767. Column() {
  1768. Button('同步数据', { type: ButtonType.Capsule, stateEffect: true })
  1769. .width(130)
  1770. .height(50)
  1771. .margin({ top: 100, bottom: 40 })
  1772. .backgroundColor(this.themeColor)
  1773. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  1774. .onClick(() => {
  1775. this.asyncCurrentPathData()
  1776. })
  1777. }
  1778. .height(100)
  1779. .position({ top: 260 })
  1780. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  1781. .animation({ duration: 500 }),
  1782. TransitionEffect.scale({ x: 0, y: 0 })))
  1783. .justifyContent(FlexAlign.Center)
  1784. .opacity(this.isZero ? 1 : 0)
  1785. .visibility(this.isZero && !this.isFavMusic && !this.isHistory
  1786. && this.modeType === 0 ? Visibility.Visible : Visibility.None)
  1787. .animation({
  1788. duration: 500,
  1789. curve: 'ease-in-out' // 可选动画曲线
  1790. })
  1791. .width('100%')
  1792. }
  1793. }
  1794. .layoutWeight(1)
  1795. .height('100%')
  1796. }
  1797. .layoutWeight(1)
  1798. .height('100%')
  1799. Row() {
  1800. Button(this.isAllSelected ? '全不选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  1801. .width('35%')
  1802. .height(60)
  1803. .margin({ top: 10, bottom: 10, right: 6 })
  1804. .backgroundColor(this.themeColor)
  1805. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1806. .onClick(() => {
  1807. if (this.isAllSelected) {
  1808. // 全不选
  1809. this.selectedFiles = [];
  1810. } else {
  1811. // 全选
  1812. this.selectedFiles = [...this.getCurFileList()];
  1813. }
  1814. this.isAllSelected = !this.isAllSelected;
  1815. })
  1816. Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  1817. .width('35%')
  1818. .height(60)
  1819. .id('music_cut')
  1820. .margin({ top: 10, bottom: 10, right: 6 })
  1821. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1822. .backgroundColor(this.themeColor)
  1823. .onClick(() => {
  1824. this.showCutDialogForMultipleFiles(false, 'music_cut')
  1825. })
  1826. Button('移动', { type: ButtonType.Circle, stateEffect: true })
  1827. .width('35%')
  1828. .height(60)
  1829. .id('music_cut_current')
  1830. .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  1831. .margin({ top: 10, bottom: 10, right: 6 })
  1832. .backgroundColor(this.themeColor)
  1833. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1834. .onClick(() => {
  1835. this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  1836. })
  1837. Button('复制', { type: ButtonType.Circle, stateEffect: true })
  1838. .width('35%')
  1839. .height(60)
  1840. .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  1841. .margin({ top: 10, bottom: 10, right: 6 })
  1842. .backgroundColor(this.themeColor)
  1843. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1844. .onClick(() => {
  1845. this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  1846. })
  1847. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  1848. .width('35%')
  1849. .height(60)
  1850. .margin({ top: 10, bottom: 10, right: 6 })
  1851. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  1852. .backgroundColor(this.themeColor)
  1853. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1854. .onClick(() => {
  1855. this.showWarnIsDelete()
  1856. })
  1857. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  1858. .width('35%')
  1859. .height(60)
  1860. .margin({ top: 10, bottom: 10, right: 6 })
  1861. .backgroundColor(this.themeColor)
  1862. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1863. .onClick(() => {
  1864. this.selectedFiles = [];
  1865. this.isAllSelected = false
  1866. this.isMultiSelect = false
  1867. })
  1868. }
  1869. .width('100%')
  1870. .justifyContent(FlexAlign.Center)
  1871. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  1872. .opacity(this.isMultiSelect ? 1 : 0)
  1873. .animation({
  1874. duration: 666,
  1875. curve: 'ease-in-out' // 可选动画曲线
  1876. })
  1877. .position(this.isShowCoverHeader() ? { bottom: 78 }
  1878. : { bottom: this.isPhoneLan() ? 130 : 168 }) // 将 Row 固定在底部
  1879. }
  1880. .width('100%')
  1881. .height('100%')
  1882. .alignContent(Alignment.Top)
  1883. Column() {
  1884. this.PlayController()
  1885. }
  1886. .hitTestBehavior(HitTestMode.Transparent)
  1887. .position({ bottom: 0 }) // 将 Row 固定在底部
  1888. .opacity(this.barBottomOpacity)
  1889. }
  1890. .width('100%')
  1891. .height('100%')
  1892. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  1893. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  1894. .backgroundImagePosition(Alignment.Center)
  1895. .backdropBlur(this.blurValue)
  1896. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  1897. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  1898. }
  1899. }
  1900. asyncCurrentPathData() {
  1901. if (this.modeType == 0) {
  1902. workerInstance.postMessage({
  1903. code: 1,
  1904. data1: this.context,
  1905. data2: this.currentPath,
  1906. data3: this.lockPath,
  1907. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  1908. });
  1909. }
  1910. }
  1911. // 处理文件选择的函数
  1912. handleFileSelection(item: VideoItem, checked: boolean) {
  1913. if (checked) {
  1914. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  1915. this.selectedFiles.push(item);
  1916. }
  1917. } else {
  1918. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  1919. if (index > -1) {
  1920. this.selectedFiles.splice(index, 1);
  1921. }
  1922. }
  1923. }
  1924. showWarnIsDelete() {
  1925. //操作确认类弹出框
  1926. DialogHelper.showAlertDialog({
  1927. content: "确定要删除这些文件吗?",
  1928. transition: AnimationHelper.transitionInUp(666),
  1929. maskColor: Color.Transparent,
  1930. backgroundColor: Color.Grey,
  1931. onAction: (action) => {
  1932. if (action == DialogAction.ONE) {
  1933. // ToastUtil.showToast(`您点击了取消按钮`);
  1934. } else if (action == DialogAction.TWO) {
  1935. // ToastUtil.showToast(`您点击了确认按钮`);
  1936. this.deleteMultipleFiles()
  1937. }
  1938. }
  1939. })
  1940. }
  1941. //多选删除文件
  1942. deleteMultipleFiles() {
  1943. if (ArrayUtil.isNotEmpty(this.selectedFiles)) {
  1944. this.selectedFiles.forEach((item) => {
  1945. Logger.info(TAG, 'delete filePath = ' + item.filePath);
  1946. if (item.type === CommonConstants.TYPE_IS_DIR) {
  1947. this.table.deleteDataForParentPath(item.filePath, () => {
  1948. FileUtil.rmdir(item.filePath).then(() => {
  1949. this.videoLocalList = this.videoLocalList.filter(v => v !== item);
  1950. this.selectedFiles = [];
  1951. this.isMultiSelect = false
  1952. this.isAllSelected = false
  1953. this.cache.delete(this.currentPath);
  1954. this.getSortedFiles(this.currentPath, true);
  1955. }).catch((error: Error) => {
  1956. console.error(error.message);
  1957. });
  1958. });
  1959. } else {
  1960. this.table.deleteData(item, () => {
  1961. FileUtil.unlink(item.filePath).catch((error: Error) => {
  1962. console.error(error.message);
  1963. }).finally(() => {
  1964. this.videoLocalList = this.videoLocalList.filter(v => v !== item);
  1965. this.selectedFiles = [];
  1966. this.isMultiSelect = false
  1967. this.isAllSelected = false
  1968. this.cache.delete(this.currentPath);
  1969. this.getSortedFiles(this.currentPath, true);
  1970. });
  1971. });
  1972. }
  1973. });
  1974. }
  1975. }
  1976. //多选移动文件
  1977. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  1978. Logger.info('onecold showCutDialogForMultipleFiles')
  1979. let mList: Array<string> = []
  1980. let rPath = this.rootPath
  1981. if (isCurrent) {
  1982. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1983. rPath = this.currentPath
  1984. } else {
  1985. mList = Utility.getNameList(this.dirList);
  1986. rPath = this.rootPath
  1987. }
  1988. let dataBean = new BubbleBean();
  1989. dataBean.data = mList;
  1990. dataBean.color = this.themeColor
  1991. dataBean.onItemClick = (i) => {
  1992. const newDirPath = rPath + '/' + mList[i];
  1993. // Logger.info('newDirPath = ' + newDirPath)
  1994. this.selectedFiles.forEach((item) => {
  1995. const newPath = newDirPath + '/' + item.fileName;
  1996. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  1997. ToastUtil.showToast('移动成功');
  1998. this.table.deleteData(item, () => {
  1999. this.cache.delete(this.currentPath); // 删除原路径缓存
  2000. this.cache.delete(newDirPath); // 删除目标路径缓存
  2001. this.getSortedFiles(this.currentPath, true);
  2002. });
  2003. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2004. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2005. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2006. CommonConstants.TYPE_LOCAL, true);
  2007. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2008. this.table.insert(newItem, (id: number) => {
  2009. //加入数据库
  2010. });
  2011. }
  2012. }).catch((error: Error) => {
  2013. console.error(error.message);
  2014. });
  2015. });
  2016. this.isMultiSelect = false
  2017. this.selectedFiles = [];
  2018. this.isAllSelected = false
  2019. XPopup.dismissTop();
  2020. };
  2021. let pup: XPopup
  2022. if (this.isDarkMode) {
  2023. pup = XPopup.Builder()
  2024. .setPopupPosition(PopupPosition.TOP)
  2025. .atView(viewId)
  2026. .setBackgroundColor(Color.Black)
  2027. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2028. .show();
  2029. } else {
  2030. pup = XPopup.Builder()
  2031. .setPopupPosition(PopupPosition.TOP)
  2032. .atView(viewId)
  2033. .setBackgroundColor(Color.White)
  2034. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2035. .show();
  2036. }
  2037. }
  2038. doFav(item: VideoItem) {
  2039. LogUtil.info('onecold doFav isFav=' + item.isFav)
  2040. let isFav = 0
  2041. if (Utility.getIsFav(this.favList, item)) {
  2042. isFav = 0
  2043. } else {
  2044. isFav = 1
  2045. }
  2046. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  2047. if (result) {
  2048. if (isFav === 1) {
  2049. ToastUtil.showToast('收藏成功');
  2050. } else {
  2051. ToastUtil.showToast('取消收藏成功');
  2052. }
  2053. this.deleteCache(this.currentPath)
  2054. this.getFavList(false)
  2055. if (this.modeType === 0 && !this.isFavMusic) {
  2056. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  2057. this.getSortedFiles(this.currentPath)
  2058. }
  2059. workerInstance.postMessage({ code: 2, data: this.context });
  2060. workerInstance.postMessage({ code: 3, data: this.context });
  2061. workerInstance.postMessage({ code: 4, data: this.context });
  2062. }
  2063. })
  2064. }
  2065. //多选复制文件
  2066. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  2067. console.log('onecold showCopyDialogForMultipleFiles');
  2068. let mList: Array<string> = []
  2069. let rPath = this.rootPath
  2070. if (isCurrent) {
  2071. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2072. rPath = this.currentPath
  2073. } else {
  2074. mList = Utility.getNameList(this.dirList);
  2075. rPath = this.rootPath
  2076. }
  2077. let dataBean = new BubbleBean();
  2078. dataBean.data = mList;
  2079. dataBean.isCopy = true
  2080. dataBean.color = this.themeColor
  2081. dataBean.onItemClick = (i) => {
  2082. const newDirPath = rPath + '/' + mList[i];
  2083. // Logger.info('newDirPath = ' + newDirPath)
  2084. this.selectedFiles.forEach((item) => {
  2085. const newPath = newDirPath + '/' + item.fileName;
  2086. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2087. ToastUtil.showToast('复制成功');
  2088. this.cache.delete(newDirPath); // 删除目标路径缓存
  2089. this.getSortedFiles(this.currentPath);
  2090. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2091. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2092. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2093. CommonConstants.TYPE_LOCAL, true);
  2094. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2095. this.table.insert(newItem, (id: number) => {
  2096. //加入数据库
  2097. });
  2098. }
  2099. }).catch((error: Error) => {
  2100. console.error(error.message);
  2101. });
  2102. });
  2103. this.isMultiSelect = false
  2104. this.selectedFiles = [];
  2105. this.isAllSelected = false
  2106. XPopup.dismissTop();
  2107. };
  2108. let pup: XPopup
  2109. if (this.isDarkMode) {
  2110. pup = XPopup.Builder()
  2111. .setPopupPosition(PopupPosition.TOP)
  2112. .atView(viewId)
  2113. .setBackgroundColor(Color.Black)
  2114. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2115. .show();
  2116. } else {
  2117. pup = XPopup.Builder()
  2118. .setPopupPosition(PopupPosition.TOP)
  2119. .atView(viewId)
  2120. .setBackgroundColor(Color.White)
  2121. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2122. .show();
  2123. }
  2124. }
  2125. @Builder
  2126. private DirItem(item: VideoItem, index?: number) {
  2127. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2128. Row() {
  2129. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  2130. $r('app.media.music_group'))
  2131. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2132. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2133. .fillColor(this.themeColor)// .fontSize(33)
  2134. .alt($r('app.media.music_group'))
  2135. .borderRadius('100%')
  2136. .clip(true)
  2137. .margin({ left: 20, top: 8, bottom: 8 })
  2138. Column() {
  2139. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  2140. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2141. .maxLines(1)// .width('88%')
  2142. .animation({
  2143. duration: 555,
  2144. curve: 'ease-in-out',
  2145. })
  2146. .transition({
  2147. type: TransitionType.Insert,
  2148. opacity: 0,
  2149. translate: { x: 160 }
  2150. })
  2151. .margin({ left: 10, right: 20 })
  2152. .fontColor($r('app.color.text_color'))
  2153. Row() {
  2154. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  2155. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2156. .padding({ top: 8 })
  2157. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  2158. .fontColor($r('app.color.text_color'))
  2159. .margin({ left: 10 })
  2160. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  2161. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2162. .padding({ top: 8 })
  2163. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2164. .fontColor($r('app.color.text_color'))
  2165. .margin({ left: 10 })
  2166. Blank()
  2167. }
  2168. }
  2169. .height('100%')
  2170. .layoutWeight(1)
  2171. .justifyContent(FlexAlign.Center)
  2172. .alignItems(HorizontalAlign.Start)
  2173. Blank()
  2174. Image($r('app.media.arrow_right'))
  2175. .height(25)
  2176. .margin({ right: 10 })
  2177. .alignSelf(ItemAlign.Center)
  2178. .id(item.filePath)
  2179. }
  2180. }
  2181. .backgroundColor(Color.Transparent)
  2182. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2183. .width('100%')
  2184. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  2185. .opacity(this.opacityItem) // 绑定透明度
  2186. }
  2187. isShowDir(dirName: string) {
  2188. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  2189. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  2190. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  2191. if (dirName === undefined) {
  2192. return true
  2193. }
  2194. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  2195. return this.isShowSimi
  2196. }
  2197. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  2198. return this.isShowFAV
  2199. }
  2200. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  2201. return this.isShowHistory
  2202. }
  2203. return true
  2204. }
  2205. @State opacityItem: number = 1; // 控制透明度的状态变量
  2206. @Builder
  2207. private MusicItem(item: VideoItem, index?: number) {
  2208. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2209. Row() {
  2210. Stack() {
  2211. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  2212. .fillColor(this.themeColor)
  2213. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2214. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  2215. .alt($r('app.media.music_red'))
  2216. .borderRadius('100%')
  2217. .clip(true)
  2218. .draggable(false)
  2219. .interpolation(ImageInterpolation.Medium)// 用于重采样后的抗锯齿
  2220. .autoResize(true) // 重采样,可减少内存占用
  2221. .opacity(this.opacityItem)// 绑定透明度
  2222. .margin({ left: 20 })
  2223. .gesture(LongPressGesture()
  2224. .onAction(async () => {
  2225. //如果是专辑和艺术家的首页,不能长按
  2226. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2227. return
  2228. //如果是我的收藏 最近播放等也不能长按
  2229. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2230. item.name === LocalMusic.STR_HISTORY_MUSIC
  2231. )
  2232. return
  2233. this.longItemFilePath = item.filePath
  2234. this.tempLyricContent = await this.getLyricContent(item)
  2235. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2236. })
  2237. .onActionEnd((event: GestureEvent) => {
  2238. }))
  2239. }
  2240. Column() {
  2241. Column() {
  2242. Text(item.name)
  2243. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2244. .maxLines(1)
  2245. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  2246. .animation({
  2247. duration: 555,
  2248. curve: 'Linear',
  2249. })
  2250. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2251. $r('app.color.text_color'))
  2252. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2253. .bindPopup(this.longItemFilePath === item.filePath, {
  2254. builder: this.MenuBuilder(item,index,item.filePath),
  2255. placement: Placement.Top,
  2256. // autoCancel: true,
  2257. mask: {color:'#33000000'},
  2258. // popupColor: Color.Yellow,
  2259. enableArrow: false,//是否显示箭头
  2260. showInSubWindow: false,
  2261. onStateChange: (e) => {
  2262. if (!e.isVisible) {
  2263. this.longItemFilePath = ''
  2264. this.tempLyricContent = ''
  2265. }
  2266. }
  2267. })
  2268. .gesture(LongPressGesture()
  2269. .onAction(async () => {
  2270. //如果是专辑和艺术家的首页,不能长按
  2271. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2272. return
  2273. //如果是我的收藏 最近播放等也不能长按
  2274. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2275. item.name === LocalMusic.STR_HISTORY_MUSIC
  2276. )
  2277. return
  2278. this.longItemFilePath = item.filePath
  2279. this.tempLyricContent = await this.getLyricContent(item)
  2280. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2281. })
  2282. .onActionEnd((event: GestureEvent) => {
  2283. })
  2284. )
  2285. Row() {
  2286. Column(){
  2287. Text(item.md5Str?.includes('Lossless')?
  2288. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  2289. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  2290. .padding({ top: 3,right:6,left:6,bottom:3 })
  2291. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2292. $r('app.color.text_color'))
  2293. .fontWeight(500)
  2294. .borderRadius(12)
  2295. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  2296. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2297. .backgroundColor('#FFC107')
  2298. }
  2299. .padding({ top: 8 })
  2300. Text(StrUtil.isEmpty(item.artist) ? item.cTime : item.artist + ' ' + item?.album)
  2301. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2302. .padding({ top: 8 })
  2303. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2304. $r('app.color.text_color'))
  2305. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2306. Blank()
  2307. Text(item.size)
  2308. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2309. .padding({ top: 8 })
  2310. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  2311. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2312. $r('app.color.text_color'))
  2313. .margin({ left: 10 })
  2314. }
  2315. .gesture(LongPressGesture()
  2316. .onAction(async () => {
  2317. //如果是专辑和艺术家的首页,不能长按
  2318. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2319. return
  2320. //如果是我的收藏 最近播放等也不能长按
  2321. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2322. item.name === LocalMusic.STR_HISTORY_MUSIC
  2323. )
  2324. return
  2325. this.longItemFilePath = item.filePath
  2326. this.tempLyricContent = await this.getLyricContent(item)
  2327. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2328. })
  2329. .onActionEnd((event: GestureEvent) => {
  2330. })
  2331. )
  2332. }
  2333. .height('100%')
  2334. .width('100%')
  2335. .justifyContent(FlexAlign.Center)
  2336. .alignItems(HorizontalAlign.Start)
  2337. }
  2338. .height('100%')
  2339. .margin({ left: 5 })
  2340. .layoutWeight(1)
  2341. Column() {
  2342. Checkbox({ name: 'checkbox' + index })
  2343. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  2344. .selectedColor(this.themeColor)
  2345. .shape(CheckBoxShape.CIRCLE)
  2346. .opacity(this.isMultiSelect ? 1 : 0)
  2347. .animation({
  2348. duration: 666,
  2349. curve: 'Smooth' // 可选动画曲线
  2350. })
  2351. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2352. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  2353. .margin({ left: 20, top: 8, bottom: 8 })
  2354. .width(22)
  2355. .height(22)
  2356. ImageAnimator()
  2357. .images(this.imagesF)// 动画数组
  2358. .duration(1000)// 持续
  2359. .state(this.animationState)// 动画状态
  2360. .fillMode(FillMode.Forwards)
  2361. .width(18)
  2362. .margin({ right: 20, top: 8, bottom: 8 })
  2363. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  2364. Visibility.None)
  2365. .height(18)
  2366. .iterations(-1) // 播放次数
  2367. }
  2368. }
  2369. }
  2370. .backgroundColor(Color.Transparent)
  2371. .width('100%')
  2372. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2373. }
  2374. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  2375. @Builder
  2376. tabTitle() {
  2377. Column() {
  2378. // 使用 Stack 布局来实现绝对定位效果
  2379. Stack() {
  2380. // 背景动画容器
  2381. Row() {
  2382. ForEach(this.tabs, (i: string, index) => {
  2383. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2384. Flex()
  2385. .backgroundColor(this.isDarkMode ? $r('app.color.tab_item_bg') : this.themeColor)
  2386. .borderRadius(20)
  2387. .padding(10)
  2388. .margin(6)
  2389. .width('100%')
  2390. .height('100%')
  2391. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2392. .visibility(this.modeType === index ? Visibility.Visible : Visibility.None)
  2393. .opacity(this.modeType === index ? 1 : 0)
  2394. .animation({
  2395. duration: 666,
  2396. playMode: PlayMode.Normal,
  2397. curve: 'ease-in-out'
  2398. });
  2399. }
  2400. .layoutWeight(1)
  2401. .margin({
  2402. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5,
  2403. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5, bottom: 1
  2404. });
  2405. });
  2406. }
  2407. .width('100%')
  2408. .height(50);
  2409. // 导航栏容器
  2410. Row() {
  2411. ForEach(this.tabs, (item: string, index) => {
  2412. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2413. Text(item)
  2414. .fontSize(16)
  2415. .fontColor(this.modeType === index ? Color.White : $r('app.color.text_color'))
  2416. .padding(15)
  2417. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2418. .onClick(() => {
  2419. this.modeType = index;
  2420. this.onModeChange();
  2421. });
  2422. }
  2423. .layoutWeight(1)
  2424. .stateStyles({
  2425. pressed: { opacity: 0.6 } // 按压反馈
  2426. });
  2427. });
  2428. }
  2429. .width('100%')
  2430. .height(this.topBarHeight)
  2431. .opacity(this.barOpacity)
  2432. .backgroundColor(Color.Transparent);
  2433. }
  2434. .width('100%')
  2435. .height(this.topBarHeight)
  2436. .opacity(this.barOpacity)
  2437. Line()
  2438. .width('100%')
  2439. .height(1)
  2440. .backgroundColor($r('app.color.index_background'))
  2441. .opacity(this.barOpacity)
  2442. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  2443. }
  2444. .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  2445. }
  2446. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  2447. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  2448. isShowCoverHeader() {
  2449. if (!this.isShowHeader) {
  2450. return false
  2451. }
  2452. if (this.modeType == 0) {
  2453. if (this.isHistory || this.isFavMusic) {
  2454. return true
  2455. }
  2456. if (this.currentPath != this.rootPath) {
  2457. return true
  2458. }
  2459. }
  2460. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  2461. }
  2462. @Builder
  2463. coverHeader() {
  2464. if (this.isShowCoverHeader()) {
  2465. Column() {
  2466. Stack() {
  2467. // 居中标题
  2468. Text('')
  2469. .fontSize(18)
  2470. .fontColor(Color.White)
  2471. .align(Alignment.Center)
  2472. // 左右按钮
  2473. Row() {
  2474. Image($r('app.media.left_back_white'))
  2475. .width(28)
  2476. .height(28)
  2477. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2478. .margin({ left: 12, right: 8 })
  2479. .onClick(() => {
  2480. animateTo({ duration: 555 }, () => {
  2481. this.doSwipBack()
  2482. })
  2483. })
  2484. Blank().flexGrow(1)
  2485. if (this.modeType == 0 && !this.isHistory && !this.isFavMusic) {
  2486. Image($r('app.media.add'))
  2487. .width(25)
  2488. .height(25)
  2489. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2490. .margin({ left: 8, right: 15 })
  2491. .onClick(() => {
  2492. this.showAddDialog()
  2493. })
  2494. }
  2495. }
  2496. .height(48)
  2497. .width('100%')
  2498. .alignItems(VerticalAlign.Center)
  2499. }
  2500. .height(48)
  2501. .width('100%')
  2502. Row() {
  2503. Column() {
  2504. Image(this.currentTitleCover)
  2505. .height(100)
  2506. .width(100)
  2507. .alt(this.imageLabel)
  2508. .borderRadius(8)
  2509. .clickEffect({ level: ClickEffectLevel.HEAVY })
  2510. }
  2511. .alignItems(HorizontalAlign.Start)
  2512. .margin({ left: 30, top: 3, bottom: 15 })
  2513. Column() {
  2514. Column() {
  2515. Text(this.currentTitleName)
  2516. .fontSize(16)
  2517. .maxLines(1)
  2518. .fontWeight(FontWeight.Bold)
  2519. .fontColor($r('app.color.text_color'))
  2520. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2521. if (this.modeType == 3 && ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2522. Text(`艺术家:${this.videoLocalList[0].artist}`)
  2523. .fontSize(14)
  2524. .padding({ top: 8 })
  2525. .maxLines(1)
  2526. .fontWeight(FontWeight.Bold)
  2527. .fontColor($r('app.color.text_color'))
  2528. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2529. if(this.videoLocalList[0].genre){
  2530. Text(`风格:${this.videoLocalList[0].genre}`)
  2531. .fontSize(14)
  2532. .padding({ top: 8 })
  2533. .maxLines(1)
  2534. .visibility(StrUtil.isEmpty(this.videoLocalList[0].genre)||
  2535. this.videoLocalList[0].genre.includes(this.UNKONWN)
  2536. ?Visibility.None:Visibility.Visible)
  2537. .fontWeight(FontWeight.Bold)
  2538. .fontColor($r('app.color.text_color'))
  2539. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2540. }
  2541. if(this.videoLocalList[0].year){
  2542. Text(`发行时间:${this.videoLocalList[0].year}`)
  2543. .fontSize(14)
  2544. .padding({ top: 8 })
  2545. .maxLines(1)
  2546. .visibility(StrUtil.isEmpty(this.videoLocalList[0].year)||
  2547. this.videoLocalList[0].year.includes(this.UNKONWN)
  2548. ?Visibility.None:Visibility.Visible)
  2549. .fontWeight(FontWeight.Bold)
  2550. .fontColor($r('app.color.text_color'))
  2551. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2552. }
  2553. }
  2554. if(this.modeType != 3){
  2555. Row() {
  2556. Text(`共${this.videoLocalList.length}首歌`)
  2557. .fontSize(13)
  2558. .fontWeight(FontWeight.Bold)
  2559. .padding({ top: 8 })
  2560. .fontColor($r('app.color.text_color'))
  2561. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  2562. Blank()
  2563. }
  2564. }
  2565. }
  2566. .height('100%')
  2567. .width('100%')
  2568. .justifyContent(FlexAlign.Center)
  2569. .alignItems(HorizontalAlign.Start)
  2570. }
  2571. .height('100%')
  2572. .layoutWeight(1)
  2573. .margin({ left: 20 })
  2574. }
  2575. this.listViewTitle()
  2576. }
  2577. .backgroundImage(this.getCoverTitleBg())
  2578. .height(250)
  2579. .width('100%')
  2580. .backgroundImageSize({ height: '100%', width: '100%' })
  2581. .backgroundBlurStyle(this.isCustomizeBg ? BlurStyle.NONE : BlurStyle.BACKGROUND_ULTRA_THICK)
  2582. .padding({ top: this.topRectHeight, bottom: this.bottomBarHeight + 48 })
  2583. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  2584. .justifyContent(FlexAlign.SpaceBetween)
  2585. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.7, y: 0.7 }).animation({ duration: 500 }),
  2586. TransitionEffect.scale({ x: 0, y: 0 })))
  2587. } else {
  2588. this.listViewTitle()
  2589. }
  2590. }
  2591. getCoverTitleBg(): ResourceStr | image.PixelMap {
  2592. if (this.isCustomizeBg) {
  2593. return ('rgba(255,255,255,0.2)')
  2594. }
  2595. if (this.isDarkMode) {
  2596. return $r('app.color.user_center_card_background')
  2597. }
  2598. return this.currentTitleCover
  2599. }
  2600. @Builder
  2601. listViewTitle() {
  2602. Column() {
  2603. Row({ space: 8 }) {
  2604. Row({ space: 8 }) {
  2605. Image($r("app.media.hm_playlist"))
  2606. .width(25)
  2607. .margin({ left: 8 })
  2608. .fillColor(this.themeColor)
  2609. Text(`共找到${this.artistList.length}位艺术家`)
  2610. .fontColor($r('app.color.text_color'))
  2611. .fontSize(14)
  2612. .opacity(this.opacityItem)
  2613. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  2614. Text(`共找到${this.albumList.length}张专辑`)
  2615. .fontColor($r('app.color.text_color'))
  2616. .opacity(this.opacityItem)
  2617. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2618. .fontSize(14)
  2619. }
  2620. .layoutWeight(1)
  2621. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  2622. Row() {
  2623. TextInput({
  2624. placeholder: this.modeType === 2 ? '输入艺术家名称...' : '输入专辑名称...',
  2625. text: this.searchText
  2626. })
  2627. .height(35)
  2628. .onChange((value: string) => {
  2629. this.onSearchInput(value);
  2630. })
  2631. .layoutWeight(1)
  2632. Text(`取消`)
  2633. .margin({ left: 10, right: 10 })
  2634. .fontColor($r('app.color.text_color'))
  2635. .fontSize(16)
  2636. .onClick(() => {
  2637. this.isSearchMode = false
  2638. this.searchText = ''
  2639. if (this.modeType === 2) {
  2640. this.updateListData(this.artistList)
  2641. } else {
  2642. this.updateListData(this.albumList)
  2643. }
  2644. })
  2645. }
  2646. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  2647. .animation({
  2648. duration: 666,
  2649. curve: 'ease-in-out' // 可选动画曲线
  2650. })
  2651. Blank()
  2652. Image($r("app.media.search"))
  2653. .width(25)
  2654. .visibility(this.modeType === 2 || this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2655. .animation({
  2656. duration: 666,
  2657. curve: 'ease-in-out' // 可选动画曲线
  2658. })// .opacity(this.opacityItem)
  2659. .fillColor(this.themeColor)
  2660. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2661. .onClick(() => {
  2662. this.isSearchMode = true
  2663. })
  2664. Image($r("app.media.top_rank"))
  2665. .width(25)// .opacity(this.opacityItem)
  2666. .fillColor(this.themeColor)
  2667. .animation({
  2668. duration: 666,
  2669. curve: 'ease-in-out' // 可选动画曲线
  2670. })
  2671. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2672. .onClick(() => {
  2673. this.showRankDialog()
  2674. })
  2675. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  2676. .width(25)
  2677. .animation({
  2678. duration: 666,
  2679. curve: 'ease-in-out' // 可选动画曲线
  2680. })
  2681. .fillColor(this.themeColor)
  2682. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2683. .onClick(() => {
  2684. this.isGridMusic = !this.isGridMusic
  2685. })
  2686. }
  2687. .visibility(((this.modeType === 2 || this.modeType === 3) && !this.isCanBack) ? Visibility.Visible :
  2688. Visibility.None)
  2689. .width('100%')
  2690. .padding(10)
  2691. .height(50)
  2692. .border({
  2693. width: { bottom: 1 },
  2694. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  2695. })
  2696. Row({ space: 8 }) {
  2697. Row({ space: 8 }) {
  2698. Image($r("app.media.hm_play"))
  2699. .width(25)
  2700. .margin({ left: 8 })
  2701. .fillColor(this.themeColor)
  2702. Text(`播放全部`)
  2703. .fontColor($r('app.color.text_color'))
  2704. .fontSize(14)
  2705. .animation({
  2706. duration: 666,
  2707. curve: 'ease-in-out' // 可选动画曲线
  2708. })
  2709. Text(`(${Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length}首)`)
  2710. .fontColor($r('app.color.text_color'))
  2711. .fontSize(14)
  2712. .opacity(this.opacityItem)
  2713. .animation({
  2714. duration: 666,
  2715. curve: 'ease-in-out' // 可选动画曲线
  2716. })
  2717. }
  2718. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2719. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  2720. .animation({
  2721. duration: 666,
  2722. curve: 'ease-in-out' // 可选动画曲线
  2723. })
  2724. // .backgroundColor(this.isClickedPLayAll ? $r('app.color.button_click') : Color.Transparent)
  2725. .onTouch((event: TouchEvent) => {
  2726. if (event.type === TouchType.Down) {
  2727. this.isClickedPLayAll = true;
  2728. } else if (event.type === TouchType.Up || event.type === TouchType.Cancel) {
  2729. this.isClickedPLayAll = false;
  2730. }
  2731. })
  2732. .onClick(() => {
  2733. // ToastUtil.showToast('当前的手机的折叠状态 ='+DisplayUtil.getFoldStatus())
  2734. if (this.modeType === 0) {
  2735. if (ArrayUtil.isNotEmpty(this.getCurFileList())) {
  2736. this.doPlay(this.getCurFileList()[0])
  2737. }
  2738. } else {
  2739. if (ArrayUtil.isNotEmpty(this.mediaKuList)) {
  2740. this.doPlay(this.mediaKuList[0])
  2741. }
  2742. }
  2743. })
  2744. Row() {
  2745. TextInput({ placeholder: '输入名称...', text: this.searchText })
  2746. .height(35)
  2747. .onChange((value: string) => {
  2748. this.onSearchInput(value);
  2749. })
  2750. .layoutWeight(1)
  2751. Text(`取消`)
  2752. .margin({ left: 10, right: 10 })
  2753. .fontColor($r('app.color.text_color'))
  2754. .fontSize(16)
  2755. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2756. .onClick(() => {
  2757. this.isSearchMode = false
  2758. this.searchText = ''
  2759. this.updateListData(this.mediaKuList)
  2760. })
  2761. }
  2762. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  2763. .animation({
  2764. duration: 666,
  2765. curve: 'ease-in-out' // 可选动画曲线
  2766. })
  2767. Blank()
  2768. Image($r("app.media.search"))
  2769. .width(25)// .visibility(this.modeType===1?Visibility.Visible:Visibility.None)
  2770. .animation({
  2771. duration: 666,
  2772. curve: 'ease-in-out' // 可选动画曲线
  2773. })// .opacity(this.opacityItem)
  2774. .fillColor(this.themeColor)
  2775. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2776. .onClick(() => {
  2777. this.isSearchMode = true
  2778. })
  2779. Image($r("app.media.refresh"))
  2780. .fillColor(this.themeColor)
  2781. .width(25)
  2782. .visibility(this.isHistory || this.isCanBack || this.isSearchMode ? Visibility.None : Visibility.Visible)
  2783. .animation({
  2784. duration: 666,
  2785. curve: 'ease-in-out' // 可选动画曲线
  2786. })
  2787. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2788. .onClick(() => {
  2789. if (this.isFavMusic) {
  2790. this.getFavList(true)
  2791. } else {
  2792. if(this.modeType == 0){
  2793. this.asyncCurrentPathData()
  2794. }else if(this.modeType ==1){
  2795. workerInstance.postMessage({ code: 2, data: this.context });
  2796. }
  2797. }
  2798. })
  2799. Image($r("app.media.top_rank"))
  2800. .width(25)
  2801. .visibility(this.isHistory || this.isSearchMode ? Visibility.None :
  2802. Visibility.Visible)// .opacity(this.opacityItem)
  2803. .animation({
  2804. duration: 666,
  2805. curve: 'ease-in-out' // 可选动画曲线
  2806. })
  2807. .fillColor(this.themeColor)
  2808. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2809. .onClick(() => {
  2810. this.showRankDialog()
  2811. })
  2812. Image(this.isMultiSelect ? $r("app.media.cancel_multi") : $r("app.media.top_flower"))
  2813. .width(24)
  2814. .visibility(this.isHistory || this.isSearchMode ? Visibility.None : Visibility.Visible)
  2815. .animation({
  2816. duration: 666,
  2817. curve: 'ease-in-out' // 可选动画曲线
  2818. })
  2819. .fillColor(this.themeColor)
  2820. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2821. .onClick(() => {
  2822. this.isMultiSelect = !this.isMultiSelect
  2823. })
  2824. SymbolGlyph($r('sys.symbol.trash'))
  2825. .fontColor([this.themeColor])
  2826. .fontSize(25)
  2827. .effectStrategy(1)
  2828. .visibility(this.isHistory ? Visibility.Visible : Visibility.None)
  2829. .animation({
  2830. duration: 666,
  2831. curve: 'ease-in-out' // 可选动画曲线
  2832. })
  2833. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2834. .onClick(() => {
  2835. this.clearVideoHistory() //清空播放记录
  2836. })
  2837. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  2838. .width(24)
  2839. .animation({
  2840. duration: 666,
  2841. curve: 'ease-in-out' // 可选动画曲线
  2842. })
  2843. .fillColor(this.themeColor)
  2844. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2845. .bindPopup($$this.tipPopup, {
  2846. builder: this.popupBuilder,
  2847. placement: Placement.Bottom,
  2848. maskColor: 0x33000000,
  2849. enableArrow: true,
  2850. onStateChange: (e) => {
  2851. if (!e.isVisible) {
  2852. this.tipPopup = false;
  2853. }
  2854. }
  2855. })
  2856. .onClick(() => {
  2857. this.isGridMusic = !this.isGridMusic
  2858. })
  2859. }
  2860. .width('100%')
  2861. .padding(10)
  2862. .height(50)
  2863. .visibility(this.modeType === 0 || this.modeType === 1 || this.isCanBack ? Visibility.Visible : Visibility.None)
  2864. .border({
  2865. width: { bottom: 1 },
  2866. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  2867. })
  2868. }
  2869. .visibility(this.isShowAllBar ? Visibility.Visible : Visibility.None)
  2870. }
  2871. // 第二步:popup构造器定义弹框内容
  2872. @Builder popupBuilder() {
  2873. Column({ space: 2 }) {
  2874. Text('友情提示:双指缩放可以放大缩小列表')
  2875. .fontSize(12)
  2876. .fontWeight(FontWeight.Regular)
  2877. .fontColor($r('app.color.text_color'))
  2878. }
  2879. .justifyContent(FlexAlign.SpaceAround)
  2880. .width(220)
  2881. .height(55)
  2882. .padding(15)
  2883. }
  2884. //搜索功能的实现
  2885. @State searchText: string = ''; // 用户输入内容
  2886. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  2887. @State isSearchMode: boolean = false
  2888. // 实时搜索逻辑(带防抖)
  2889. private onSearchInput(value: string) {
  2890. this.searchText = value.trim();
  2891. let mSearchList: Array<VideoItem> = []
  2892. switch (this.modeType) {
  2893. case 0:
  2894. mSearchList = this.videoLocalList
  2895. break;
  2896. case 1:
  2897. mSearchList = this.mediaKuList
  2898. break;
  2899. case 2:
  2900. mSearchList = this.artistList
  2901. break;
  2902. case 3:
  2903. mSearchList = this.albumList
  2904. break;
  2905. }
  2906. // 新增条件判断:空输入时显示所有数据
  2907. if (this.searchText === '') {
  2908. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  2909. } else {
  2910. this.filteredList = mSearchList.filter((item: VideoItem) => {
  2911. return item.name.toLowerCase().includes(this.searchText.toLowerCase());
  2912. });
  2913. }
  2914. this.updateListData(this.filteredList);
  2915. // this.isSearchMode = false; // 根据业务需求决定是否启用
  2916. }
  2917. @State dragItem: number = -1
  2918. @State scaleItem: number = -1
  2919. @State neighborItem: number = -1
  2920. @State neighborScale: number = -1
  2921. @State offsetY: number = 0
  2922. private dragRefOffset: number = 0
  2923. private ITEM_INTV: number = 78
  2924. scaleSelect(item: number): number {
  2925. if (this.scaleItem === item) {
  2926. return 1.05
  2927. } else if (this.neighborItem === item) {
  2928. return this.neighborScale
  2929. } else {
  2930. return 1
  2931. }
  2932. }
  2933. itemMove(index: number, newIndex: number): void {
  2934. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  2935. return;
  2936. }
  2937. let tmp = this.videoLocalList.splice(index, 1);
  2938. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  2939. this.dataSource.pushArrayData(this.videoLocalList)
  2940. }
  2941. // Grid布局的开始
  2942. private dragRefOffSetX: number = 0;
  2943. private dragRefOffSetY: number = 0;
  2944. private FIX_VP_X: number = 180;
  2945. private FIX_VP_Y: number = 84;
  2946. isDraggable(index: number): boolean {
  2947. return index >= 0;
  2948. }
  2949. getRowEnd(item: number) {
  2950. if (item.toString() === '0') {
  2951. return 1;
  2952. } else {
  2953. return 0;
  2954. }
  2955. }
  2956. // [Start itemMove_start]
  2957. // itemMoveGrid(index: number, newIndex: number): void {
  2958. // if (!this.isDraggable(newIndex)) {
  2959. // return;
  2960. // }
  2961. // let tmp = this.videoLocalList.splice(index, 1);
  2962. // this.videoLocalList.splice(newIndex, 0, tmp[0]);
  2963. // // this.bigItemIndex = this.videoLocalList.findIndex((item) => item === 0);
  2964. // }
  2965. isInLeft(index: number) {
  2966. return index % 2 == 0;
  2967. }
  2968. down(index: number): void {
  2969. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  2970. return;
  2971. }
  2972. this.offsetY -= this.FIX_VP_Y;
  2973. this.dragRefOffSetY += this.FIX_VP_Y;
  2974. this.itemMove(index, index + 1);
  2975. }
  2976. up(index: number): void {
  2977. if (!this.isDraggable(index - 2)) {
  2978. return;
  2979. }
  2980. this.offsetY += this.FIX_VP_Y;
  2981. this.dragRefOffSetY -= this.FIX_VP_Y;
  2982. this.itemMove(index, index - 1);
  2983. }
  2984. left(index: number): void {
  2985. if (this.isInLeft(index)) {
  2986. return;
  2987. }
  2988. if (!this.isDraggable(index - 1)) {
  2989. return;
  2990. }
  2991. this.offsetX += this.FIX_VP_X;
  2992. this.dragRefOffSetX -= this.FIX_VP_X;
  2993. this.itemMove(index, index - 1)
  2994. }
  2995. right(index: number): void {
  2996. if (!this.isInLeft(index)) {
  2997. return;
  2998. }
  2999. if (!this.isDraggable(index + 1)) {
  3000. return;
  3001. }
  3002. this.offsetX -= this.FIX_VP_X;
  3003. this.dragRefOffSetX += this.FIX_VP_X;
  3004. this.itemMove(index, index + 1)
  3005. }
  3006. private scroller: Scroller = new Scroller();
  3007. @State startIndex: number = 0
  3008. @State endIndex: number = 0
  3009. @State scaleValue: number = 1
  3010. @State pinchValue: number = 1
  3011. layoutOptionsForHeader: GridLayoutOptions = {
  3012. regularSize: [1, 1], // 只支持[1, 1]
  3013. irregularIndexes: [0], // 索引为0的GridItem占用一行
  3014. };
  3015. @Builder
  3016. getGridView() {
  3017. Grid(this.scroller, this.layoutOptionsForHeader) {
  3018. GridItem() {
  3019. if (this.isShowCoverHeader()) {
  3020. this.coverHeader()
  3021. } else {
  3022. this.listViewTitle()
  3023. }
  3024. }
  3025. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  3026. GridItem() {
  3027. Stack({ alignContent: Alignment.Center }) {
  3028. this.MusicItemGrid(item, index)
  3029. }
  3030. }
  3031. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  3032. {
  3033. preview: MenuPreviewMode.IMAGE,
  3034. previewAnimationOptions: { scale: [0.8, 1.0] },
  3035. })
  3036. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  3037. {
  3038. preview: MenuPreviewMode.IMAGE,
  3039. previewAnimationOptions: { scale: [0.8, 1.0] },
  3040. })
  3041. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  3042. TransitionEffect.scale({ x: 0, y: 0 })))
  3043. .clickEffect({ level: ClickEffectLevel.LIGHT })
  3044. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  3045. .zIndex(this.dragItem === index ? 1 : 0)
  3046. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  3047. // .hitTestBehavior(this.isDraggable(this.videoLocalList.indexOf(item)) ? HitTestMode.Default : HitTestMode.None)
  3048. }, (item: VideoItem) => item.filePath)
  3049. }
  3050. .width(this.isShowHeader ? '100%' : '94%')
  3051. .height('100%')
  3052. .editMode(true)
  3053. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3054. .animation({ duration: 500, curve: Curve.Ease }))
  3055. // .margin({ bottom: this.isCoverOpacity() ? 80 : 175 })
  3056. .margin({
  3057. bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? this.topBarHeight+30 : this.topBarHeight+90)
  3058. : (this.isShowCoverHeader() ? this.topBarHeight+45 : this.topBarHeight+128)
  3059. })
  3060. .layoutWeight(1)
  3061. .scrollBar(BarState.Off)
  3062. .supportAnimation(true)
  3063. .cachedCount(this.twoFingerType==1?5:this.twoFingerType==2?4:3)
  3064. // .columnsTemplate('1fr '.repeat(this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM ? 2 : 5))
  3065. .columnsTemplate(
  3066. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  3067. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  3068. )
  3069. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  3070. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  3071. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  3072. .gesture(PinchGesture({ fingers: 2 })
  3073. .onActionEnd((event: GestureEvent) => {
  3074. this.setGridTwoFingers()
  3075. })
  3076. .onActionUpdate(e => {
  3077. this.scaleValue = this.pinchValue * e.scale
  3078. })
  3079. .onActionStart(e => {
  3080. }))
  3081. .enableScrollInteraction(true)
  3082. // 滚轴滑动,记录下滑动时的起始位置和终点位置
  3083. .onScrollIndex((start: number, end: number) => {
  3084. this.startIndex = start
  3085. this.endIndex = end
  3086. })
  3087. .onScrollFrameBegin((offset: number) => {
  3088. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  3089. // if (this.isPhoneLan()) {
  3090. // this.setBarHeightHide(offset)
  3091. // } else
  3092. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  3093. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  3094. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  3095. if (this.isScrollHide) {
  3096. this.setBarHeightHide2(offset)
  3097. } else {
  3098. this.setBarHeightNormal()
  3099. }
  3100. } else {
  3101. this.setBarHeightHide(offset)
  3102. }
  3103. return { offsetRemain: offset };
  3104. })
  3105. //允许拖拽音乐和视频到List或Grid上自动导入视频
  3106. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3107. .onDrop((event?: DragEvent) => {
  3108. try {
  3109. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3110. if (dragData !== undefined) {
  3111. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3112. if (records.length > 0) {
  3113. for (let i = 0; i < records.length; i++) {
  3114. let types = records[i].getTypes();
  3115. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3116. const fileUriUds =
  3117. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3118. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3119. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3120. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3121. this.targetFile = fileUriUds.oriUri;
  3122. this.saveVideoDatas([this.targetFile])
  3123. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3124. }
  3125. }
  3126. }
  3127. } else {
  3128. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3129. }
  3130. } else {
  3131. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3132. }
  3133. } catch (error) {
  3134. const err = error as BusinessError;
  3135. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3136. }
  3137. })
  3138. }
  3139. @State targetFile: string = '';
  3140. setGridTwoFingers() {
  3141. this.pinchValue = this.scaleValue;
  3142. Logger.info('this.pinchValue = ' + this.pinchValue);
  3143. if (this.pinchValue >= 1) {
  3144. this.twoFingerType++
  3145. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  3146. if (this.twoFingerType > 3) {
  3147. this.twoFingerType = 3
  3148. }
  3149. } else {
  3150. this.twoFingerType--
  3151. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  3152. if (this.twoFingerType < 1) {
  3153. this.twoFingerType = 3
  3154. this.isGridMusic = false
  3155. }
  3156. }
  3157. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  3158. this.pinchValue = 1;
  3159. this.scaleValue = 1;
  3160. }
  3161. @State longItemFilePath: string = ''
  3162. @State tempLyricContent: string = ''
  3163. @Builder
  3164. private MusicItemGrid(item: VideoItem, index: number) {
  3165. Button({ type: ButtonType.Normal, stateEffect: false }) {
  3166. Stack() {
  3167. Column() {
  3168. Image(StrUtil.isEmpty(item.pixelMapPath) ? Utility.getMusisBg2(index) : item.pixelMapPath)
  3169. .height(this.getGridHeight())
  3170. .width(this.getGridWight())
  3171. .draggable(false)
  3172. .interpolation(ImageInterpolation.Medium)// 用于重采样后的抗锯齿
  3173. .autoResize(true) // 重采样,可减少内存占用
  3174. .alt($r('app.media.ic_avatar2'))
  3175. .clip(true)
  3176. .borderRadius({
  3177. topLeft: 12,
  3178. topRight: 12,
  3179. bottomLeft: 0,
  3180. bottomRight: 0
  3181. })
  3182. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  3183. height: '99%' ,
  3184. dragBar: true,
  3185. onDisappear: () => {
  3186. this.longItemFilePath = '';
  3187. this.tempLyricContent = ''
  3188. },
  3189. showClose: true,
  3190. preferType: SheetType.CENTER ,
  3191. title: { title: '编辑标签' }
  3192. })
  3193. .draggable(false)
  3194. .opacity(this.opacityItem)// 绑定透明度
  3195. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3196. // .animation({ duration: 500, curve: Curve.Ease }))
  3197. .animation({
  3198. duration: 666,
  3199. curve: 'ease-in-out' // 可选动画曲线
  3200. })
  3201. .margin({
  3202. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3203. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3204. })
  3205. Column() {
  3206. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  3207. .fontSize(this.twoFingerType == 1 ? 14 : this.twoFingerType == 2 ? 16 : 18)
  3208. .maxLines(1)
  3209. .fontWeight(FontWeight.Bold)
  3210. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3211. .animation({
  3212. duration: 555,
  3213. curve: 'Linear',
  3214. })
  3215. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  3216. height: '95%',
  3217. dragBar: true,
  3218. showClose: true,
  3219. onDisappear: () => {
  3220. this.longItemFilePathDetail = '';
  3221. },
  3222. blurStyle:BlurStyle.Thin,
  3223. backgroundColor:Color.Transparent,
  3224. preferType: SheetType.CENTER ,
  3225. title: { title: '详情' }
  3226. })
  3227. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3228. $r('app.color.text_color'))
  3229. Column() {
  3230. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  3231. .fontSize(11)
  3232. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  3233. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3234. .fontColor($r('app.color.text_color'))
  3235. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  3236. .fontSize(11)
  3237. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  3238. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3239. .fontColor($r('app.color.text_color'))
  3240. Row(){
  3241. Column(){
  3242. Text(item.md5Str?.includes('Lossless')?
  3243. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  3244. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  3245. .padding({ top: 3,right:6,left:6,bottom:3 })
  3246. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3247. $r('app.color.text_color'))
  3248. .fontWeight(500)
  3249. .borderRadius(12)
  3250. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  3251. .backgroundColor('#FFC107')
  3252. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  3253. }
  3254. .margin({ top: 2 ,right:6})
  3255. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  3256. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  3257. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  3258. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  3259. .maxLines(1)
  3260. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3261. .margin({ top: 2})
  3262. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  3263. || item.type == CommonConstants.TYPE_IS_ALBUM
  3264. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3265. .fontWeight(FontWeight.Medium)
  3266. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3267. $r('app.color.text_color'))
  3268. }
  3269. }
  3270. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  3271. }
  3272. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 55 : 42)
  3273. .width(this.getGridWight())
  3274. .justifyContent(FlexAlign.Center)
  3275. .margin({
  3276. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3277. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3278. })
  3279. }
  3280. .width(this.getGridWight())
  3281. .borderRadius(12)
  3282. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?Utility.getMusisBg2(index):item.pixelMapPath)
  3283. .backgroundImageSize({ height: '100%', width: '100%' })
  3284. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  3285. .animation({ curve: Curve.Sharp, duration: 300 })
  3286. Checkbox({ name: 'checkbox' + index })
  3287. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  3288. .selectedColor(this.themeColor)
  3289. .shape(CheckBoxShape.CIRCLE)
  3290. .opacity(this.isMultiSelect ? 1 : 0)
  3291. .animation({
  3292. duration: 666,
  3293. curve: 'Smooth' // 可选动画曲线
  3294. })
  3295. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  3296. Visibility.None)
  3297. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  3298. .margin({ left: 20, top: 8, bottom: 8 })
  3299. .width(38)
  3300. .height(38)
  3301. }
  3302. }
  3303. .backgroundColor(Color.Transparent)
  3304. .width('100%')
  3305. .padding({ top: 15 })
  3306. .height(this.getGridAllHeight())
  3307. .onClick(() => {
  3308. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  3309. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3310. this.handleFileSelection(item, !isChecked);
  3311. } else {
  3312. this.doPlay(item, index)
  3313. }
  3314. })
  3315. }
  3316. getGridAllHeight() {
  3317. let heightG = 222
  3318. switch (this.twoFingerType) {
  3319. case 1:
  3320. heightG = 118
  3321. break;
  3322. case 2:
  3323. heightG = 168
  3324. break;
  3325. case 3:
  3326. heightG = 222
  3327. break;
  3328. }
  3329. return heightG
  3330. }
  3331. getGridHeight() {
  3332. let heightG = 150
  3333. switch (this.twoFingerType) {
  3334. case 1:
  3335. heightG = 55
  3336. break;
  3337. case 2:
  3338. heightG = 100
  3339. break;
  3340. case 3:
  3341. heightG = 150
  3342. break;
  3343. }
  3344. return heightG
  3345. }
  3346. getGridWight() {
  3347. let wightG = 158
  3348. switch (this.twoFingerType) {
  3349. case 1:
  3350. wightG = 80
  3351. break;
  3352. case 2:
  3353. wightG = 110
  3354. break;
  3355. case 3:
  3356. wightG = 158
  3357. break;
  3358. }
  3359. return wightG
  3360. }
  3361. @State isShowDetail:boolean = false
  3362. // @State isShowDetailGrid:boolean = false
  3363. // @State isShowEditGrid:boolean = false
  3364. @State longItemFilePathDetail:string =''
  3365. @Builder
  3366. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  3367. if(
  3368. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  3369. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3370. item.name === LocalMusic.STR_HISTORY_MUSIC)
  3371. ){
  3372. //如果是专辑和艺术家的首页,不能长按
  3373. //如果是我的收藏 最近播放等也不能长按
  3374. }else{
  3375. Scroll() {
  3376. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  3377. Menu() {
  3378. MenuItem({
  3379. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  3380. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  3381. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  3382. })
  3383. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3384. .onClick(() => {
  3385. if (item) {
  3386. this.doFav(item)
  3387. }
  3388. this.longItemFilePath = ''
  3389. })
  3390. MenuItem({
  3391. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  3392. content: '下一首播放'
  3393. })
  3394. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3395. .onClick(() => {
  3396. this.addToNextPlay(item);
  3397. this.longItemFilePath = ''
  3398. })
  3399. if(Utility.isNoble()){
  3400. MenuItem({
  3401. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  3402. content: '编辑标签'
  3403. })
  3404. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  3405. height: '99%',
  3406. dragBar: true,
  3407. showClose: true,
  3408. preferType: SheetType.CENTER ,
  3409. title: { title: '编辑标签' }
  3410. })
  3411. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3412. .onClick(async() => {
  3413. this.setEditStrEmpty()
  3414. this.tempLyricContent = await this.getLyricContent(item);
  3415. // console.info('onecold 长按this.tempLyricContent' +this.tempLyricContent)
  3416. if(this.isGridMusic){
  3417. this.longItemFilePath = item.filePath
  3418. }else{
  3419. this.isShowEdit = !this.isShowEdit;
  3420. }
  3421. })
  3422. }
  3423. MenuItem({
  3424. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  3425. content: $r('app.string.select_all')
  3426. })
  3427. .onClick(() => {
  3428. this.isMultiSelect = !this.isMultiSelect
  3429. this.longItemFilePath = ''
  3430. })
  3431. MenuItem({
  3432. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  3433. content: $r('app.string.rename')
  3434. })
  3435. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  3436. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3437. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  3438. .onClick(() => {
  3439. this.showReNameDialog(item, index + '', filePath)
  3440. this.longItemFilePath = ''
  3441. })
  3442. MenuItem({
  3443. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  3444. content: $r('app.string.delete')
  3445. })
  3446. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  3447. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  3448. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  3449. .onClick(() => {
  3450. this.showWarnIsDeleteFile(item, index + '', filePath)
  3451. this.longItemFilePath = ''
  3452. })
  3453. MenuItem({
  3454. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  3455. content: $r('app.string.detail')
  3456. })
  3457. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  3458. height:'95%',
  3459. dragBar: true,
  3460. showClose: true,
  3461. blurStyle:BlurStyle.Thin,
  3462. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3463. backgroundColor:Color.Transparent,
  3464. title: { title: '详情信息' }
  3465. })
  3466. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3467. .onClick(() => {
  3468. if(this.isGridMusic){
  3469. this.longItemFilePathDetail = item.filePath
  3470. }else{
  3471. this.isShowDetail = !this.isShowDetail
  3472. }
  3473. })
  3474. MenuItem({
  3475. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  3476. content: $r('app.string.share')
  3477. })
  3478. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3479. .onClick(() => {
  3480. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  3481. this.longItemFilePath = ''
  3482. })
  3483. }
  3484. .font({ size: 15, weight: FontWeight.Normal })
  3485. }
  3486. .width(180)
  3487. }
  3488. .height('auto')
  3489. }
  3490. }
  3491. private listMaxScrollOffsetY: number = 0
  3492. @State selectedIndex: number = -1
  3493. setlistTwoFingers() {
  3494. this.pinchValue = this.scaleValue;
  3495. Logger.info('this.pinchValue = ' + this.pinchValue);
  3496. if (this.pinchValue >= 1) {
  3497. this.twoFingerType++
  3498. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  3499. if (this.twoFingerType > 3) {
  3500. this.twoFingerType = 1
  3501. this.isGridMusic = true
  3502. }
  3503. } else {
  3504. this.twoFingerType--
  3505. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  3506. if (this.twoFingerType < 1) {
  3507. this.twoFingerType = 1
  3508. }
  3509. }
  3510. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  3511. this.pinchValue = 1;
  3512. this.scaleValue = 1;
  3513. }
  3514. @Builder
  3515. getListView() {
  3516. List({ scroller: this.listScroller }) {
  3517. ListItemGroup({ header: this.coverHeader() }) {
  3518. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  3519. ListItem() {
  3520. Column() {
  3521. if (item.type === CommonConstants.TYPE_IS_DIR
  3522. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  3523. this.DirItem(item, index)
  3524. } else if (item.type === CommonConstants.TYPE_IS_CSJAD) { //如果是穿山甲广告
  3525. } else {
  3526. this.MusicItem(item, index)
  3527. }
  3528. }
  3529. .shadow(this.scaleItem === index ? {
  3530. radius: 70,
  3531. color: '#15000000',
  3532. offsetX: 0,
  3533. offsetY: 0
  3534. } :
  3535. {
  3536. radius: 0,
  3537. color: '#15000000',
  3538. offsetX: 0,
  3539. offsetY: 0
  3540. })
  3541. .animation({ curve: Curve.Sharp, duration: 300 })
  3542. }
  3543. // .transition(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }))
  3544. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  3545. .animation({ duration: 500 }),
  3546. TransitionEffect.scale({ x: 0, y: 0 })))
  3547. .clickEffect({ level: ClickEffectLevel.LIGHT })
  3548. .swipeAction((
  3549. (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
  3550. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  3551. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath) } : {}) //左滑
  3552. .onClick(() => {
  3553. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  3554. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3555. this.handleFileSelection(item, !isChecked);
  3556. } else {
  3557. this.doPlay(item, index)
  3558. }
  3559. })
  3560. //拖动List关键代码开始
  3561. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  3562. .zIndex(this.dragItem === index ? 1 : 0)
  3563. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  3564. .gesture(
  3565. GestureGroup(GestureMode.Sequence,
  3566. LongPressGesture({ repeat: true })
  3567. .onAction((event?: GestureEvent) => {
  3568. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3569. this.scaleItem = index
  3570. })
  3571. })
  3572. .onActionEnd(() => {
  3573. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3574. this.scaleItem = -1
  3575. })
  3576. }),
  3577. PanGesture({ fingers: 1, direction: null, distance: 0 })
  3578. .onActionStart(() => {
  3579. this.dragItem = index // 记录当前拖动项索引
  3580. this.dragRefOffset = 0 // 重置偏移基准
  3581. })
  3582. .onActionUpdate((event: GestureEvent) => {
  3583. this.offsetY = event.offsetY - this.dragRefOffset;
  3584. this.neighborItem = -1;
  3585. let indexA = this.videoLocalList.indexOf(item);
  3586. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  3587. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  3588. let value: number = 0;
  3589. if (this.offsetY < 0) {
  3590. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  3591. this.neighborItem = indexA - 1;
  3592. this.neighborScale = 1 - value / 20;
  3593. } else if (this.offsetY > 0) {
  3594. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  3595. this.neighborItem = indexA + 1;
  3596. this.neighborScale = 1 - value / 20;
  3597. }
  3598. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  3599. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3600. this.offsetY -= this.ITEM_INTV;
  3601. this.dragRefOffset += this.ITEM_INTV;
  3602. this.itemMove(indexA, indexA + 1);
  3603. });
  3604. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  3605. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3606. this.offsetY += this.ITEM_INTV;
  3607. this.dragRefOffset -= this.ITEM_INTV;
  3608. this.itemMove(indexA, indexA - 1);
  3609. });
  3610. }
  3611. let curListOffset = this.listScroller.currentOffset()
  3612. // 获取手指信息
  3613. let fingerInfo = event.fingerList[0]
  3614. let clickPercentY =
  3615. (fingerInfo.globalY - Number(this.listArea.globalPosition.y)) / Number(this.listArea.height)
  3616. if (clickPercentY > 0.8 && !this.listScroller.isAtEnd()) {
  3617. let scrollVelocity = clickPercentY > 0.9 ? 4 : 2
  3618. if (this.listMaxScrollOffsetY - curListOffset.yOffset > scrollVelocity + 5) {
  3619. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset += scrollVelocity })
  3620. }
  3621. } else if (clickPercentY < 0.2 && curListOffset.yOffset >= 0) {
  3622. let scrollVelocity = clickPercentY < 0.1 ? 4 : 2
  3623. if (curListOffset.yOffset > scrollVelocity + 5) {
  3624. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset -= scrollVelocity })
  3625. }
  3626. }
  3627. })
  3628. .onActionEnd((event: GestureEvent) => {
  3629. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3630. this.dragItem = -1
  3631. this.neighborItem = -1
  3632. })
  3633. animateTo({
  3634. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  3635. }, () => {
  3636. this.scaleItem = -1
  3637. })
  3638. })
  3639. )
  3640. .onCancel(() => {
  3641. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3642. this.dragItem = -1
  3643. this.neighborItem = -1
  3644. })
  3645. animateTo({
  3646. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  3647. }, () => {
  3648. this.scaleItem = -1
  3649. })
  3650. })
  3651. ) //拖动List关键代码结束
  3652. }, (item: VideoItem) => item.filePath)
  3653. }
  3654. }
  3655. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  3656. .gesture(PinchGesture({ fingers: 2 })
  3657. .onActionEnd((event: GestureEvent) => {
  3658. this.setlistTwoFingers()
  3659. })
  3660. .onActionUpdate(e => {
  3661. this.scaleValue = this.pinchValue * e.scale
  3662. })
  3663. .onActionStart(e => {
  3664. }))
  3665. // .divider({ strokeWidth: 1, color: this.isDarkMode? '#333333':'#ffe9f0f0' })
  3666. .margin({
  3667. bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? this.topBarHeight+25 : this.topBarHeight+80)
  3668. : (this.isShowCoverHeader() ? this.topBarHeight+35 : this.isHiCarSmall()?this.topBarHeight+90:this.topBarHeight+125)
  3669. })
  3670. .cachedCount(6)
  3671. .borderRadius(20)
  3672. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  3673. TransitionEffect.scale({ x: 0, y: 0 })))
  3674. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3675. // .animation({ duration: 500, curve: Curve.Ease }))
  3676. .layoutWeight(1)
  3677. .onScrollIndex((start) => {
  3678. this.selectedIndex = start
  3679. })
  3680. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  3681. .lanes(
  3682. new BreakpointType<number>({
  3683. sm: 1,
  3684. md: 2,
  3685. lg: 2,
  3686. xl: 3,
  3687. xxl: 4
  3688. }).getValue(this.currentBreakpoint),
  3689. new BreakpointType<number>({
  3690. sm: 0,
  3691. md: 12,
  3692. lg: 12,
  3693. xl: 16,
  3694. xxl: 20
  3695. }).getValue(this.currentBreakpoint)
  3696. )
  3697. .onAreaChange((oldValue: Area, newValue: Area) => {
  3698. this.listArea = newValue
  3699. if (this.twoFingerType == 3) {
  3700. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  3701. } else if (this.twoFingerType == 2) {
  3702. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  3703. } else if (this.twoFingerType == 1) {
  3704. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  3705. }
  3706. })
  3707. .onScrollFrameBegin((offset: number) => {
  3708. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  3709. // if (this.isPhoneLan()) {
  3710. // this.setBarHeightHide(offset)
  3711. // } else
  3712. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  3713. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  3714. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  3715. if (this.isScrollHide) {
  3716. this.setBarHeightHide2(offset)
  3717. } else {
  3718. this.setBarHeightNormal()
  3719. }
  3720. } else {
  3721. this.setBarHeightHide(offset)
  3722. }
  3723. return { offsetRemain: offset };
  3724. })
  3725. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  3726. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3727. .onDrop((event?: DragEvent) => {
  3728. try {
  3729. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3730. if (dragData !== undefined) {
  3731. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3732. if (records.length > 0) {
  3733. for (let i = 0; i < records.length; i++) {
  3734. let types = records[i].getTypes();
  3735. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3736. const fileUriUds =
  3737. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3738. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3739. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3740. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3741. this.targetFile = fileUriUds.oriUri;
  3742. this.saveVideoDatas([this.targetFile])
  3743. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3744. }
  3745. }
  3746. }
  3747. } else {
  3748. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3749. }
  3750. } else {
  3751. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3752. }
  3753. } catch (error) {
  3754. const err = error as BusinessError;
  3755. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3756. }
  3757. })
  3758. }
  3759. setBarHeightNormal() {
  3760. this.hideDone = false;
  3761. this.getUIContext().animateTo({
  3762. duration: 300
  3763. }, () => {
  3764. this.bottomBarHeight = 55 + 0;
  3765. this.topBarHeight = 50 + 0;
  3766. this.barOpacity = 1;
  3767. this.barBottomOpacity = 1
  3768. this.currentYOffset = 0;
  3769. this.isHiding = false;
  3770. });
  3771. }
  3772. setBarHeightHide(offset: number) {
  3773. if (offset > 0 && !this.hideDone) {
  3774. this.currentYOffset += offset;
  3775. if (this.currentYOffset <= 100) {
  3776. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  3777. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  3778. this.barOpacity = 1 - this.currentYOffset / 100;
  3779. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  3780. } else {
  3781. this.topBarHeight = 0;
  3782. this.bottomBarHeight = 0;
  3783. this.barBottomOpacity = 0
  3784. this.barOpacity = 0;
  3785. this.hideDone = true;
  3786. }
  3787. this.isHiding = true;
  3788. }
  3789. if (offset < 0 && this.isHiding) {
  3790. this.hideDone = false;
  3791. this.getUIContext().animateTo({
  3792. duration: 300
  3793. }, () => {
  3794. this.bottomBarHeight = 55 + 0;
  3795. this.topBarHeight = 50 + 0;
  3796. this.barOpacity = 1;
  3797. this.barBottomOpacity = 1
  3798. this.currentYOffset = 0;
  3799. this.isHiding = false;
  3800. });
  3801. }
  3802. }
  3803. //这个方法没隐藏bottomBar,只隐藏topbar
  3804. setBarHeightHide2(offset: number) {
  3805. if (offset > 0 && !this.hideDone) {
  3806. this.currentYOffset += offset;
  3807. if (this.currentYOffset <= 100) {
  3808. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  3809. this.barOpacity = 1 - this.currentYOffset / 100;
  3810. } else {
  3811. this.topBarHeight = 0;
  3812. this.barOpacity = 0;
  3813. this.hideDone = true;
  3814. }
  3815. this.isHiding = true;
  3816. }
  3817. if (offset < 0 && this.isHiding) {
  3818. this.hideDone = false;
  3819. this.getUIContext().animateTo({
  3820. duration: 300
  3821. }, () => {
  3822. this.topBarHeight = 50 + 0;
  3823. this.barOpacity = 1;
  3824. this.currentYOffset = 0;
  3825. this.isHiding = false;
  3826. });
  3827. }
  3828. }
  3829. private doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean) {
  3830. switch (item.type) {
  3831. case CommonConstants.TYPE_IS_DIR:
  3832. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  3833. let offsetB = 0
  3834. if (this.isGridMusic) {
  3835. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  3836. let cur = this.scroller.currentOffset()
  3837. if (cur && typeof cur.yOffset === 'number') {
  3838. offsetB = cur.yOffset
  3839. }
  3840. }
  3841. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  3842. } else {
  3843. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  3844. let cur = this.listScroller.currentOffset()
  3845. if (cur && typeof cur.yOffset === 'number') {
  3846. offsetB = cur.yOffset
  3847. }
  3848. }
  3849. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  3850. }
  3851. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  3852. this.showVerifyDialog()
  3853. this.currentTitleName = '私密音频'
  3854. this.currentTitleCover = $r('app.media.ic_avatar5')
  3855. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  3856. this.titleBarModel.setTitleName('最近播放')
  3857. this.currentTitleCover = $r('app.media.ic_avatar2')
  3858. this.currentTitleName = '最近播放'
  3859. //加载动画效果
  3860. this.updateListData(this.historyList, true)
  3861. // this.videoLocalList = this.historyList
  3862. if (ArrayUtil.isEmpty(this.historyList)) {
  3863. ToastUtil.showToast('最近播放记录空空如也')
  3864. } else {
  3865. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  3866. }
  3867. this.isHistory = true
  3868. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3869. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  3870. this.titleBarModel.setTitleName('我的收藏')
  3871. this.currentTitleName = '我的收藏'
  3872. this.currentTitleCover = $r('app.media.ic_avatar1')
  3873. //加载动画效果
  3874. this.updateListData(this.favList)
  3875. if (ArrayUtil.isEmpty(this.favList)) {
  3876. ToastUtil.showToast('无音乐收藏记录')
  3877. } else {
  3878. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  3879. }
  3880. this.isFavMusic = true
  3881. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3882. } else {
  3883. this.currentTitleName = item.name
  3884. this.currentPath = item.filePath
  3885. this.currentTitleCover = $r('app.media.ic_avatar5')
  3886. this.getSortedFiles(this.currentPath)
  3887. }
  3888. //进入歌单的时候的滚动位置在顶部
  3889. if (this.isGridMusic) {
  3890. this.scroller.scrollToIndex(0)
  3891. }
  3892. setTimeout(() => {
  3893. if (this.modeType == 0) {
  3894. if (!this.isGridMusic) {
  3895. this.listScroller.scrollToIndex(0)
  3896. }
  3897. }
  3898. }, 200)
  3899. break;
  3900. case CommonConstants.TYPE_IS_ARTIST:
  3901. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  3902. let offsetA = 0
  3903. if (this.isGridMusic) {
  3904. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  3905. let cur = this.scroller.currentOffset()
  3906. if (cur && typeof cur.yOffset === 'number') {
  3907. offsetA = cur.yOffset
  3908. }
  3909. }
  3910. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  3911. } else {
  3912. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  3913. let cur = this.listScroller.currentOffset()
  3914. if (cur && typeof cur.yOffset === 'number') {
  3915. offsetA = cur.yOffset
  3916. }
  3917. }
  3918. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  3919. }
  3920. let mList = this.artistMap.get(item.name)
  3921. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  3922. Utility.doSortListAscending(mList)
  3923. this.isCanBack = true
  3924. this.titleBarModel.setTitleName(item.name)
  3925. this.currentTitleName = '艺术家:' + item.name
  3926. if (item.pixelMapPath) {
  3927. this.currentTitleCover = item.pixelMapPath
  3928. }
  3929. this.updateListData(mList)
  3930. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3931. }
  3932. //进入歌单的时候的滚动位置在顶部
  3933. if (this.isGridMusic) {
  3934. this.scroller.scrollToIndex(0)
  3935. }
  3936. break;
  3937. case CommonConstants.TYPE_IS_ALBUM:
  3938. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  3939. let offset = 0
  3940. if (this.isGridMusic) {
  3941. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  3942. let cur = this.scroller.currentOffset()
  3943. if (cur && typeof cur.yOffset === 'number') {
  3944. offset = cur.yOffset
  3945. }
  3946. }
  3947. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  3948. } else {
  3949. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  3950. let cur = this.listScroller.currentOffset()
  3951. if (cur && typeof cur.yOffset === 'number') {
  3952. offset = cur.yOffset
  3953. }
  3954. }
  3955. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  3956. }
  3957. let albumList = this.albumMap.get(item.name)
  3958. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  3959. Utility.doSortListAscending(albumList)
  3960. this.isCanBack = true
  3961. this.titleBarModel.setTitleName(item.name)
  3962. this.currentTitleName = '专辑:' + item.name
  3963. if (item.pixelMapPath) {
  3964. this.currentTitleCover = item.pixelMapPath
  3965. }
  3966. this.updateListData(albumList)
  3967. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  3968. this.mScrollMap.set(item.name, this.selectedIndex)
  3969. }
  3970. //进入歌单的时候的滚动位置在顶部
  3971. if (this.isGridMusic) {
  3972. this.scroller.scrollToIndex(0)
  3973. }
  3974. break;
  3975. case CommonConstants.TYPE_IS_CSJAD:
  3976. return
  3977. break;
  3978. case CommonConstants.TYPE_LOCAL:
  3979. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  3980. this.stop();
  3981. }
  3982. if (isFromSonPlayList) { //点击来自右下角的播放列表
  3983. this.currentSong = item
  3984. if (index !== undefined) {
  3985. this.curIndex = index
  3986. }
  3987. } else {
  3988. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  3989. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  3990. this.songList = globalVideoList
  3991. this.sonDataSource.pushArrayData(this.songList)
  3992. this.currentSong = globalVideoList[this.curIndex]
  3993. }
  3994. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  3995. this.videoUrl = this.currentSong.filePath
  3996. this.name = this.currentSong.name
  3997. this.cover = this.currentSong.pixelMapPath
  3998. this.artist = this.currentSong.artist
  3999. LogUtil.info('this.currentSong.duration =' + this.currentSong.duration)
  4000. LogUtil.info('this.currentSong.sampleRate =' + this.currentSong.sampleRate)
  4001. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  4002. this.startPlayOrResumePlay()
  4003. break;
  4004. }
  4005. }
  4006. @Builder
  4007. PlayController() {
  4008. Column() {
  4009. Line().width('100%').height(1).backgroundColor($r('app.color.index_background'))
  4010. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  4011. Row() {
  4012. Row() {
  4013. RotatingCover({ songLabel: this.currentSong?.pixelMapPath })
  4014. Column() {
  4015. Text(this.currentSong?.name)
  4016. .fontSize(16)
  4017. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4018. .maxLines(1)
  4019. .fontColor($r('app.color.text_color'))
  4020. .fontWeight(500)
  4021. Row() {
  4022. Text(this.currentSong?.artist)
  4023. .margin({ top: 2 })
  4024. .fontSize(13)
  4025. .maxLines(1)
  4026. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4027. .fontColor($r('app.color.text_color'))
  4028. }
  4029. }
  4030. .alignItems(HorizontalAlign.Start)
  4031. .margin({ right: 22 })
  4032. }
  4033. .padding({ right: 18 })
  4034. .layoutWeight(1)
  4035. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4036. .onClick(() => {
  4037. if (ArrayUtil.isNotEmpty(this.songList)) {
  4038. this.isShowPlay = true;
  4039. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  4040. this.initLyric(lyricPath);
  4041. this.startAutoHide()
  4042. } else {
  4043. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4044. }
  4045. })
  4046. Row() {
  4047. Image($r('app.media.hm_previous'))
  4048. .height(28)
  4049. .width(28)
  4050. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4051. .margin({ left: 8, right: 16 })
  4052. .fillColor(this.themeColor)
  4053. .displayPriority(2)
  4054. .onClick(() => {
  4055. if (ArrayUtil.isNotEmpty(this.songList)) {
  4056. this.playPrevious()
  4057. } else {
  4058. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4059. }
  4060. })
  4061. //播放进度条
  4062. Stack() {
  4063. Progress({
  4064. value: Math.floor(this.progressValue),
  4065. type: ProgressType.Ring,
  4066. })
  4067. .color(this.themeColor)// 进度条前景色为灰色
  4068. .backgroundColor($r('app.color.index_background'))
  4069. .height(40)
  4070. .aspectRatio(CommonConstants.ASPECT_RATIO)
  4071. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ? $r('app.media.hm_pause') : $r('app.media.hm_play2'))
  4072. .height(38)
  4073. .width(38)
  4074. .displayPriority(3)
  4075. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4076. .fillColor(this.themeColor)
  4077. .onClick(() => {
  4078. if (ArrayUtil.isNotEmpty(this.songList)) {
  4079. this.playOrPause()
  4080. } else {
  4081. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4082. }
  4083. })
  4084. }
  4085. Image($r('app.media.hm_next'))
  4086. .height(28)
  4087. .width(28)
  4088. .margin({
  4089. right: 16,
  4090. left: 16
  4091. })
  4092. .fillColor(this.themeColor)
  4093. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4094. .displayPriority(2)
  4095. .onClick(() => {
  4096. if (ArrayUtil.isNotEmpty(this.songList)) {
  4097. this.playNext()
  4098. } else {
  4099. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4100. }
  4101. })
  4102. Image($r('app.media.hm_playlist'))
  4103. .height(28)
  4104. .width(28)
  4105. .displayPriority(1)
  4106. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  4107. .fillColor(this.themeColor)
  4108. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  4109. height: '95%',
  4110. dragBar: true,
  4111. showClose: true,
  4112. blurStyle: BlurStyle.Thin,
  4113. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  4114. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  4115. title: {
  4116. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  4117. + `(${this.songList.length}首)`
  4118. }
  4119. })
  4120. .onClick(() => {
  4121. if (ArrayUtil.isNotEmpty(this.songList)) {
  4122. this.isShowSheet = !this.isShowSheet;
  4123. this.isFrontWhite = false
  4124. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  4125. setTimeout(() => {
  4126. this.playListScroller.scrollToIndex(this.curIndex, true, ScrollAlign.CENTER)
  4127. }, 123)
  4128. } else {
  4129. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  4130. }
  4131. })
  4132. }
  4133. }
  4134. .width('100%')
  4135. .height(this.bottomBarHeight)
  4136. .justifyContent(FlexAlign.Center)
  4137. .hitTestBehavior(HitTestMode.Transparent)
  4138. .backgroundColor(this.isCustomizeBg ? Color.Transparent : $r('app.color.bottom_control_background'))
  4139. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  4140. // modalTransition: ModalTransition.DEFAULT,
  4141. transition: AnimationHelper.transitionInDown(666),
  4142. backgroundColor: 'rgba(0, 0, 0, 0.9)',
  4143. })
  4144. .padding({
  4145. left: 16,
  4146. right: 16
  4147. })
  4148. Line()
  4149. .width('100%')
  4150. .height(25)
  4151. .backgroundColor($r('app.color.bottom_control_background'))// .visibility(this.isPhoneLan()?Visibility.None:this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
  4152. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  4153. }
  4154. .clickEffect({ level: ClickEffectLevel.HEAVY })
  4155. }
  4156. @State isFrontWhite: boolean = false
  4157. //播放列表布局
  4158. @Builder
  4159. PlayListSheet() {
  4160. Column() {
  4161. this.PlayList()
  4162. }
  4163. .width('100%')
  4164. .height('100%')
  4165. }
  4166. @State titleStr: string = ''
  4167. @State ablumStr: string = ''
  4168. @State artistStr: string = ''
  4169. @State lyricConStr: string = ''
  4170. @State currentEditItem: string = ''
  4171. @State yearStr: string = ''
  4172. @State trackStr: string = ''
  4173. @State genreStr: string = ''
  4174. @State imagePathStr: string = ''
  4175. @State albumArtistStr: string = ''
  4176. @State composerStr: string = ''
  4177. @State lyricistStr: string = ''
  4178. @State commentStr: string = ''
  4179. @State discStr: string = ''
  4180. doUpdateData() {
  4181. setTimeout(() => {
  4182. if (this.modeType === 0) {
  4183. this.deleteCache(this.currentPath)
  4184. this.getSortedFiles(this.currentPath)
  4185. }
  4186. workerInstance.postMessage({ code: 2, data: this.context });
  4187. workerInstance.postMessage({ code: 3, data: this.context });
  4188. workerInstance.postMessage({ code: 4, data: this.context });
  4189. }, 999)
  4190. }
  4191. //编辑信息
  4192. async doEdit(item: VideoItem) {
  4193. if (!item) {
  4194. return
  4195. }
  4196. if (StrUtil.isEmpty(this.titleStr)) {
  4197. ToastUtil.showToast('标题不能为空')
  4198. return
  4199. }
  4200. // let doChangeLyric = false
  4201. // if(item.filePath==this.currentSong?.filePath){
  4202. // if(this.lyricConStr !== this.lyricContent){
  4203. // doChangeLyric = true
  4204. // }
  4205. // }else if(this.lyricConStr !== this.tempLyricContent){
  4206. // doChangeLyric = true
  4207. // }
  4208. //用户更改了封面,那就内嵌下封面
  4209. if(StrUtil.isNotEmpty(this.imagePathStr)){
  4210. const resultCover:boolean = await changeMusicCover(this.context,
  4211. item.filePath,this.imagePathStr,true);
  4212. this.imagePathStr = ''
  4213. if(resultCover){
  4214. ToastUtil.showToast('内嵌封面成功')
  4215. }
  4216. }
  4217. const metadata:FFMpegTags = {
  4218. title: this.titleStr,
  4219. artist: this.artistStr,
  4220. album: this.ablumStr,
  4221. // LYRICS:this.lyricConStr,
  4222. // USLT:this.lyricConStr,
  4223. TYER:this.yearStr,
  4224. genre:this.genreStr,
  4225. track:this.trackStr,
  4226. albumartist:this.albumArtistStr,
  4227. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  4228. COMPOSER:this.composerStr,
  4229. lyricist:this.lyricistStr,
  4230. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  4231. comment:this.commentStr,
  4232. // comm:this.commentStr,//ID3v2:使用 COMM(Comment)字段。
  4233. disc:this.discStr,
  4234. };
  4235. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  4236. const result:boolean = await repairAudioMetadata(
  4237. item.filePath,
  4238. this.lyricConStr,
  4239. metadata,
  4240. true
  4241. );
  4242. if (result) {
  4243. this.table.updateMediaInfo(item.filePath, this.titleStr, this.artistStr, this.ablumStr,this.lyricConStr,
  4244. this.yearStr,this.genreStr,this.trackStr,this.albumArtistStr,this.composerStr, this.lyricistStr,this.commentStr,this.discStr,
  4245. (success: boolean, error?: string) => {
  4246. // this.isShowEdit = false
  4247. if(this.isGridMusic){
  4248. this.longItemFilePath =''
  4249. }else{
  4250. this.isShowEdit = false
  4251. }
  4252. if (success) {
  4253. console.log(" onecold 编辑信息成功,数据库已同步");
  4254. ToastUtil.showToast('内嵌音乐标签成功')
  4255. this.isShowMoreView = false
  4256. this.name = this.titleStr
  4257. if (item.filePath == this.currentSong?.filePath) {
  4258. this.currentSong.name = this.titleStr
  4259. this.artist = this.artistStr
  4260. this.currentSong.artist = this.artistStr
  4261. this.currentSong.album = this.ablumStr
  4262. this.currentSong.year = this.yearStr
  4263. this.currentSong.genre = this.genreStr
  4264. this.currentSong.track = this.trackStr
  4265. this.currentSong.ALBUMARTIST = this.albumArtistStr
  4266. this.currentSong.COMPOSER = this.composerStr
  4267. this.currentSong.LYRICIST = this.lyricistStr
  4268. this.currentSong.COMMENT = this.commentStr
  4269. }
  4270. this.doUpdateData()
  4271. } else {
  4272. // ToastUtil.showToast('保存失败' + error?.toString())
  4273. console.error(" onecold 编辑信息数据库失败原因: " + error);
  4274. }
  4275. });
  4276. console.log(' onecold 元数据标签更新成功,');
  4277. } else {
  4278. ToastUtil.showToast('内嵌音乐标签失败')
  4279. console.log('onecold 内嵌音乐标签失败');
  4280. }
  4281. }
  4282. updateLyricToDB() {
  4283. }
  4284. @Builder
  4285. editSheet(item: VideoItem) {
  4286. Scroll() {
  4287. Column() {
  4288. this.editDetail(item)
  4289. }
  4290. }
  4291. .width('100%')
  4292. .height('100%')
  4293. }
  4294. @Builder
  4295. editDetail(item: VideoItem) {
  4296. Column() {
  4297. if (item) {
  4298. Row() {
  4299. Stack() {
  4300. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  4301. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  4302. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') :
  4303. item.pixelMapPath)
  4304. .fillColor(this.themeColor)
  4305. .height(55)
  4306. .width(55)
  4307. .borderRadius('100%')
  4308. .clip(true)
  4309. .opacity(this.opacityItem)// 绑定透明度
  4310. .margin({ left: 25 })
  4311. }
  4312. .onClick(async () => {
  4313. const imagePath:string | undefined = await this.goSelectImage(item);
  4314. if (imagePath) {
  4315. //用户更改过图片
  4316. this.imagePathStr = imagePath
  4317. }
  4318. })
  4319. .width('18%')
  4320. Row() {
  4321. Column() {
  4322. Text(item.name)
  4323. .fontSize(14)
  4324. .maxLines(1)
  4325. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4326. .animation({
  4327. duration: 555,
  4328. curve: 'Linear',
  4329. })
  4330. .fontColor(this.themeColor)
  4331. .margin({ left: 18 })
  4332. Row() {
  4333. Text(item.artist)
  4334. .fontSize(11)
  4335. .maxLines(1)
  4336. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4337. .padding({ top: 8 })
  4338. .fontColor(this.themeColor)
  4339. .margin({ left: 18 })
  4340. }
  4341. }
  4342. .height('100%')
  4343. .width(100)
  4344. .visibility(this.isDarkMode ? Visibility.None : Visibility.Visible)
  4345. .justifyContent(FlexAlign.Center)
  4346. .alignItems(HorizontalAlign.Start)
  4347. Button('获取封面')
  4348. .fontColor(Color.White)
  4349. .fontSize(12)
  4350. .height(38)
  4351. .width(88)
  4352. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4353. .backgroundColor(this.themeColor)
  4354. .stateEffect(true)
  4355. .margin({ right: 5, left: 12 })
  4356. .onClick(async () => {
  4357. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  4358. this.isShowMoreView = false;
  4359. this.showTipsDialog();
  4360. return; // Return empty string when no API is configured
  4361. }
  4362. const imagePath:string | undefined = await this.doSearchCover(item);
  4363. console.info('onecold imagePath = '+imagePath)
  4364. if (StrUtil.isNotEmpty(imagePath)) {
  4365. //用户更改过图片
  4366. this.imagePathStr = imagePath
  4367. ToastUtil.showToast('获取封面成功')
  4368. }else{
  4369. ToastUtil.showToast('获取封面失败,请重试')
  4370. }
  4371. })
  4372. Button('获取歌词')
  4373. .fontColor(Color.White)
  4374. .fontSize(12)
  4375. .height(38)
  4376. .width(88)
  4377. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4378. .backgroundColor(this.themeColor)
  4379. .stateEffect(true)
  4380. .margin({ right: 12, left: 5 })
  4381. .onClick(async () => {
  4382. //判断有没有设置api
  4383. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  4384. if (StrUtil.isEmpty(apiUrl)) {
  4385. this.isLyricSetting = false
  4386. this.showTipsDialog()
  4387. return
  4388. }
  4389. let artist = item.artist
  4390. let title = item.name
  4391. if(!artist)
  4392. artist = ''
  4393. if(!title)
  4394. title = ''
  4395. let res: string | undefined = await getApiLyric(apiUrl,title, artist, false);
  4396. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  4397. this.lyricConStr = res;
  4398. ToastUtil.showToast('获取歌词成功')
  4399. }else{
  4400. ToastUtil.showToast('获取歌词失败,请重试')
  4401. }
  4402. // let res : string | undefined = await getApiLyric(title, artist, false);
  4403. })
  4404. }
  4405. .height('100%')
  4406. .justifyContent(FlexAlign.Start)
  4407. .layoutWeight(1)
  4408. }
  4409. .width('100%')
  4410. .height(58)
  4411. Row() {
  4412. Text('标题:')
  4413. .fontSize(14)
  4414. .fontColor($r('app.color.text_color'))
  4415. .margin({ left: 22 })
  4416. TextInput({ text: item.name })
  4417. .height(40)
  4418. .maxLines(1)
  4419. .fontSize(14)
  4420. .layoutWeight(1)
  4421. .fontColor($r('app.color.text_color'))
  4422. .margin({ right: 20, left: 10 })
  4423. .onChange((val: string) => {
  4424. this.titleStr = val
  4425. })
  4426. }
  4427. .width('100%')
  4428. .margin({ top: 10, bottom: 10 })
  4429. .justifyContent(FlexAlign.Start)
  4430. Row() {
  4431. Text('艺术家:')
  4432. .fontSize(14)
  4433. .fontColor($r('app.color.text_color'))
  4434. .margin({ left: 22 })
  4435. TextInput({ text: item.artist })
  4436. .height(40)
  4437. .maxLines(1)
  4438. .fontSize(14)
  4439. .layoutWeight(1)
  4440. .fontColor($r('app.color.text_color'))
  4441. .margin({ right: 20, left: 10 })
  4442. .onChange((val: string) => {
  4443. this.artistStr = val
  4444. })
  4445. }
  4446. .width('100%')
  4447. .margin({ top: 10, bottom: 10 })
  4448. .justifyContent(FlexAlign.Start)
  4449. Row() {
  4450. Text('专辑名:')
  4451. .fontSize(14)
  4452. .fontColor($r('app.color.text_color'))
  4453. .margin({ left: 22 })
  4454. TextInput({ text: item.album })
  4455. .height(40)
  4456. .maxLines(1)
  4457. .fontSize(14)
  4458. .layoutWeight(1)
  4459. .fontColor($r('app.color.text_color'))
  4460. .margin({ right: 20, left: 10 })
  4461. .onChange((val: string) => {
  4462. this.ablumStr = val
  4463. })
  4464. }
  4465. .width('100%')
  4466. .margin({ top: 10, bottom: 10 })
  4467. .justifyContent(FlexAlign.Start)
  4468. Row() {
  4469. Text('年份:')
  4470. .fontSize(14)
  4471. .fontColor($r('app.color.text_color'))
  4472. .margin({ left: 22 })
  4473. TextInput({ text: item.year })
  4474. .height(40)
  4475. .maxLines(1)
  4476. .fontSize(14)
  4477. .type(InputType.Number)
  4478. .layoutWeight(1)
  4479. .fontColor($r('app.color.text_color'))
  4480. .margin({ right: 20, left: 10 })
  4481. .onChange((val: string) => {
  4482. this.yearStr = val
  4483. })
  4484. }
  4485. .width('100%')
  4486. .margin({ top: 10, bottom: 10 })
  4487. .justifyContent(FlexAlign.Start)
  4488. Row() {
  4489. Text('音轨号:')
  4490. .fontSize(14)
  4491. .fontColor($r('app.color.text_color'))
  4492. .margin({ left: 22 })
  4493. TextInput({ text:item.track=='未知'?'': item.track })
  4494. .height(40)
  4495. .maxLines(1)
  4496. .fontSize(14)
  4497. .type(InputType.Number)
  4498. .layoutWeight(1)
  4499. .fontColor($r('app.color.text_color'))
  4500. .margin({ right: 20, left: 10 })
  4501. .onChange((val: string) => {
  4502. this.trackStr = val
  4503. })
  4504. }
  4505. .width('100%')
  4506. .margin({ top: 10, bottom: 10 })
  4507. .justifyContent(FlexAlign.Start)
  4508. Row() {
  4509. Text('碟号:')
  4510. .fontSize(14)
  4511. .fontColor($r('app.color.text_color'))
  4512. .margin({ left: 22 })
  4513. TextInput({ text:item.disc })
  4514. .height(40)
  4515. .maxLines(1)
  4516. .fontSize(14)
  4517. .type(InputType.Number)
  4518. .layoutWeight(1)
  4519. .fontColor($r('app.color.text_color'))
  4520. .margin({ right: 20, left: 10 })
  4521. .onChange((val: string) => {
  4522. this.discStr = val
  4523. })
  4524. }
  4525. .width('100%')
  4526. .margin({ top: 10, bottom: 10 })
  4527. .justifyContent(FlexAlign.Start)
  4528. Row() {
  4529. Text('风格:')
  4530. .fontSize(14)
  4531. .fontColor($r('app.color.text_color'))
  4532. .margin({ left: 22 })
  4533. TextInput({ text: item.genre })
  4534. .height(40)
  4535. .maxLines(1)
  4536. .fontSize(14)
  4537. .layoutWeight(1)
  4538. .fontColor($r('app.color.text_color'))
  4539. .margin({ right: 20, left: 10 })
  4540. .onChange((val: string) => {
  4541. this.genreStr = val
  4542. })
  4543. }
  4544. .width('100%')
  4545. .margin({ top: 10, bottom: 10 })
  4546. .justifyContent(FlexAlign.Start)
  4547. Row() {
  4548. Text('专辑艺术家:')
  4549. .fontSize(14)
  4550. .fontColor($r('app.color.text_color'))
  4551. .margin({ left: 22 })
  4552. TextInput({ text: item.ALBUMARTIST })
  4553. .height(40)
  4554. .maxLines(1)
  4555. .fontSize(14)
  4556. .layoutWeight(1)
  4557. .fontColor($r('app.color.text_color'))
  4558. .margin({ right: 20, left: 10 })
  4559. .onChange((val: string) => {
  4560. this.albumArtistStr = val
  4561. })
  4562. }
  4563. .width('100%')
  4564. .margin({ top: 10, bottom: 10 })
  4565. .justifyContent(FlexAlign.Start)
  4566. Row() {
  4567. Text('作曲:')
  4568. .fontSize(14)
  4569. .fontColor($r('app.color.text_color'))
  4570. .margin({ left: 22 })
  4571. TextInput({ text: item.COMPOSER })
  4572. .height(40)
  4573. .maxLines(1)
  4574. .fontSize(14)
  4575. .layoutWeight(1)
  4576. .fontColor($r('app.color.text_color'))
  4577. .margin({ right: 20, left: 10 })
  4578. .onChange((val: string) => {
  4579. this.composerStr = val
  4580. })
  4581. }
  4582. .width('100%')
  4583. .margin({ top: 10, bottom: 10 })
  4584. .justifyContent(FlexAlign.Start)
  4585. Row() {
  4586. Text('作词:')
  4587. .fontSize(14)
  4588. .fontColor($r('app.color.text_color'))
  4589. .margin({ left: 22 })
  4590. TextInput({ text: item.LYRICIST })
  4591. .height(40)
  4592. .maxLines(1)
  4593. .fontSize(14)
  4594. .layoutWeight(1)
  4595. .fontColor($r('app.color.text_color'))
  4596. .margin({ right: 20, left: 10 })
  4597. .onChange((val: string) => {
  4598. this.lyricistStr = val
  4599. })
  4600. }
  4601. .width('100%')
  4602. .margin({ top: 10, bottom: 10 })
  4603. .justifyContent(FlexAlign.Start)
  4604. Row() {
  4605. Text('注释:')
  4606. .fontSize(14)
  4607. .fontColor($r('app.color.text_color'))
  4608. .margin({ left: 22 })
  4609. TextInput({ text: item.COMMENT })
  4610. .height(40)
  4611. .maxLines(1)
  4612. .fontSize(14)
  4613. .layoutWeight(1)
  4614. .fontColor($r('app.color.text_color'))
  4615. .margin({ right: 20, left: 10 })
  4616. .onChange((val: string) => {
  4617. this.commentStr = val
  4618. })
  4619. }
  4620. .width('100%')
  4621. .margin({ top: 10, bottom: 10 })
  4622. .justifyContent(FlexAlign.Start)
  4623. Row() {
  4624. Column(){
  4625. Text('歌词:')
  4626. .fontSize(14)
  4627. .fontColor($r('app.color.text_color'))
  4628. .margin({ left: 22 })
  4629. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  4630. SymbolGlyph($r('sys.symbol.trash_fill'))
  4631. .fontSize(25)
  4632. .alignSelf(ItemAlign.Center)
  4633. .margin({ left: 22,top:15})
  4634. }
  4635. .backgroundColor(Color.Transparent)
  4636. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  4637. Visibility.None:Visibility.Visible)
  4638. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4639. .onClick(()=>{
  4640. this.lyricConStr = ''
  4641. this.lyricContent = ''
  4642. this.tempLyricContent = ''
  4643. })
  4644. }
  4645. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  4646. this.tempLyricContent })
  4647. .type(TextAreaType.NORMAL)
  4648. .height('auto')
  4649. .fontSize(14)
  4650. .layoutWeight(1)
  4651. .fontColor($r('app.color.text_color'))
  4652. .margin({ right: 20, left: 10 })
  4653. .onChange((val: string) => {
  4654. this.lyricConStr = val
  4655. })
  4656. }
  4657. .width('100%')
  4658. .margin({ top: 10, bottom: 10 })
  4659. .justifyContent(FlexAlign.Start)
  4660. Row() {
  4661. Button('保存')
  4662. .fontColor(Color.White)
  4663. .layoutWeight(1)
  4664. .height(50)
  4665. .width(100)
  4666. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4667. .backgroundColor(this.themeColor)
  4668. .stateEffect(true)
  4669. .margin({ right: 20, bottom: 20 })
  4670. .onClick(async () => {
  4671. this.doEdit(item)
  4672. })
  4673. Button('取消')
  4674. .fontColor(Color.White)
  4675. .layoutWeight(1)
  4676. .height(50)
  4677. .width(100)
  4678. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4679. .backgroundColor(this.themeColor)
  4680. .stateEffect(true)
  4681. .margin({ left: 20, bottom: 20 })
  4682. .onClick(async () => {
  4683. if(this.isGridMusic){
  4684. this.longItemFilePath =''
  4685. }else{
  4686. this.isShowEdit = false
  4687. }
  4688. this.setEditStrEmpty()
  4689. if(this.isShowPlay){
  4690. this.isShowEdit = false
  4691. }
  4692. })
  4693. }
  4694. .margin({
  4695. left: 38,
  4696. right: 38,
  4697. top: 10,
  4698. bottom: 10
  4699. })
  4700. .width(250)
  4701. .height(60)
  4702. }
  4703. }
  4704. .margin({ bottom: 20 })
  4705. }
  4706. setEditStrEmpty(){
  4707. this.imagePathStr = ''
  4708. this.lyricConStr = ''
  4709. this.artistStr = ''
  4710. this.titleStr = ''
  4711. this.ablumStr = ''
  4712. this.genreStr = ''
  4713. this.yearStr = ''
  4714. this.trackStr = ''
  4715. this.albumArtistStr = ''
  4716. this.composerStr = ''
  4717. this.lyricistStr = ''
  4718. this.commentStr = ''
  4719. this.discStr = ''
  4720. }
  4721. @Builder
  4722. detailSheet(item:VideoItem) {
  4723. Scroll() {
  4724. Column() {
  4725. this.songDetail(item)
  4726. }
  4727. }
  4728. .width('100%')
  4729. .height('100%')
  4730. }
  4731. @Builder
  4732. songDetail(currentItem:VideoItem) {
  4733. Column() {
  4734. if (currentItem) {
  4735. Row() {
  4736. Stack() {
  4737. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.music_red') :
  4738. currentItem.pixelMapPath)
  4739. .fillColor(this.themeColor)
  4740. .height(80)
  4741. .width(80)
  4742. .borderRadius(10)
  4743. .opacity(this.opacityItem)// 绑定透明度
  4744. .margin({ left: 22 })
  4745. }
  4746. Column() {
  4747. Column() {
  4748. Text(currentItem.name)
  4749. .fontSize(16)
  4750. .maxLines(1)
  4751. .animation({
  4752. duration: 555,
  4753. curve: 'Linear',
  4754. })
  4755. .fontColor($r('app.color.text_color'))
  4756. .margin({ left: 15 })
  4757. }
  4758. .height('100%')
  4759. .width('100%')
  4760. .justifyContent(FlexAlign.Center)
  4761. .alignItems(HorizontalAlign.Start)
  4762. }
  4763. .height('100%')
  4764. }
  4765. .width('100%')
  4766. .height(90)
  4767. .justifyContent(FlexAlign.SpaceBetween)
  4768. Row() {
  4769. Text('艺术家:')
  4770. .fontSize(14)
  4771. .fontColor($r('app.color.text_color'))
  4772. .margin({ left: 22 })
  4773. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  4774. .fontSize(14)
  4775. .fontColor($r('app.color.text_color'))
  4776. .margin({ left: 10 })
  4777. .layoutWeight(1)
  4778. }
  4779. .width('100%')
  4780. .margin({ top: 10, bottom: 10 })
  4781. .justifyContent(FlexAlign.Start)
  4782. Row() {
  4783. Text('专辑名:')
  4784. .fontSize(14)
  4785. .fontColor($r('app.color.text_color'))
  4786. .margin({ left: 22 })
  4787. Text(currentItem?.album ?currentItem.album : '未知专辑')
  4788. .fontSize(14)
  4789. .margin({ left: 10 })
  4790. .fontColor($r('app.color.text_color'))
  4791. .layoutWeight(1)
  4792. }
  4793. .width('100%')
  4794. .margin({ top: 10, bottom: 10 })
  4795. .justifyContent(FlexAlign.Start)
  4796. Row() {
  4797. Text('时长:')
  4798. .fontSize(14)
  4799. .fontColor($r('app.color.text_color'))
  4800. .margin({ left: 22 })
  4801. Text(StrUtil.isEmpty(currentItem.duration)?
  4802. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  4803. .fontSize(14)
  4804. .margin({ left: 10 })
  4805. .fontColor($r('app.color.text_color'))
  4806. .layoutWeight(1)
  4807. }
  4808. .width('100%')
  4809. .margin({ top: 10, bottom: 10 })
  4810. .justifyContent(FlexAlign.Start)
  4811. Row() {
  4812. Text('采样率:')
  4813. .fontSize(14)
  4814. .fontColor($r('app.color.text_color'))
  4815. .margin({ left: 22 })
  4816. Text(Utility.convertToKHz(currentItem.sampleRate))
  4817. .fontSize(14)
  4818. .margin({ left: 10 })
  4819. .fontColor($r('app.color.text_color'))
  4820. .layoutWeight(1)
  4821. }
  4822. .width('100%')
  4823. .margin({ top: 10, bottom: 10 })
  4824. .justifyContent(FlexAlign.Start)
  4825. Row() {
  4826. Text('比特率:')
  4827. .fontSize(14)
  4828. .fontColor($r('app.color.text_color'))
  4829. .margin({ left: 22 })
  4830. Text(currentItem.bit_rate)
  4831. .fontSize(14)
  4832. .margin({ left: 10 })
  4833. .fontColor($r('app.color.text_color'))
  4834. .layoutWeight(1)
  4835. }
  4836. .width('100%')
  4837. .margin({ top: 10, bottom: 10 })
  4838. .justifyContent(FlexAlign.Start)
  4839. Row() {
  4840. Text('位深:')
  4841. .fontSize(14)
  4842. .fontColor($r('app.color.text_color'))
  4843. .margin({ left: 22 })
  4844. Text(`${currentItem.bits_per_raw_sample} bits`)
  4845. .fontSize(14)
  4846. .margin({ left: 10 })
  4847. .fontColor($r('app.color.text_color'))
  4848. .layoutWeight(1)
  4849. }
  4850. .width('100%')
  4851. .margin({ top: 10, bottom: 10 })
  4852. .justifyContent(FlexAlign.Start)
  4853. Row() {
  4854. Text('声道:')
  4855. .fontSize(14)
  4856. .fontColor($r('app.color.text_color'))
  4857. .margin({ left: 22 })
  4858. Text(`${currentItem.channels}`)
  4859. .fontSize(14)
  4860. .margin({ left: 10 })
  4861. .fontColor($r('app.color.text_color'))
  4862. .layoutWeight(1)
  4863. }
  4864. .width('100%')
  4865. .margin({ top: 10, bottom: 10 })
  4866. .justifyContent(FlexAlign.Start)
  4867. Row() {
  4868. Text('声道布局:')
  4869. .fontSize(14)
  4870. .fontColor($r('app.color.text_color'))
  4871. .margin({ left: 22 })
  4872. Text(`${currentItem.channel_layout}`)
  4873. .fontSize(14)
  4874. .margin({ left: 10 })
  4875. .fontColor($r('app.color.text_color'))
  4876. .layoutWeight(1)
  4877. }
  4878. .width('100%')
  4879. .margin({ top: 10, bottom: 10 })
  4880. .justifyContent(FlexAlign.Start)
  4881. Row() {
  4882. Text('起始播放点:')
  4883. .fontSize(14)
  4884. .fontColor($r('app.color.text_color'))
  4885. .margin({ left: 22 })
  4886. Text(`${currentItem.start_time}`)
  4887. .fontSize(14)
  4888. .margin({ left: 10 })
  4889. .fontColor($r('app.color.text_color'))
  4890. .layoutWeight(1)
  4891. }
  4892. .width('100%')
  4893. .margin({ top: 10, bottom: 10 })
  4894. .justifyContent(FlexAlign.Start)
  4895. Row() {
  4896. Text('风格:')
  4897. .fontSize(14)
  4898. .fontColor($r('app.color.text_color'))
  4899. .margin({ left: 22 })
  4900. Text(currentItem.genre)
  4901. .fontSize(14)
  4902. .margin({ left: 10 })
  4903. .fontColor($r('app.color.text_color'))
  4904. .layoutWeight(1)
  4905. }
  4906. .width('100%')
  4907. .margin({ top: 10, bottom: 10 })
  4908. .justifyContent(FlexAlign.Start)
  4909. Row() {
  4910. Text('发行时间:')
  4911. .fontSize(14)
  4912. .fontColor($r('app.color.text_color'))
  4913. .margin({ left: 22 })
  4914. Text(currentItem.year)
  4915. .fontSize(14)
  4916. .margin({ left: 10 })
  4917. .fontColor($r('app.color.text_color'))
  4918. .layoutWeight(1)
  4919. }
  4920. .width('100%')
  4921. .margin({ top: 10, bottom: 10 })
  4922. .justifyContent(FlexAlign.Start)
  4923. Row() {
  4924. Text('质量评分:')
  4925. .fontSize(14)
  4926. .fontColor($r('app.color.text_color'))
  4927. .margin({ left: 22 })
  4928. Text(currentItem.probe_score+"")
  4929. .fontSize(14)
  4930. .margin({ left: 10 })
  4931. .fontColor($r('app.color.text_color'))
  4932. .layoutWeight(1)
  4933. }
  4934. .width('100%')
  4935. .margin({ top: 10, bottom: 10 })
  4936. .justifyContent(FlexAlign.Start)
  4937. Row() {
  4938. Text('音轨号:')
  4939. .fontSize(14)
  4940. .fontColor($r('app.color.text_color'))
  4941. .margin({ left: 22 })
  4942. Text(currentItem.track)
  4943. .fontSize(14)
  4944. .margin({ left: 10 })
  4945. .fontColor($r('app.color.text_color'))
  4946. .layoutWeight(1)
  4947. }
  4948. .width('100%')
  4949. .margin({ top: 10, bottom: 10 })
  4950. .justifyContent(FlexAlign.Start)
  4951. Row() {
  4952. Text('碟号:')
  4953. .fontSize(14)
  4954. .fontColor($r('app.color.text_color'))
  4955. .margin({ left: 22 })
  4956. Text(currentItem.disc)
  4957. .fontSize(14)
  4958. .margin({ left: 10 })
  4959. .fontColor($r('app.color.text_color'))
  4960. .layoutWeight(1)
  4961. }
  4962. .width('100%')
  4963. .margin({ top: 10, bottom: 10 })
  4964. .justifyContent(FlexAlign.Start)
  4965. Row() {
  4966. Text('专辑艺术家:')
  4967. .fontSize(14)
  4968. .fontColor($r('app.color.text_color'))
  4969. .margin({ left: 22 })
  4970. Text(currentItem.ALBUMARTIST)
  4971. .fontSize(14)
  4972. .margin({ left: 10 })
  4973. .fontColor($r('app.color.text_color'))
  4974. .layoutWeight(1)
  4975. }
  4976. .width('100%')
  4977. .margin({ top: 10, bottom: 10 })
  4978. .justifyContent(FlexAlign.Start)
  4979. Row() {
  4980. Text('作曲家:')
  4981. .fontSize(14)
  4982. .fontColor($r('app.color.text_color'))
  4983. .margin({ left: 22 })
  4984. Text(currentItem.COMPOSER)
  4985. .fontSize(14)
  4986. .margin({ left: 10 })
  4987. .fontColor($r('app.color.text_color'))
  4988. .layoutWeight(1)
  4989. }
  4990. .width('100%')
  4991. .margin({ top: 10, bottom: 10 })
  4992. .justifyContent(FlexAlign.Start)
  4993. Row() {
  4994. Text('作词家:')
  4995. .fontSize(14)
  4996. .fontColor($r('app.color.text_color'))
  4997. .margin({ left: 22 })
  4998. Text(currentItem.LYRICIST)
  4999. .fontSize(14)
  5000. .margin({ left: 10 })
  5001. .fontColor($r('app.color.text_color'))
  5002. .layoutWeight(1)
  5003. }
  5004. .width('100%')
  5005. .margin({ top: 10, bottom: 10 })
  5006. .justifyContent(FlexAlign.Start)
  5007. Row() {
  5008. Text('注释:')
  5009. .fontSize(14)
  5010. .fontColor($r('app.color.text_color'))
  5011. .margin({ left: 22 })
  5012. Text(currentItem.COMMENT)
  5013. .fontSize(14)
  5014. .margin({ left: 10 })
  5015. .fontColor($r('app.color.text_color'))
  5016. .layoutWeight(1)
  5017. }
  5018. .width('100%')
  5019. .margin({ top: 10, bottom: 10 })
  5020. .justifyContent(FlexAlign.Start)
  5021. Row() {
  5022. Text('格式:')
  5023. .fontSize(14)
  5024. .fontColor($r('app.color.text_color'))
  5025. .margin({ left: 22 })
  5026. Text(Utility.formatMimeType(currentItem.mimeType))
  5027. .fontSize(14)
  5028. .margin({ left: 10 })
  5029. .fontColor($r('app.color.text_color'))
  5030. .layoutWeight(1)
  5031. }
  5032. .width('100%')
  5033. .margin({ top: 10, bottom: 10 })
  5034. .justifyContent(FlexAlign.Start)
  5035. Row() {
  5036. Text('播放次数:')
  5037. .fontSize(14)
  5038. .fontColor($r('app.color.text_color'))
  5039. .margin({ left: 22 })
  5040. Text(currentItem.playCount?.toString())
  5041. .fontSize(14)
  5042. .margin({ left: 10 })
  5043. .fontColor($r('app.color.text_color'))
  5044. .layoutWeight(1)
  5045. }
  5046. .width('100%')
  5047. .margin({ top: 10, bottom: 10 })
  5048. .justifyContent(FlexAlign.Start)
  5049. Row() {
  5050. Text('流数量:')
  5051. .fontSize(14)
  5052. .fontColor($r('app.color.text_color'))
  5053. .margin({ left: 22 })
  5054. Text(currentItem.nb_streams?.toString())
  5055. .fontSize(14)
  5056. .margin({ left: 10 })
  5057. .fontColor($r('app.color.text_color'))
  5058. .layoutWeight(1)
  5059. }
  5060. .width('100%')
  5061. .margin({ top: 10, bottom: 10 })
  5062. .justifyContent(FlexAlign.Start)
  5063. Row() {
  5064. Text('文件大小:')
  5065. .fontSize(14)
  5066. .fontColor($r('app.color.text_color'))
  5067. .margin({ left: 22 })
  5068. Text(currentItem.size)
  5069. .fontSize(14)
  5070. .margin({ left: 10 })
  5071. .fontColor($r('app.color.text_color'))
  5072. .layoutWeight(1)
  5073. }
  5074. .width('100%')
  5075. .margin({ top: 10, bottom: 10 })
  5076. .justifyContent(FlexAlign.Start)
  5077. Row() {
  5078. Text('文件名:')
  5079. .fontSize(14)
  5080. .fontColor($r('app.color.text_color'))
  5081. .margin({ left: 22 })
  5082. Text(currentItem.fileName)
  5083. .fontSize(14)
  5084. .margin({ left: 10 })
  5085. .fontColor($r('app.color.text_color'))
  5086. .layoutWeight(1)
  5087. }
  5088. .width('100%')
  5089. .margin({ top: 10, bottom: 10 })
  5090. .justifyContent(FlexAlign.Start)
  5091. Row() {
  5092. Text('修改时间:')
  5093. .fontSize(14)
  5094. .fontColor($r('app.color.text_color'))
  5095. .margin({ left: 22 })
  5096. Text(currentItem.cTime)
  5097. .fontSize(14)
  5098. .margin({ left: 10 })
  5099. .fontColor($r('app.color.text_color'))
  5100. .layoutWeight(1)
  5101. }
  5102. .width('100%')
  5103. .margin({ top: 10, bottom: 10 })
  5104. .justifyContent(FlexAlign.Start)
  5105. Row() {
  5106. Text('存放目录:')
  5107. .fontSize(14)
  5108. .fontColor($r('app.color.text_color'))
  5109. .margin({ left: 22 })
  5110. Text(currentItem.filePath)
  5111. .fontSize(12)
  5112. .margin({ left: 10 })
  5113. .fontColor($r('app.color.text_color'))
  5114. .layoutWeight(1)
  5115. }
  5116. .margin({ top: 10, bottom: 10 })
  5117. .width('100%')
  5118. .justifyContent(FlexAlign.Start)
  5119. }
  5120. }
  5121. .margin({ bottom: 20 })
  5122. }
  5123. //定时关闭布局
  5124. @Builder
  5125. TimeCloseSheet() {
  5126. Scroll() {
  5127. Column() {
  5128. this.TimeClose()
  5129. }
  5130. }
  5131. .width('100%')
  5132. .height('100%')
  5133. }
  5134. //倒计时关闭音乐,退出App功能实现。
  5135. @State selectedMinutes: number = 0 // 0表示未开启
  5136. @State remainingSeconds: number = 0
  5137. // 预设时间选项
  5138. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  5139. private formatTime(seconds: number): string {
  5140. const mins = Math.floor(seconds / 60)
  5141. const secs = seconds % 60
  5142. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  5143. }
  5144. // 开始倒计时
  5145. private handleTimeSelect(minutes: number) {
  5146. if (minutes === this.selectedMinutes) {
  5147. this.stopCountdown();
  5148. this.selectedMinutes = 0;
  5149. return;
  5150. }
  5151. this.selectedMinutes = minutes;
  5152. this.remainingSeconds = minutes * 60;
  5153. this.startCountdown(); // 新增调用
  5154. }
  5155. @Builder
  5156. TimeClose() {
  5157. Column() {
  5158. // 倒计时显示区域
  5159. Text(this.selectedMinutes > 0 ?
  5160. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  5161. "定时关闭未开启")
  5162. .fontSize(17)
  5163. .fontColor($r('app.color.text_color'))
  5164. .margin({ top: 2, bottom: 8 });
  5165. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  5166. ForEach(this.presetTimes, (minutes: number, index: number) => {
  5167. // 单行时间选项容器
  5168. Row() {
  5169. // 文字描述区域
  5170. Text(this.getDisplayText(minutes))
  5171. .fontSize(15)
  5172. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  5173. $r('app.color.text_color'))// 选中态颜色变化
  5174. .textAlign(TextAlign.Start)
  5175. .layoutWeight(1); // 占据剩余空间
  5176. // 复选框样式的选择器
  5177. Row() {
  5178. if (minutes === this.selectedMinutes) {
  5179. // 选中状态 - 带勾号的圆形复选框
  5180. Row() {
  5181. // 使用系统内置的勾号图标
  5182. Image($r('sys.media.ohos_ic_public_ok'))
  5183. .width(14)
  5184. .height(14)
  5185. .fillColor(Color.White)
  5186. }
  5187. .width(24)
  5188. .height(24)
  5189. .borderRadius(12)
  5190. .backgroundColor(this.themeColor)
  5191. .justifyContent(FlexAlign.Center)
  5192. .alignItems(VerticalAlign.Center)
  5193. } else {
  5194. // 未选中状态的圆形边框
  5195. Row()
  5196. .width(24)
  5197. .height(24)
  5198. .borderRadius(12)
  5199. .border({
  5200. width: 2,
  5201. color: $r('app.color.text_color'),
  5202. style: BorderStyle.Solid
  5203. })
  5204. .backgroundColor(Color.Transparent)
  5205. }
  5206. }
  5207. .width(24)
  5208. .height(24)
  5209. .margin({ left: 20 })
  5210. .justifyContent(FlexAlign.Center)
  5211. .alignItems(VerticalAlign.Center)
  5212. }
  5213. .width('100%')
  5214. .padding({
  5215. top: 18,
  5216. bottom: 18,
  5217. left: 18,
  5218. right: 18
  5219. })
  5220. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  5221. $r('app.color.bottom_control_background')) // 选中背景高亮
  5222. .borderRadius(12)
  5223. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  5224. .margin({ bottom: 18 })
  5225. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  5226. });
  5227. }
  5228. .width('100%')
  5229. .padding(16)
  5230. }
  5231. }
  5232. // 获取显示文本
  5233. private getDisplayText(minutes: number): string {
  5234. if (minutes === -1) {
  5235. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  5236. }
  5237. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  5238. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  5239. }
  5240. // 处理选择事件
  5241. private handleSelect(minutes: number): void {
  5242. if (minutes === -1) { // 自定义
  5243. // 弹出自定义时间对话框
  5244. DialogHelper.showTextInputDialog({
  5245. title: '自定义时间',
  5246. maskColor: Color.Transparent,
  5247. inputType: InputType.Number,
  5248. text: '',
  5249. onChange: (text) => {
  5250. console.error("onChange: " + text);
  5251. },
  5252. onAction: (action, dialogId, content) => {
  5253. if (action == DialogAction.TWO) {
  5254. const customMinutes = Number(content);
  5255. if (customMinutes > 0) {
  5256. this.handleTimeSelect(customMinutes); // 设置自定义时间
  5257. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  5258. }
  5259. }
  5260. }
  5261. });
  5262. } else {
  5263. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  5264. }
  5265. }
  5266. // 添加定时器引用
  5267. private timerId: number = -1;
  5268. // 启动/重置倒计时
  5269. private startCountdown() {
  5270. // 清除旧定时器
  5271. if (this.timerId !== -1) {
  5272. clearInterval(this.timerId);
  5273. }
  5274. // 创建新定时器
  5275. if (this.selectedMinutes > 0) {
  5276. this.timerId = setInterval(() => {
  5277. if (this.remainingSeconds === 15) {
  5278. this.showConfirmationDialog();
  5279. }
  5280. if (this.remainingSeconds > 0) {
  5281. this.remainingSeconds -= 1;
  5282. } else {
  5283. this.stopCountdown();
  5284. this.handleTimeout();
  5285. }
  5286. }, 1000);
  5287. }
  5288. }
  5289. // 15倒计时后再次提示显示确认是否关闭App对话框
  5290. private showConfirmationDialog() {
  5291. DialogHelper.showAlertDialog({
  5292. backgroundColor: $r('app.color.btn_green'),
  5293. title: '确认关闭',
  5294. maskColor: Color.Transparent,
  5295. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  5296. borderStyle: BorderStyle.Dashed,
  5297. primaryButton: '暂不关闭',
  5298. secondaryButton: '确定',
  5299. onAction: (action) => {
  5300. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  5301. this.stopCountdown();
  5302. this.selectedMinutes = 0
  5303. } else if (action == DialogAction.TWO) {
  5304. }
  5305. }
  5306. })
  5307. }
  5308. // 停止倒计时
  5309. private stopCountdown() {
  5310. if (this.timerId !== -1) {
  5311. clearInterval(this.timerId);
  5312. this.timerId = -1;
  5313. }
  5314. }
  5315. // 超时处理
  5316. private handleTimeout() {
  5317. // 执行播放器关闭逻辑
  5318. this.selectedMinutes = 0;
  5319. ToastUtil.showToast(" 定时关闭已完成");
  5320. this.stop(); // 假设存在的播放器实例
  5321. //退出APP
  5322. const mContext = getContext(this) as common.UIAbilityContext
  5323. mContext.terminateSelf();
  5324. AvSessionController.getInstance(true).unregisterSessionListener()
  5325. }
  5326. //倒计时关闭音乐,退出App功能实现结束。
  5327. //播放列表的拖动List 重新排序
  5328. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  5329. //左滑操作 移动文件 重命名 删除等操作
  5330. @Builder
  5331. sonButton(item: VideoItem, index: number, filePath: string) {
  5332. Row() {
  5333. //加入下一首播放
  5334. Button() {
  5335. Image($r('app.media.next_to_play'))
  5336. .fillColor(Color.White)
  5337. .width(20)
  5338. }
  5339. .width(40)
  5340. .height(40)
  5341. .type(ButtonType.Circle)
  5342. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  5343. .backgroundColor(this.themeColor)
  5344. .margin(5)
  5345. .onClick(() => {
  5346. this.addToNextPlay(item);
  5347. })
  5348. Button() {
  5349. Image($r('app.media.close'))
  5350. .fillColor(Color.White)
  5351. .width(20)
  5352. }
  5353. .width(40)
  5354. .height(40)
  5355. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  5356. .type(ButtonType.Circle)
  5357. .backgroundColor(this.themeColor)
  5358. .margin(5)
  5359. .onClick(() => {
  5360. this.songList.splice(Number(index), 1)
  5361. this.sonDataSource.pushArrayData(this.songList)
  5362. })
  5363. Button() {
  5364. Image($r('app.media.share2'))
  5365. .fillColor(Color.White)
  5366. .width(20)
  5367. }
  5368. .width(40)
  5369. .height(40)
  5370. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  5371. .type(ButtonType.Circle)
  5372. .backgroundColor(this.themeColor)
  5373. .margin(5)
  5374. .onClick(() => {
  5375. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  5376. })
  5377. }
  5378. }
  5379. itemMoveSon(index: number, newIndex: number): void {
  5380. if (newIndex < 0 || newIndex >= this.songList.length) {
  5381. return;
  5382. }
  5383. let tmp = this.songList.splice(index, 1);
  5384. this.songList.splice(newIndex, 0, tmp[0]);
  5385. this.sonDataSource.pushArrayData(this.songList)
  5386. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  5387. }
  5388. @Builder
  5389. PlayList() {
  5390. List({ scroller: this.playListScroller }) {
  5391. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  5392. ListItem() {
  5393. this.MusicItemSon(item, index)
  5394. }
  5395. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  5396. .animation({
  5397. duration: 666,
  5398. curve: 'ease-in-out' // 可选动画曲线
  5399. })
  5400. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
  5401. TransitionEffect.scale({ x: 0, y: 0 })))
  5402. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  5403. //拖动List关键代码开始
  5404. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  5405. .zIndex(this.dragItem === index ? 1 : 0)
  5406. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  5407. .gesture(
  5408. GestureGroup(GestureMode.Sequence,
  5409. LongPressGesture({ repeat: true })
  5410. .onAction((event?: GestureEvent) => {
  5411. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5412. this.scaleItem = index
  5413. })
  5414. })
  5415. .onActionEnd(() => {
  5416. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5417. this.scaleItem = -1
  5418. })
  5419. }),
  5420. PanGesture({ fingers: 1, direction: null, distance: 0 })
  5421. .onActionStart(() => {
  5422. this.dragItem = index // 记录当前拖动项索引
  5423. this.dragRefOffset = 0 // 重置偏移基准
  5424. })
  5425. .onActionUpdate((event: GestureEvent) => {
  5426. this.offsetY = event.offsetY - this.dragRefOffset;
  5427. this.neighborItem = -1;
  5428. let indexA = this.songList.indexOf(item);
  5429. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  5430. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  5431. let value: number = 0;
  5432. if (this.offsetY < 0) {
  5433. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  5434. this.neighborItem = indexA - 1;
  5435. this.neighborScale = 1 - value / 20;
  5436. } else if (this.offsetY > 0) {
  5437. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  5438. this.neighborItem = indexA + 1;
  5439. this.neighborScale = 1 - value / 20;
  5440. }
  5441. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  5442. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5443. this.offsetY -= this.ITEM_INTV;
  5444. this.dragRefOffset += this.ITEM_INTV;
  5445. this.itemMoveSon(indexA, indexA + 1);
  5446. });
  5447. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  5448. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5449. this.offsetY += this.ITEM_INTV;
  5450. this.dragRefOffset -= this.ITEM_INTV;
  5451. this.itemMoveSon(indexA, indexA - 1);
  5452. });
  5453. }
  5454. })
  5455. .onActionEnd((event: GestureEvent) => {
  5456. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5457. this.dragItem = -1
  5458. this.neighborItem = -1
  5459. })
  5460. animateTo({
  5461. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5462. }, () => {
  5463. this.scaleItem = -1
  5464. })
  5465. })
  5466. )
  5467. .onCancel(() => {
  5468. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5469. this.dragItem = -1
  5470. this.neighborItem = -1
  5471. })
  5472. animateTo({
  5473. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5474. }, () => {
  5475. this.scaleItem = -1
  5476. })
  5477. })
  5478. ) //拖动List关键代码结束
  5479. .onClick(() => {
  5480. this.doPlay(item, index, true)
  5481. })
  5482. }, (item: VideoItem) => item.filePath)
  5483. }
  5484. .width('100%')
  5485. .height('100%')
  5486. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  5487. // .animation({ duration: 500, curve: Curve.Ease }))
  5488. .cachedCount(10)
  5489. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5490. .gesture(PinchGesture({ fingers: 2 })
  5491. .onActionEnd((event: GestureEvent) => {
  5492. this.setlistTwoFingers()
  5493. })
  5494. .onActionUpdate(e => {
  5495. this.scaleValue = this.pinchValue * e.scale
  5496. })
  5497. .onActionStart(e => {
  5498. }))
  5499. .padding({
  5500. bottom: 0
  5501. })
  5502. }
  5503. @Builder
  5504. private MusicItemSon(item: VideoItem, index?: number) {
  5505. Button({ type: ButtonType.Normal, stateEffect: true }) {
  5506. Row() {
  5507. Stack() {
  5508. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  5509. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  5510. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 35 : 30)
  5511. .alt($r('app.media.music_red'))
  5512. .fillColor(this.themeColor)
  5513. .borderRadius('100%')
  5514. .clip(true)
  5515. .margin({ left: 20 })
  5516. }
  5517. .width('15%')
  5518. Column() {
  5519. Column() {
  5520. Text(item.name)
  5521. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5522. .fontColor(this.curIndex === index ? this.themeColor :
  5523. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  5524. .maxLines(1)
  5525. .margin({ left: this.twoFingerType == 3 ? 18 : 10 })
  5526. Row() {
  5527. Column(){
  5528. Text(item.md5Str?.includes('Lossless')?
  5529. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5530. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  5531. .padding({ top: 3,right:6,left:6,bottom:3 })
  5532. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5533. $r('app.color.text_color'))
  5534. .fontWeight(500)
  5535. .borderRadius(12)
  5536. .margin({ left: this.twoFingerType == 3 ? 12 : 10 })
  5537. .backgroundColor('#FFC107')
  5538. }
  5539. .padding({ top: 8 })
  5540. Text(StrUtil.isEmpty(item.artist) ? item.cTime : item.artist + ' ' + item?.album)
  5541. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5542. .padding({ top: 8 })
  5543. .fontColor(this.curIndex === index ? this.themeColor :
  5544. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  5545. .margin({ left: this.twoFingerType == 3 ? 5 : 3 })
  5546. Blank()
  5547. Text(item.size)
  5548. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5549. .padding({ top: 8 })
  5550. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  5551. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  5552. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  5553. .margin({ left: 10 })
  5554. }
  5555. }
  5556. .height('100%')
  5557. .width('100%')
  5558. .justifyContent(FlexAlign.Center)
  5559. .alignItems(HorizontalAlign.Start)
  5560. }
  5561. .height('100%')
  5562. .width('65%')
  5563. Column() {
  5564. ImageAnimator()
  5565. .images(this.imagesF)// 动画数组
  5566. .duration(1000)// 持续
  5567. .state(this.animationState)// 动画状态
  5568. .fillMode(FillMode.Forwards)
  5569. .width(18)
  5570. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  5571. Visibility.None)
  5572. .height(18)
  5573. .iterations(-1) // 播放次数
  5574. }
  5575. .width('20%')
  5576. }
  5577. }
  5578. .backgroundColor(Color.Transparent)
  5579. .width('100%')
  5580. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  5581. .shadow(this.scaleItem === index ? {
  5582. radius: 70,
  5583. color: '#15000000',
  5584. offsetX: 0,
  5585. offsetY: 0
  5586. } :
  5587. {
  5588. radius: 0,
  5589. color: '#15000000',
  5590. offsetX: 0,
  5591. offsetY: 0
  5592. })
  5593. .animation({ curve: Curve.Sharp, duration: 300 })
  5594. }
  5595. @Builder
  5596. MusicPlayBuilder() {
  5597. Column() {
  5598. this.IjkMusicPlayerView()
  5599. }
  5600. .height('100%')
  5601. .width('100%')
  5602. .onDisAppear(() => {
  5603. this.translateY = 0;
  5604. })
  5605. .translate({ y: this.translateY })
  5606. .gesture(
  5607. PanGesture(this.panOption)
  5608. .onActionUpdate((event?: GestureEvent) => {
  5609. if (event) {
  5610. // 只允许向下滑动,向上滑动时限制为0
  5611. this.translateY = Math.max(0, event.offsetY);
  5612. }
  5613. })
  5614. .onActionEnd((event?: GestureEvent) => {
  5615. // 使用更低的阈值和滑动速度判断
  5616. const minDistance = 100; // 最小滑动距离 100vp
  5617. const minVelocity = 500; // 最小滑动速度
  5618. // 获取滑动速度(如果可用)
  5619. const velocity = event?.velocityY || 0;
  5620. // 判断是否应该关闭:距离足够 或者 速度足够快
  5621. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  5622. if (shouldClose) {
  5623. // 添加关闭动画
  5624. this.getUIContext().animateTo({
  5625. duration: 300,
  5626. curve: Curve.Smooth
  5627. }, () => {
  5628. this.isShowPlay = false;
  5629. this.translateY = 0;
  5630. })
  5631. } else {
  5632. // 回弹动画
  5633. this.getUIContext().animateTo({
  5634. duration: 300,
  5635. curve: Curve.Smooth
  5636. }, () => {
  5637. this.translateY = 0;
  5638. })
  5639. }
  5640. })
  5641. )
  5642. }
  5643. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  5644. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  5645. HeightBreakpoint.HEIGHT_LG;
  5646. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  5647. @State topBarHeight: number = 50
  5648. @State barOpacity: number = 1
  5649. @State barBottomOpacity: number = 1
  5650. private hideDone: boolean = false;
  5651. @State currentYOffset: number = 0;
  5652. @State bottomBarHeight: number = 60;
  5653. private isHiding: boolean = false;
  5654. //是否是Pura X外屏,或者小屏幕
  5655. isPuraWP() {
  5656. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  5657. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  5658. }
  5659. //是否是Pura X外屏,或者小屏幕,手机横屏
  5660. /**
  5661. * 是否是Pura X外屏,或者小屏幕,手机横屏
  5662. * @returns
  5663. */
  5664. isCoverOpacity() {
  5665. if (this.isPuraWP()) {
  5666. return true
  5667. }
  5668. if (this.isPhoneLan()) {
  5669. return true
  5670. }
  5671. if (deviceInfo.marketName.includes('Pura X')
  5672. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  5673. return true
  5674. }
  5675. return false
  5676. }
  5677. //是不是手机横屏
  5678. isPhoneLan() {
  5679. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  5680. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  5681. LogUtil.info('hicar isPhoneLan width= ' + this.windowWidth);
  5682. LogUtil.info('hicar isPhoneLan height= ' + this.windowHeight);
  5683. LogUtil.info(`twocold hicarWindow size: ${this.windowWidth}x${this.windowHeight}, this.isHiCarStatus: ${this.isHiCarStatus}`);
  5684. LogUtil.info(`twocold hicar Window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall: ${this.isHiCarSmall()}`);
  5685. if (this.isHiCarKuanBianPing()) {
  5686. return true
  5687. }
  5688. if (this.isHiCar()) {
  5689. return false
  5690. }
  5691. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  5692. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  5693. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  5694. return true
  5695. }
  5696. return false
  5697. }
  5698. //是不是1920x720的hicar的屏幕分辨率
  5699. isHiCarKuanBianPing(){
  5700. if(!this.isHiCar()){
  5701. return false
  5702. }
  5703. const hiCarAspectRatios: HiCarAspectRatio[] = [
  5704. { ratio: 1920 / 720, name: "1920x720" },
  5705. ];
  5706. const currentRatio: number = this.windowWidth / this.windowHeight;
  5707. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  5708. LogUtil.info('twocold isHiCarKuanBianPing currentRatio = ' + currentRatio)
  5709. for (const hiCarRatio of hiCarAspectRatios) {
  5710. LogUtil.info('twocold isHiCarKuanBianPing hiCarRatio= ' + hiCarRatio.ratio)
  5711. LogUtil.info('twocold isHiCarKuanBianPing Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  5712. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  5713. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  5714. return true;
  5715. }
  5716. }
  5717. return false;
  5718. }
  5719. //是不是hicar的屏幕分辨率
  5720. isHiCarSmall() {
  5721. if(!this.isHiCar()){
  5722. return false
  5723. }
  5724. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  5725. return false
  5726. const hiCarAspectRatios: HiCarAspectRatio[] = [
  5727. { ratio: 800 / 480, name: "800x480" },
  5728. { ratio: 1280 / 720, name: "1280x720" },
  5729. { ratio: 1920 / 1080, name: "1920x1080" },
  5730. ];
  5731. const currentRatio: number = this.windowWidth / this.windowHeight;
  5732. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  5733. LogUtil.info('twocold isHiCarSmall currentRatio = ' + currentRatio)
  5734. for (const hiCarRatio of hiCarAspectRatios) {
  5735. LogUtil.info('twocold isHiCarSmall hiCarRatio= ' + hiCarRatio.ratio)
  5736. LogUtil.info('twocold isHiCarSmall Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  5737. LogUtil.info('twocold isHiCarSmall isHiCarStatus= ' + this.isHiCarStatus);
  5738. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  5739. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  5740. return true;
  5741. }
  5742. }
  5743. return false;
  5744. }
  5745. isHiCar() {
  5746. return this.isHiCarStatus&&this.curDisplayIsHiCar;
  5747. }
  5748. //是不是正常的手机竖屏
  5749. isPhonePortrait() {
  5750. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  5751. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  5752. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  5753. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  5754. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  5755. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  5756. return true
  5757. }
  5758. return false
  5759. }
  5760. @State showSpeedDialog: boolean = false
  5761. @State longPressSpeed: number = 3 //长按默认倍数
  5762. @Builder
  5763. SpeedDialog() {
  5764. Stack() {
  5765. Column() {
  5766. Text('已切换至' + this.longPressSpeed + '倍速播放')
  5767. .fontColor(Color.White)
  5768. .visibility(Visibility.Hidden)
  5769. }
  5770. .backgroundColor(Color.Black)
  5771. .borderRadius(20)
  5772. .padding({
  5773. top: 10,
  5774. right: 20,
  5775. left: 15,
  5776. bottom: 20
  5777. })
  5778. .opacity(0.6)
  5779. Text('已切换至' + this.longPressSpeed + '倍速播放')
  5780. .fontColor(Color.White)
  5781. }
  5782. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  5783. .zIndex(5)
  5784. .margin({ top: 80 })
  5785. }
  5786. @Builder
  5787. IjkMusicPlayerView() {
  5788. Column() {
  5789. Column() {
  5790. Column() {
  5791. //播放标题
  5792. Column() {
  5793. this.PlayTitle()
  5794. }
  5795. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  5796. .width('100%')
  5797. .margin({ top: 0 })
  5798. .height(PlayConstants.HEIGHT)
  5799. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  5800. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  5801. if (this.showSpeedDialog) {
  5802. this.SpeedDialog()
  5803. }
  5804. Stack() {
  5805. //手势拖动快进
  5806. Column()
  5807. .width(CommonConstants.FULL_PERCENT)
  5808. .height('100%')
  5809. .gesture(
  5810. GestureGroup(GestureMode.Parallel,
  5811. // 长按屏幕倍数播放
  5812. LongPressGesture({ repeat: true })
  5813. .onAction(() => {
  5814. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  5815. this.showSpeedDialog = true;
  5816. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  5817. }
  5818. })
  5819. .onActionEnd(() => {
  5820. this.showSpeedDialog = false;
  5821. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  5822. }),
  5823. //双击屏幕暂停或者播放
  5824. TapGesture({ count: 2 })
  5825. .onAction((event: GestureEvent) => {
  5826. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  5827. ToastUtil.showToast('已暂停')
  5828. }
  5829. this.playOrPause()
  5830. })
  5831. )
  5832. )
  5833. }
  5834. .height('65%')
  5835. Swiper() {
  5836. this.CoverInfo()
  5837. this.PlayerLyrics()
  5838. }
  5839. .onChange((index: number) => {
  5840. this.currentSwiperIndex = index
  5841. })
  5842. .indicator(false)
  5843. // .indicator(this.currentBreakpoint === BreakpointTypeEnum.SM ?
  5844. // new DotIndicator()
  5845. // .top(this.isCoverOpacity()?0:10)
  5846. //
  5847. // .selectedColor($r('app.color.select_swiper'))
  5848. // .color($r('app.color.slider_track')):false
  5849. // )
  5850. .displayCount(new BreakpointType({
  5851. sm: 1,
  5852. md: 2,
  5853. lg: 2,
  5854. xl: 2,
  5855. xxl: 2
  5856. }).getValue(this.currentBreakpoint))
  5857. .clip(false)
  5858. .loop(false)
  5859. .autoPlay(false)
  5860. // .interval(8000)
  5861. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  5862. .height('100%')
  5863. .hitTestBehavior(HitTestMode.Transparent)
  5864. Image($r('app.media.icon_replay'))
  5865. .objectFit(ImageFit.Auto)
  5866. .width('120px')
  5867. .height('120px')
  5868. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  5869. .border({ width: 0 })
  5870. .visibility(Visibility.None)
  5871. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  5872. .onClick(() => {
  5873. this.startPlayOrResumePlay();
  5874. })
  5875. }
  5876. .width(CommonConstants.FULL_PERCENT)
  5877. .height(CommonConstants.FULL_PERCENT)
  5878. .justifyContent(FlexAlign.End)
  5879. }
  5880. .justifyContent(FlexAlign.End)
  5881. .margin({ bottom: 8 })
  5882. }
  5883. // .backgroundImage(this.imageLabelBg)
  5884. .backgroundImage(this.isPuraWP() && this.currentSwiperIndex === 0 ?
  5885. (StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover) : this.imageLabelBg)
  5886. .backgroundImageSize(this.isPuraWP() ? { width: '100%' } : { height: '150%', width: '100%' })
  5887. // .backgroundImagePosition(Alignment.Center)
  5888. .animation({
  5889. duration: 666,
  5890. curve: 'ease-in-out' // 可选动画曲线
  5891. })
  5892. .backgroundBlurStyle(this.isPuraWP() && this.currentSwiperIndex === 0 ? BlurStyle.NONE :
  5893. BlurStyle.BACKGROUND_ULTRA_THICK)
  5894. .hitTestBehavior(HitTestMode.Transparent)
  5895. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  5896. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  5897. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  5898. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  5899. .onClick(() => {
  5900. // this.startAutoHide()
  5901. if(this.isHiCar())
  5902. return
  5903. if(this.is_auto_hide_progress){
  5904. this.is_auto_hide_progress = false
  5905. }
  5906. this.startAutoHide()
  5907. })
  5908. }
  5909. @State progressValue: number = 0;
  5910. @State currentTime: string = "00:00";
  5911. @State totalTime: string = "00:00";
  5912. @State loadingVisible: Visibility = Visibility.None;
  5913. @State replayVisible: Visibility = Visibility.None;
  5914. @State slideEnable: boolean = false;
  5915. @State aspRatio: number = 0.5;
  5916. @State mContext: object | undefined = undefined;
  5917. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  5918. @State mFirst: boolean = true;
  5919. @State mDestroyPage: boolean = false;
  5920. @State playSpeed: number = 1;
  5921. @State oldSeconds: number = 0;
  5922. @State isSeekTo: boolean = false;
  5923. @State isCurrentTime: boolean = false;
  5924. @State videoWidth: string = '100%';
  5925. @State videoHeight: string = '100%';
  5926. @State initAspectRatio: number = 1;
  5927. @State videoAspectRatio: number = this.initAspectRatio;
  5928. private videoUrl: string = '';
  5929. private last: number = 0;
  5930. @State videoParentAspectRatio: number = this.initAspectRatio;
  5931. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  5932. @State CONTROL_PlayStatus: number = PlayStatus.INIT;
  5933. @State PROGRESS_MAX_VALUE: number = 100;
  5934. @State updateProgressTimer: number = 0;
  5935. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  5936. @State name: string = '';
  5937. // @State loop: boolean = false;
  5938. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  5939. @State multiple: string = '1.0X';
  5940. xcomponentController: XComponentController = new XComponentController()
  5941. private panOptionBright: PanGestureOptions =
  5942. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  5943. private panOptionVolume: PanGestureOptions =
  5944. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  5945. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  5946. //手势的音量控制和亮度控制
  5947. private positionX: number = PlayConstants.POSITION_X;
  5948. private positionY: number = PlayConstants.POSITION_Y;
  5949. private windowClass: window.Window = globalThis.windowClass
  5950. @State volume: number = 0.3;
  5951. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  5952. @State bright: number = PlayConstants.BRIGHT;
  5953. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  5954. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  5955. @State screenWidth: number = 0
  5956. @State screenHeight: number = 0
  5957. @State statusBarHeight: number = 0
  5958. @State isYesFull: boolean = false
  5959. private seekValue: number = 0
  5960. @State isVideoLock: boolean = false; // Whether the video playback is locked
  5961. eventHub = getContext().eventHub;
  5962. //投播组件
  5963. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  5964. private castController: avSession.AVCastController | undefined = undefined;
  5965. @State isCastPlaying: boolean = false;
  5966. @State currentTime2: number = 0;
  5967. @State currentStringTime: string = '00:00';
  5968. @State duration: number = 0;
  5969. @State isReady: boolean = false;
  5970. @State durationTime: number = 0;
  5971. @State durationStringTime: string = '00:00';
  5972. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  5973. // @State isPlaying: boolean = false;
  5974. private castSeek: boolean = false;
  5975. private castItem: avSession.AVQueueItem | undefined = undefined;
  5976. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  5977. @State imageLabel: PixelMap | Resource = CommonConstants.musicBgList[0];
  5978. @State imageLabelBg: PixelMap | Resource = CommonConstants.musicBgList[0];
  5979. @State rotateAngle2: number = 0
  5980. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  5981. @State cover: string | undefined = '';
  5982. @State artist: string | undefined = ''
  5983. // 1.初始化controller
  5984. private lyricController: LyricController = new LyricController()
  5985. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  5986. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  5987. private parser = new LyricParser()
  5988. @State randomColor: string = 'rgb(0,0,0)'
  5989. @State randomShakenX: number = 0
  5990. @State randomShakenY: number = 0
  5991. @State lyricTextSize: number = 24
  5992. @State lyricContent: string = ''
  5993. @State isDebug: boolean = false
  5994. @State isHightLightCenter: boolean = true
  5995. /**
  5996. * 初始化歌词加载与展示逻辑
  5997. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  5998. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  5999. * @param isApi2 是否使用API2获取歌词(可选)
  6000. *
  6001. * 主要流程:
  6002. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  6003. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  6004. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  6005. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  6006. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  6007. * 6. 解析失败或读取失败时,清空歌词显示。
  6008. *
  6009. * 注意事项:
  6010. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  6011. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  6012. * - 歌词内容解析后通过lyricController驱动UI渲染。
  6013. */
  6014. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean) {
  6015. if (StrUtil.isEmpty(lyricPath)) {
  6016. return
  6017. }
  6018. this.initPipLyricSetting()
  6019. this.lyricControllerSingle
  6020. .setTextSize(15)
  6021. .setCacheSize(4)
  6022. .setTextColor("#FFFFFF")
  6023. .setHighlightColor("#FFFFFF")
  6024. .setHighlightScale(1.2)
  6025. .setEmptyHint("")
  6026. .setAlignMode('center')
  6027. .setAnimationDuration(500)
  6028. .setSingleLine(true)
  6029. this.lyricContent = ''
  6030. this.lyricController
  6031. .setTextSize(this.currentLyricSize)
  6032. .setCacheSize(4)
  6033. .setTextColor("#DDDDDD")
  6034. .setHighlightColor("#FFFFFF")
  6035. .setEmptyHint("")
  6036. .setAnimationDuration(1000)
  6037. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  6038. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  6039. this.setBlurDegree(this.blurDegree, false)
  6040. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  6041. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  6042. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  6043. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  6044. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  6045. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  6046. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  6047. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  6048. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  6049. this.lyricController.setTextWeight(this.lyricTextWeight)
  6050. this.showSingleLyric = false
  6051. this.timeOffset = 0
  6052. this.lyricController.setLyric(null)
  6053. this.lyricControllerSingle.setLyric(null)
  6054. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  6055. console.log("onecold lyricPath =" + lyricPath)
  6056. let neiqianLrc = ''
  6057. let lyContent = this.currentSong?.lyricContent
  6058. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  6059. neiqianLrc = lyContent
  6060. }
  6061. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast) {
  6062. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  6063. //赋值给this.lyricContent,播控中心才可以显示歌词
  6064. this.lyricContent = neiqianLrc
  6065. // 将文件内容按行分割成字符串数组
  6066. let lines = neiqianLrc.split('\n').map(line => line.trim());
  6067. // 3.解析歌词
  6068. let lyric = this.parser.parse(lines);
  6069. // 4.设置歌词
  6070. this.lyricController.setLyric(lyric);
  6071. this.lyricControllerXF.setLyric(lyric)
  6072. this.lyricControllerSingle.setLyric(lyric)
  6073. return
  6074. }
  6075. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  6076. && !Utility.isVideoByExtension(this.videoUrl))) {
  6077. if (this.currentSong !== undefined) {
  6078. // ToastUtil.showShort('正在为你搜索在线歌词!')
  6079. //判断是不是赞助会员,是会员的话才开启歌词功能
  6080. // if (!this.isDebug) {
  6081. // if (!Utility.isNoble()) {
  6082. // LogUtil.debug("onecold 不是赞助会员")
  6083. // return
  6084. // }
  6085. // if(!Utility.isPassInstallTime(33)){
  6086. // LogUtil.debug("onecold not pass time")
  6087. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  6088. // return
  6089. // }
  6090. // }
  6091. let artist = this.currentSong?.artist
  6092. if (artist === undefined) {
  6093. artist = ''
  6094. }
  6095. if (isApi2 === undefined) {
  6096. isApi2 = false
  6097. }
  6098. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  6099. // LogUtil.debug("onecold res =" + res)
  6100. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  6101. if (StrUtil.isNotEmpty(res)) {
  6102. this.lyricContent = res
  6103. let lines = res.split('\n').map(line => line.trim());
  6104. // 3.解析歌词
  6105. let lyric = this.parser.parse(lines);
  6106. // 4.设置歌词
  6107. this.lyricController.setLyric(lyric);
  6108. this.lyricControllerXF.setLyric(lyric)
  6109. this.lyricControllerSingle.setLyric(lyric)
  6110. this.showSingleLyric = true
  6111. // 4.保存歌词文件lyric到本地
  6112. this.saveDataToFile(res, jiaMilyricPath, true)
  6113. } else {
  6114. this.lyricController.setLyric(null)
  6115. this.lyricControllerXF.setLyric(null)
  6116. this.lyricControllerSingle.setLyric(null)
  6117. if (isOnLineAndToast) {
  6118. ToastUtil.showShort('未获取到歌词!')
  6119. }
  6120. }
  6121. } else {
  6122. this.lyricController.setLyric(null)
  6123. this.lyricControllerXF.setLyric(null)
  6124. this.lyricControllerSingle.setLyric(null)
  6125. if (isOnLineAndToast) {
  6126. ToastUtil.showShort('未获取到歌词!')
  6127. }
  6128. }
  6129. })
  6130. } else {
  6131. this.lyricController.setLyric(null)
  6132. this.lyricControllerXF.setLyric(null)
  6133. this.lyricControllerSingle.setLyric(null)
  6134. if (isOnLineAndToast) {
  6135. ToastUtil.showShort('未获取到歌词!')
  6136. }
  6137. }
  6138. return
  6139. }
  6140. try {
  6141. let isJiaMi = false;
  6142. let realLyricPath = lyricPath
  6143. if (FileUtil.accessSync(jiaMilyricPath)) {
  6144. isJiaMi = true
  6145. realLyricPath = jiaMilyricPath
  6146. console.info("onecold 找到加密本地歌词 ");
  6147. } else {
  6148. isJiaMi = false
  6149. realLyricPath = lyricPath
  6150. console.info("onecold 找到本地歌词 ");
  6151. }
  6152. // 3.读取文件内容并指定编码为 UTF-8
  6153. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  6154. const stat = await fileIo.stat(file.fd);
  6155. const arrayBuffer = new ArrayBuffer(stat.size);
  6156. fs.read(file.fd, arrayBuffer)
  6157. .then((readLen: number) => {
  6158. console.info("read file data succeed");
  6159. // let buf = buffer.from(arrayBuffer, 0, readLen);
  6160. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  6161. // 检查 buf 是否为空
  6162. if (buf.length === 0) {
  6163. throw new Error("Buffer is empty after reading the file");
  6164. }
  6165. try {
  6166. // 检测文件编码
  6167. // let detectedEncoding = chardet.detect(buf);
  6168. // console.info("onecoldT Detected encoding: " + detectedEncoding);
  6169. let detectedEncoding = this.detect(arrayBuffer)
  6170. console.info("onecoldT Detected encoding: " + detectedEncoding);
  6171. // 使用检测到的编码解码,解决中文乱码问题
  6172. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  6173. console.info("onecoldT Detected textDecoder: " + textDecoder);
  6174. let fileContent = textDecoder.decode(buf);
  6175. console.info(`onecoldT The content of file1: ${fileContent}`);
  6176. //解密
  6177. if (isJiaMi) {
  6178. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  6179. }
  6180. console.info(`onecold The content of file2: ${fileContent}`);
  6181. this.lyricContent = fileContent
  6182. // 将文件内容按行分割成字符串数组
  6183. let lines = fileContent.split('\n').map(line => line.trim());
  6184. console.info(`onecold The content of file: ${fileContent}`);
  6185. // 3.解析歌词
  6186. let lyric = this.parser.parse(lines);
  6187. // 4.设置歌词
  6188. this.lyricController.setLyric(lyric);
  6189. this.lyricControllerXF.setLyric(lyric)
  6190. this.lyricControllerSingle.setLyric(lyric)
  6191. this.showSingleLyric = true
  6192. console.info(`The content of file: ${fileContent}`);
  6193. } catch (chardetError) {
  6194. console.error("chardet.detect failed with error: " + chardetError.message);
  6195. this.lyricController.setLyric(null);
  6196. this.lyricControllerXF.setLyric(null)
  6197. this.lyricControllerSingle.setLyric(null)
  6198. }
  6199. })
  6200. .catch((err: BusinessError) => {
  6201. this.lyricController.setLyric(null)
  6202. this.lyricControllerXF.setLyric(null)
  6203. this.lyricControllerSingle.setLyric(null)
  6204. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  6205. })
  6206. .catch((err: Error) => {
  6207. this.lyricController.setLyric(null)
  6208. this.lyricControllerXF.setLyric(null)
  6209. this.lyricControllerSingle.setLyric(null)
  6210. console.error("read file 2 data failed with error message: " + err.message);
  6211. })
  6212. .finally(() => {
  6213. fs.closeSync(file);
  6214. });
  6215. } catch (error) {
  6216. this.lyricController.setLyric(null)
  6217. this.lyricControllerSingle.setLyric(null)
  6218. this.lyricControllerXF.setLyric(null)
  6219. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  6220. }
  6221. }
  6222. detect(data: ArrayBuffer): string {
  6223. //创建检测对象
  6224. let detector: UniversalDetector = new UniversalDetector();
  6225. // 传入检测数据并实时判断编码格式
  6226. detector.handleData(data, 0, data.byteLength);
  6227. // 标记检测数据 读取结束
  6228. detector.dataEnd();
  6229. // 获取检测结果
  6230. let detected: string = detector.getDetectedCharset();
  6231. // 释放资源
  6232. detector.reset();
  6233. return detected;
  6234. }
  6235. //初始化悬浮歌词的自定义设置
  6236. initPipLyricSetting() {
  6237. this.lyricControllerXF
  6238. .setTextSize(this.currentLyricSize)
  6239. .setCacheSize(4)
  6240. .setTextColor("#DDDDDD")
  6241. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  6242. .setEmptyHint("")
  6243. .setAnimationDuration(1000)
  6244. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  6245. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  6246. this.setBlurDegree(this.blurDegreePip, true)
  6247. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  6248. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  6249. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  6250. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  6251. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  6252. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  6253. this.lyricControllerXF.setHightLightCenter(true)
  6254. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  6255. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  6256. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  6257. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  6258. if (this.pipBgIndex === 0) {
  6259. if (this.cover) {
  6260. this.pipBg = this.cover
  6261. } else {
  6262. this.pipBg = this.imageColor
  6263. }
  6264. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  6265. }
  6266. }
  6267. //根据item返回歌词内容
  6268. async getLyricContent(item: VideoItem): Promise<string> {
  6269. let neiqianLrc = ''
  6270. let lyContent = item?.lyricContent
  6271. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  6272. neiqianLrc = lyContent
  6273. return neiqianLrc
  6274. }
  6275. try {
  6276. let filePath = item.filePath;
  6277. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  6278. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  6279. let isJiaMi = false;
  6280. let realLyricPath = lyricPath;
  6281. if (FileUtil.accessSync(jiaMilyricPath)) {
  6282. isJiaMi = true;
  6283. realLyricPath = jiaMilyricPath;
  6284. console.info("onecold 找到加密本地歌词");
  6285. } else {
  6286. console.info("onecold 找到本地歌词");
  6287. }
  6288. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  6289. const stat = await fileIo.stat(file.fd);
  6290. const arrayBuffer = new ArrayBuffer(stat.size);
  6291. const readLen = await fs.read(file.fd, arrayBuffer);
  6292. console.info("read file data succeed");
  6293. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  6294. if (buf.length === 0) {
  6295. throw new Error("Buffer is empty after reading the file");
  6296. }
  6297. // let detectedEncoding = chardet.detect(buf);
  6298. let detectedEncoding = this.detect(arrayBuffer)
  6299. console.info("Detected encoding: " + detectedEncoding);
  6300. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  6301. let fileContent = textDecoder.decode(buf);
  6302. console.info(`onecold The content of file1: ${fileContent}`);
  6303. if (isJiaMi) {
  6304. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  6305. }
  6306. console.info(`onecold The content of file2: ${fileContent}`);
  6307. fs.closeSync(file);
  6308. return fileContent;
  6309. } catch (error) {
  6310. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  6311. return '';
  6312. }
  6313. }
  6314. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  6315. if (StrUtil.isEmpty(filePath)) {
  6316. return
  6317. }
  6318. try {
  6319. //将content进行加密
  6320. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  6321. let lyricContent = ''
  6322. if (isJiaMi) {
  6323. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  6324. } else {
  6325. lyricContent = content
  6326. }
  6327. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  6328. // 清空文件内容
  6329. await fileIo.truncate(file.fd, 0);
  6330. await fileIo.write(file.fd, lyricContent);
  6331. await fileIo.close(file);
  6332. console.log('onecold lyric file Data saved successfully.');
  6333. } catch (error) {
  6334. console.error('onecold lyric file Failed to save data:', error);
  6335. }
  6336. }
  6337. /**
  6338. * Get largest proportion color of an image.
  6339. */
  6340. getImageColor() {
  6341. if (!this.context) {
  6342. return;
  6343. }
  6344. let bg = Utility.getMusisBg()
  6345. this.imageLabel = bg
  6346. ColorConversion.setSysBarLightBackground(true);
  6347. this.context.resourceManager.getMediaContent(bg)
  6348. .then((value: Uint8Array) => {
  6349. let buffer = value.buffer as ArrayBuffer;
  6350. image.createImageSource(buffer).createPixelMap().then((pixelMap) => {
  6351. effectKit.createColorPicker(pixelMap, (error, colorPicker) => {
  6352. if (error) {
  6353. Logger.error('Failed to create color picker.');
  6354. } else {
  6355. let color = colorPicker.getLargestProportionColor();
  6356. let colorArr = ColorConversion.dealColor(color.red, color.green, color.blue);
  6357. this.imageColor = `rgba(${colorArr[0]}, ${colorArr[1]}, ${colorArr[2]}, 1)`;
  6358. }
  6359. })
  6360. let headFilter = effectKit.createEffect(pixelMap);
  6361. if (headFilter !== null) {
  6362. headFilter.blur(15);
  6363. headFilter.getEffectPixelMap().then((value) => {
  6364. this.imageLabelBg = value;
  6365. })
  6366. }
  6367. })
  6368. .catch((error: BusinessError) => {
  6369. Logger.error(`${error.code} + ${error.message}`)
  6370. })
  6371. })
  6372. .catch((error: BusinessError) => {
  6373. Logger.error(`${error.code} + ${error.message}`)
  6374. })
  6375. }
  6376. setImageColor(cover: string) {
  6377. if (!this.context) {
  6378. return;
  6379. }
  6380. if (cover === undefined) {
  6381. return;
  6382. }
  6383. ImageUtil.imagePathToPixelMap(cover).then((value) => {
  6384. let headFilter = effectKit.createEffect(value);
  6385. if (headFilter !== null) {
  6386. headFilter.blur(15);
  6387. headFilter.getEffectPixelMap().then((value) => {
  6388. this.imageLabelBg = value;
  6389. })
  6390. }
  6391. }).catch((error: BusinessError) => {
  6392. Logger.error(`${error.code} + ${error.message}`)
  6393. })
  6394. }
  6395. setImageColor2(cover: string) {
  6396. if (!this.context) {
  6397. return;
  6398. }
  6399. if (cover === undefined) {
  6400. return;
  6401. }
  6402. LogUtils.getInstance().LOGI("setImageColor2--> cover ==" + cover);
  6403. ImageUtils.getImageDealData(getContext(this), cover, this.videoUrl).then((data) => {
  6404. this.imageColor = data.imageColor;
  6405. if (data.blurPixelMap) {
  6406. this.imageLabelBg = data.blurPixelMap;
  6407. }
  6408. })
  6409. }
  6410. // 定义开始旋转的方法
  6411. // 定时器用于一百毫秒执行一次旋转角度
  6412. @State timer: number = 0
  6413. @State rotateAngle: number = 0
  6414. //封面旋转动画
  6415. animationRoFun() {
  6416. if (this.isPlaying && !this.isCoverRectangle) {
  6417. this.timer = setInterval(() => {
  6418. this.rotateAngle += 1
  6419. }, 100)
  6420. this.startRotation()
  6421. } else {
  6422. clearInterval(this.timer)
  6423. this.stopRotation()
  6424. }
  6425. }
  6426. // 定义开始旋转的方法
  6427. startRotation() {
  6428. if (this.isPlaying) {
  6429. animateTo({
  6430. duration: 777,
  6431. iterations: 1,
  6432. curve: Curve.Linear
  6433. }, () => {
  6434. this.rotateAngle2 = 0
  6435. })
  6436. }
  6437. }
  6438. // 回调,暂停和播放按钮回调,下一首和上一首
  6439. playChange() {
  6440. // if(this.isCoverRectangle){
  6441. // return
  6442. // }
  6443. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  6444. this.setIsPlaying(true)
  6445. this.animationState = AnimationStatus.Running
  6446. } else {
  6447. this.setIsPlaying(false)
  6448. this.animationState = AnimationStatus.Paused
  6449. }
  6450. }
  6451. // 定义停止旋转的方法
  6452. stopRotation() {
  6453. if (this.isCoverRectangle) {
  6454. this.rotateAngle = 0
  6455. } else {
  6456. //唱针以左上角为点选择逆时针40度
  6457. animateTo({
  6458. duration: 1000,
  6459. curve: Curve.Linear,
  6460. iterations: 1,
  6461. }, () => {
  6462. this.rotateAngle2 = -40;
  6463. });
  6464. }
  6465. }
  6466. @Builder
  6467. private LyricsTopItem() {
  6468. Row() {
  6469. Stack() {
  6470. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  6471. .height(55)
  6472. .width(55)
  6473. .alt(this.imageLabel)
  6474. .borderRadius(8)
  6475. .clickEffect({ level: ClickEffectLevel.HEAVY })
  6476. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  6477. }
  6478. .width('18%')
  6479. Column() {
  6480. Column() {
  6481. Text(this.name)
  6482. .fontSize(16)
  6483. .maxLines(1)
  6484. .fontWeight(FontWeight.Bolder)
  6485. .fontColor(this.currentLyricColor)
  6486. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  6487. Row() {
  6488. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  6489. .fontSize(13)
  6490. .fontWeight(FontWeight.Bold)
  6491. .padding({ top: 8 })
  6492. .fontColor(this.currentLyricColor)
  6493. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  6494. Blank()
  6495. }
  6496. }
  6497. .height('100%')
  6498. .width('100%')
  6499. .justifyContent(FlexAlign.Center)
  6500. .alignItems(HorizontalAlign.Start)
  6501. }
  6502. .height('100%')
  6503. .width('65%')
  6504. Column() {
  6505. Image($r('app.media.lyric'))
  6506. .width(28)
  6507. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6508. .margin({ right: 30 })
  6509. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6510. .onClick(() => {
  6511. this.isLyricSetting = !this.isLyricSetting;
  6512. })
  6513. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  6514. height: this.isCoverOpacity() ? '95%' : '88%',
  6515. dragBar: true,
  6516. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6517. showClose: true,
  6518. blurStyle: BlurStyle.Thin,
  6519. backgroundColor: Color.Transparent,
  6520. // title: { title: $r('app.string.lyric_setting') }
  6521. })
  6522. }
  6523. .width('18%')
  6524. }
  6525. .width('82%')
  6526. .height(58)
  6527. .justifyContent(FlexAlign.SpaceBetween)
  6528. }
  6529. //歌词显示
  6530. @Builder
  6531. PlayerLyrics() {
  6532. Column() {
  6533. Column() {
  6534. this.LyricsTopItem()
  6535. }
  6536. .height(this.isPuraWP() ? 15 : 58)
  6537. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  6538. Visibility.None : Visibility.Visible)
  6539. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  6540. .width("100%")
  6541. Column() {
  6542. LyricView2({
  6543. controller: this.lyricController,
  6544. enableSeek: true,
  6545. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  6546. seekLineColor: "#80ffffff", // 滑动定位线颜色
  6547. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  6548. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  6549. if (!this.isPlaying) {
  6550. this.startPlayOrResumePlay()
  6551. } else {
  6552. this.isSeekTo = true;
  6553. this.mDestroyPage = false;
  6554. this.showLoadIng();
  6555. this.seekTo(position + "");
  6556. this.isSeekTo = false;
  6557. }
  6558. return true
  6559. }
  6560. })
  6561. .width("100%")
  6562. .layoutWeight(1)
  6563. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  6564. if (this.isPhoneLan()) {
  6565. Column() {
  6566. this.playProgressView()
  6567. // this.playCenterView()
  6568. }
  6569. .margin({ bottom: 30, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  6570. }
  6571. }
  6572. .position({
  6573. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  6574. (this.isPuraWP() ? 58 : 99)
  6575. })
  6576. .justifyContent(FlexAlign.Center)
  6577. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  6578. }
  6579. }
  6580. @Builder
  6581. SingleLyricView() {
  6582. Column() {
  6583. Column() {
  6584. LyricView2({
  6585. controller: this.lyricControllerSingle,
  6586. enableSeek: false,
  6587. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  6588. seekLineColor: "#80ffffff", // 滑动定位线颜色
  6589. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  6590. })
  6591. }
  6592. .height(66)
  6593. .margin({ bottom: 20 })
  6594. }
  6595. }
  6596. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  6597. @Builder
  6598. BottomControl() {
  6599. Column() {
  6600. this.TopPlayProgressView()
  6601. //播放 暂停,下一首,上一首
  6602. this.playCenterView()
  6603. //播放进度条
  6604. this.BottomView()
  6605. }
  6606. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  6607. }
  6608. //播放控制上一首 下一首 暂停和播放
  6609. @Builder
  6610. playCenterView(){
  6611. Row() {
  6612. Row({ space: 20 }) {
  6613. Button({type:ButtonType.Circle,stateEffect:true}){
  6614. //更多功能
  6615. Image($r('app.media.menu'))
  6616. .width(24)
  6617. .clickEffect({level:ClickEffectLevel.MIDDLE})
  6618. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  6619. height: this.isCoverOpacity() ? '95%' : '93%',
  6620. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  6621. dragBar: true,
  6622. showClose: true,
  6623. blurStyle: BlurStyle.Thin,
  6624. backgroundColor: Color.Transparent,
  6625. })
  6626. }
  6627. .margin({ left: 5 })
  6628. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6629. .backgroundColor(Color.Transparent)
  6630. .onClick(() => {
  6631. this.isShowMoreView = !this.isShowMoreView;
  6632. })
  6633. Button({type:ButtonType.Circle,stateEffect:true}){
  6634. Image($r('app.media.ic_previous'))
  6635. .width(33)
  6636. .clickEffect({level:ClickEffectLevel.HEAVY})
  6637. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6638. }
  6639. .onClick(async () => {
  6640. this.playPrevious()
  6641. })
  6642. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6643. .backgroundColor(Color.Transparent)
  6644. .margin({ left: 5 })
  6645. }
  6646. Button({type:ButtonType.Circle,stateEffect:true}){
  6647. Column() {
  6648. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  6649. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  6650. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  6651. .width(this.isPhoneLan()?45:55)
  6652. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6653. .fillColor(Color.White)
  6654. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6655. .onClick(async () => {
  6656. this.playOrPause()
  6657. })
  6658. }
  6659. }
  6660. .backgroundColor(Color.Transparent)
  6661. .layoutWeight(1)
  6662. // .margin({ left: 38, right: 38 })
  6663. Row({ space: 20 }) {
  6664. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6665. Image($r('app.media.ic_next'))
  6666. .width(33)
  6667. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6668. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6669. .onClick(() => {
  6670. this.playNext();
  6671. })
  6672. }
  6673. .backgroundColor(Color.Transparent)
  6674. .margin({ right: 5 })
  6675. .width(33)
  6676. Button({type:ButtonType.Circle,stateEffect:true}){
  6677. //添加或取消收藏
  6678. Image(Utility.getIsFav(this.favList,this.currentSong)?
  6679. $r('app.media.add_fac_light'):$r('app.media.add_fac'))
  6680. .width(24)
  6681. .clickEffect({level:ClickEffectLevel.MIDDLE})
  6682. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6683. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6684. .onClick(async () => {
  6685. if(this.currentSong){
  6686. this.doFav(this.currentSong)
  6687. }
  6688. })
  6689. }
  6690. .backgroundColor(Color.Transparent)
  6691. .width(24)
  6692. }
  6693. // .margin({ left: 5 })
  6694. }
  6695. .width('95%')
  6696. .margin({ bottom:this.isCoverOpacity()?0:20 })
  6697. .justifyContent(FlexAlign.SpaceEvenly)
  6698. }
  6699. @Builder
  6700. TopPlayProgressView(){
  6701. Row() {
  6702. Column(){
  6703. Row(){
  6704. Slider({
  6705. value: this.progressValue,
  6706. min: 0,
  6707. max: this.PROGRESS_MAX_VALUE,
  6708. step: 1,
  6709. style: SliderStyle.InSet
  6710. })
  6711. .height(20)
  6712. .blockColor('rgba(255,255,255,1)')
  6713. .trackColor('rgba(255,255,255,0.3)')
  6714. .selectedColor(Color.White)
  6715. .trackThickness(4)
  6716. .layoutWeight(1)
  6717. .showSteps(false)
  6718. .showTips(true)
  6719. .alignSelf(ItemAlign.Center)
  6720. .enabled(this.slideEnable)
  6721. .onChange((value: number, mode: SliderChangeMode) => {
  6722. // if (mode == 2) {
  6723. this.isSeekTo = true;
  6724. this.mDestroyPage = false;
  6725. this.showLoadIng();
  6726. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  6727. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  6728. this.seekTo(seekValue + "");
  6729. // this.setProgress()
  6730. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  6731. this.isSeekTo = false;
  6732. // }
  6733. })
  6734. }
  6735. .padding({ right: 7,left:20 })
  6736. Row(){
  6737. Text(this.currentTime)
  6738. .fontSize(10)
  6739. .fontColor(Color.White)
  6740. Blank()
  6741. .layoutWeight(1)
  6742. Text(this.totalTime)
  6743. .fontSize(10)
  6744. .fontColor(Color.White)
  6745. }
  6746. .justifyContent(FlexAlign.Start)
  6747. .padding({ right: 18,left:36 })
  6748. }
  6749. }
  6750. //x5的竖屏模式需要99%
  6751. .width(this.isLandscape?'80%':'93%')
  6752. .justifyContent(FlexAlign.Center)
  6753. .margin({bottom:6})
  6754. .animation({
  6755. duration: 666,
  6756. curve: 'ease-in-out' // 可选动画曲线
  6757. })
  6758. }
  6759. //播放进度条
  6760. @Builder
  6761. BottomView(){
  6762. Row() {
  6763. Button({type:ButtonType.Circle,stateEffect:true}){
  6764. Column() {
  6765. if (this.playType === 0) {
  6766. Image($r('app.media.loop'))
  6767. .width(27)
  6768. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6769. } else if (this.playType === 1) {
  6770. Image($r('app.media.single'))
  6771. .width(27)
  6772. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6773. } else if (this.playType === 2) {
  6774. Image($r('app.media.normal_play'))
  6775. .width(27)
  6776. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6777. } else if (this.playType === 3) {
  6778. Image($r('app.media.random'))
  6779. .width(27)
  6780. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6781. }
  6782. }
  6783. }
  6784. .layoutWeight(1)
  6785. .margin({ left: 5 })
  6786. .backgroundColor(Color.Transparent)
  6787. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6788. .onClick(async () => {
  6789. this.setLoopMode()
  6790. })
  6791. Button({type:ButtonType.Circle,stateEffect:true}){
  6792. Column() {
  6793. Image($r('app.media.full_4'))
  6794. .width(25)
  6795. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6796. }
  6797. }
  6798. .layoutWeight(1)
  6799. .backgroundColor(Color.Transparent)
  6800. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6801. .onClick(async () => {
  6802. if (this.isLandscape) {
  6803. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  6804. } else {
  6805. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  6806. }
  6807. })
  6808. Button({type:ButtonType.Circle,stateEffect:true}){
  6809. Column() {
  6810. Image($r('app.media.lyric'))
  6811. .width(26)
  6812. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6813. }
  6814. }
  6815. .layoutWeight(1)
  6816. .backgroundColor(Color.Transparent)
  6817. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6818. .onClick(async () => {
  6819. this.isLyricSetting = !this.isLyricSetting;
  6820. })
  6821. //播放列表
  6822. Button({type:ButtonType.Circle,stateEffect:true}){
  6823. Image($r('app.media.hm_playlist'))
  6824. .width(24)
  6825. .fillColor(Color.White)
  6826. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6827. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  6828. height: '95%',
  6829. dragBar: true,
  6830. showClose: true,
  6831. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6832. blurStyle: BlurStyle.Thin,
  6833. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  6834. title: {
  6835. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  6836. + `(${this.songList.length}首)`
  6837. }
  6838. })
  6839. }
  6840. .layoutWeight(1)
  6841. .backgroundColor(Color.Transparent)
  6842. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  6843. .onClick(() => {
  6844. this.isShowSheetView = !this.isShowSheetView;
  6845. if(this.isPlayListBgGrass){
  6846. this.isFrontWhite = true
  6847. }else{
  6848. this.isFrontWhite = false
  6849. }
  6850. setTimeout(() => {
  6851. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  6852. }, 123)
  6853. })
  6854. }
  6855. .width(this.isLandscape?'88%':'95%')
  6856. .justifyContent(FlexAlign.SpaceAround)
  6857. .height(30)
  6858. .margin({top:3})
  6859. .animation({
  6860. duration: 666,
  6861. curve: 'ease-in-out' // 可选动画曲线
  6862. })
  6863. }
  6864. //旧版本播放进度条
  6865. @Builder
  6866. playProgressView() {
  6867. Row() {
  6868. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6869. Column() {
  6870. if (this.playType === 0) {
  6871. Image($r('app.media.loop'))
  6872. .width($r('app.float.control_image_width'))
  6873. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6874. } else if (this.playType === 1) {
  6875. Image($r('app.media.single'))
  6876. .width($r('app.float.control_image_width'))
  6877. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6878. } else if (this.playType === 2) {
  6879. Image($r('app.media.normal_play'))
  6880. .width($r('app.float.control_image_width'))
  6881. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6882. } else if (this.playType === 3) {
  6883. Image($r('app.media.random'))
  6884. .width($r('app.float.control_image_width'))
  6885. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6886. }
  6887. }
  6888. }
  6889. .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  6890. .animation({
  6891. duration: 666,
  6892. curve: 'ease-in-out' // 可选动画曲线
  6893. })
  6894. .backgroundColor(Color.Transparent)
  6895. .margin({ right: 10 })
  6896. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6897. .onClick(async () => {
  6898. this.setLoopMode()
  6899. })
  6900. Text(this.currentTime)
  6901. .fontSize($r('app.float.slider_font_size'))
  6902. .fontColor(Color.White)
  6903. .margin(3)
  6904. Slider({
  6905. value: this.progressValue,
  6906. min: 0,
  6907. max: this.PROGRESS_MAX_VALUE,
  6908. step: 1,
  6909. style: SliderStyle.OutSet
  6910. })
  6911. .width('600px')
  6912. .blockColor('rgba(255,255,255,1)')
  6913. .trackColor('rgba(255,255,255,0.3)')
  6914. .selectedColor(Color.White)
  6915. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  6916. .layoutWeight(1)
  6917. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  6918. .showSteps(false)
  6919. .showTips(true)
  6920. .enabled(this.slideEnable)
  6921. .onChange((value: number, mode: SliderChangeMode) => {
  6922. // if (mode == 2) {
  6923. this.isSeekTo = true;
  6924. this.mDestroyPage = false;
  6925. this.showLoadIng();
  6926. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  6927. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  6928. this.seekTo(seekValue + "");
  6929. // this.setProgress()
  6930. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  6931. this.isSeekTo = false;
  6932. // }
  6933. })
  6934. Text(this.totalTime)
  6935. .fontSize($r('app.float.slider_font_size'))
  6936. .fontColor(Color.White)
  6937. .margin(3)
  6938. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  6939. //播放列表
  6940. Button({ type: ButtonType.Circle, stateEffect: true }) {
  6941. Image($r('app.media.hm_playlist'))
  6942. .width($r('app.float.control_image_width'))
  6943. .fillColor(Color.White)
  6944. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6945. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  6946. height: '95%',
  6947. dragBar: true,
  6948. showClose: true,
  6949. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6950. blurStyle: BlurStyle.Thin,
  6951. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  6952. title: {
  6953. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  6954. + `(${this.songList.length}首)`
  6955. }
  6956. })
  6957. }
  6958. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  6959. .animation({
  6960. duration: 666,
  6961. curve: 'ease-in-out' // 可选动画曲线
  6962. })
  6963. .backgroundColor(Color.Transparent)
  6964. .margin({ right: 20, left: 10 })
  6965. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6966. .onClick(() => {
  6967. this.isShowSheetView = !this.isShowSheetView;
  6968. if (this.isPlayListBgGrass) {
  6969. this.isFrontWhite = true
  6970. } else {
  6971. this.isFrontWhite = false
  6972. }
  6973. setTimeout(() => {
  6974. this.playListScroller.scrollToIndex(this.curIndex, true, ScrollAlign.CENTER)
  6975. }, 123)
  6976. })
  6977. }
  6978. //x5的竖屏模式需要99%
  6979. .width(this.isPhonePortrait() ? '93.4%'
  6980. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  6981. .height(this.isPhoneLan() ? 25 : 33)
  6982. .animation({
  6983. duration: 666,
  6984. curve: 'ease-in-out' // 可选动画曲线
  6985. })
  6986. }
  6987. isBigScreen() {
  6988. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  6989. return true
  6990. }
  6991. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  6992. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  6993. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  6994. return false
  6995. } else {
  6996. return true
  6997. }
  6998. return false
  6999. }
  7000. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  7001. @State isCoverRectangle: boolean = false
  7002. @State isCoverTop: boolean = true
  7003. // 添加控制缩放的状态变量
  7004. @State scaleValueImage: number = 1
  7005. @Builder
  7006. CoverInfo() {
  7007. Column() {
  7008. //如果是方形,判断是不是封面在顶部,如果不是顶部,显示musicNameInfo, 如果是圆形显示musicNameInfo
  7009. if (this.isCoverRectangle) {
  7010. if (!this.isCoverTop) {
  7011. this.musicNameInfo(false)
  7012. }
  7013. } else {
  7014. this.musicNameInfo(false)
  7015. }
  7016. Stack() {
  7017. // 唱片旋转效果
  7018. Image($r('app.media.ic_music_disc'))
  7019. .width(245)
  7020. .height(245)
  7021. .margin({ right: 20, left: 20 })
  7022. .aspectRatio(1)
  7023. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  7024. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  7025. .borderRadius('100%')
  7026. .align(Alignment.Center)
  7027. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  7028. .rotate({
  7029. angle: this.rotateAngle,
  7030. centerX: "50%",
  7031. centerY: "50%",
  7032. })
  7033. .animation({
  7034. duration: 100,
  7035. curve: Curve.Linear
  7036. })
  7037. .shadow({
  7038. radius: 30,
  7039. color: this.randomColor
  7040. })
  7041. Column() {
  7042. if (this.isCoverTop && !this.isCoverOpacity() && this.isCoverRectangle) {
  7043. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)// .height(this.isCoverOpacity() ? 250 : this.isCoverRectangle ? 320 : 162)
  7044. .width(this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '86%')
  7045. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  7046. .alt(this.imageLabel)
  7047. .margin({ right: 8, left: 8, top: 8 })
  7048. .aspectRatio(1)
  7049. .opacity(this.opacityValueImage)
  7050. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  7051. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  7052. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  7053. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  7054. .align(Alignment.Center)//
  7055. .clip(true)
  7056. .rotate({
  7057. x: 0,
  7058. y: 0,
  7059. z: 1,
  7060. angle: this.rotateAngle
  7061. })
  7062. .onClick(() => {
  7063. this.getImageColor()
  7064. })
  7065. this.musicNameInfo(false)
  7066. } else {
  7067. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  7068. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):(this.isCoverOpacity() ? 250 : this.isCoverRectangle ? 320 : 162))
  7069. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  7070. .alt(this.imageLabel)
  7071. .margin({ right: 20, left: 20 })
  7072. .aspectRatio(1)
  7073. .opacity(this.opacityValueImage)
  7074. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  7075. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  7076. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  7077. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  7078. .align(Alignment.Center)//
  7079. .clip(true)
  7080. .rotate({
  7081. x: 0,
  7082. y: 0,
  7083. z: 1,
  7084. angle: this.rotateAngle
  7085. })
  7086. .onClick(() => {
  7087. this.getImageColor()
  7088. })
  7089. if (this.isPhoneLan()) {
  7090. Text(this.name)
  7091. .fontSize(18)
  7092. .fontWeight(FontWeight.Bold)
  7093. .margin({ top: 13 })
  7094. .textOverflow({ overflow: TextOverflow.Ellipsis })
  7095. .maxLines(1)
  7096. .width('99%')
  7097. .textAlign(TextAlign.Center)
  7098. .fontColor(Color.White)
  7099. }
  7100. }
  7101. }
  7102. // 唱针以左上角为点选择逆时针40度
  7103. Image($r('app.media.ic_music_cover_hand'))
  7104. .height(130)
  7105. .margin({ bottom: 220, top: 0 })
  7106. .align(Alignment.Top)
  7107. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  7108. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  7109. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  7110. Column({ space: 8 }) {
  7111. Text(this.name)
  7112. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  7113. .fontWeight(FontWeight.Bold)
  7114. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  7115. .maxLines(1)
  7116. .width('48%')
  7117. .textAlign(TextAlign.Center)
  7118. .fontColor(Color.White)
  7119. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  7120. Text(this.artist)
  7121. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  7122. .fontColor(Color.White)
  7123. .fontWeight(FontWeight.Bold)
  7124. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  7125. }
  7126. .justifyContent(FlexAlign.Start)
  7127. .zIndex(1)
  7128. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  7129. }
  7130. .margin({
  7131. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  7132. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  7133. top: this.isCoverOpacity() ? 0 : 20
  7134. })
  7135. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  7136. this.SingleLyricView()
  7137. }
  7138. if (this.isPhoneLan()) {
  7139. Column() {
  7140. this.playCenterView()
  7141. // this.playProgressView()
  7142. }
  7143. .position({ left: 28, bottom: 38 })
  7144. } else {
  7145. this.BottomControl()
  7146. }
  7147. }
  7148. .width(CommonConstants.FULL_PERCENT)
  7149. .clip(true)
  7150. }
  7151. @Builder
  7152. private musicNameInfo(isHidden: boolean) {
  7153. Column({ space: 8 }) {
  7154. Text(this.name)
  7155. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22)
  7156. .fontWeight(FontWeight.Bold)
  7157. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  7158. .maxLines(1)
  7159. .width('99%')
  7160. .textAlign(TextAlign.Center)
  7161. .fontColor(Color.White)
  7162. Text(this.artist + ' ' + this.currentSong?.album)
  7163. .fontSize(this.isCoverOpacity() ? 12 : 15)
  7164. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  7165. .fontColor(Color.White)
  7166. .textAlign(TextAlign.Center)
  7167. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  7168. .width('99%')
  7169. .maxLines(1)
  7170. }
  7171. .margin({ top: this.isCoverOpacity() ? 20 : isHidden ? 40 : 20 })
  7172. .zIndex(1)
  7173. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  7174. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  7175. }
  7176. @Builder
  7177. private PlayTitle() {
  7178. Row() {
  7179. Row() {
  7180. Image($r('app.media.ic_back_down'))
  7181. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  7182. .hitTestBehavior(HitTestMode.Transparent)
  7183. Text(this.name + ' ' + this.artist)
  7184. .fontColor(Color.White)
  7185. .fontSize($r('app.float.title_font_size'))
  7186. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  7187. .maxLines(1)
  7188. .visibility(Visibility.None)
  7189. .margin({ left: 2, right: 30 })
  7190. }
  7191. .layoutWeight(1)
  7192. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7193. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  7194. .onClick(() => {
  7195. this.isShowPlay = false;
  7196. })
  7197. Column() {
  7198. AVCastPicker({
  7199. normalColor: Color.White,
  7200. onStateChange: this.onStateVastChange
  7201. })
  7202. .width(24)
  7203. .height(24)
  7204. }
  7205. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  7206. }
  7207. .width(PlayConstants.ROW_WIDTH)
  7208. }
  7209. @Builder
  7210. lyricSettingSheet(isPip: boolean) {
  7211. Scroll() {
  7212. this.lyricSetting(isPip)
  7213. }
  7214. .width('100%')
  7215. .height('100%')
  7216. }
  7217. @Builder
  7218. lyricSetting(isPip: boolean) {
  7219. Column() {
  7220. // 时间调节模块
  7221. if (!isPip) {
  7222. this.BuildTimeControls()
  7223. }
  7224. // 字号控制模块
  7225. this.BuildFontControls(isPip)
  7226. }
  7227. }
  7228. // 歌词时间偏移状态
  7229. @State timeOffset: number = 0.0
  7230. @State currentLyricColor: string = '#FFFFFF'
  7231. @State currentLyricColorPip: string = '#FFFFFF'
  7232. @State currentHighLightLyricColor: string = '#FF4081'
  7233. @State currentHighLightLyricColorPip: string = '#FF4081'
  7234. // 歌词字号状态
  7235. @State currentLyricSize: number = 20
  7236. @State currentLyricSizePip: number = 20
  7237. // 高亮歌词放大倍数
  7238. @State currentHightLyricSize: number = 1.2
  7239. @State currentHightLyricSizePip: number = 1.2
  7240. @State currentLyricLineSpace: number = 10
  7241. @State currentLyricLineSpacePip: number = 10
  7242. @State currentLyricAlignMode: number = 1
  7243. @State currentLyricAlignModePip: number = 1
  7244. @State blurDegree: number = 2
  7245. @State blurDegreePip: number = 2
  7246. @State isShowSelectColor: boolean = false
  7247. @State isShowHLSelectColor: boolean = false
  7248. @State isShowPipBgSelectColor: boolean = false
  7249. @State pipLyWidth: number = 330
  7250. @State pipLyHeight: number = 120
  7251. // 构建颜色选择器
  7252. @Builder
  7253. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  7254. Row({ space: 10 }) {
  7255. HSBColorPicker({
  7256. color: '#FFFFFF',
  7257. radius: 8,
  7258. layout: HSBColorPickerLayout.COLUMN,
  7259. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  7260. '#fa7105'],
  7261. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  7262. this.changeLyricColor(value, isPip, isBGPip)
  7263. })
  7264. .height(250)
  7265. .layoutWeight(1)
  7266. .padding(25)
  7267. }
  7268. .width('66%')
  7269. }
  7270. @State isOpenPip: boolean = false
  7271. @State pipBgIndex: number = 0
  7272. // 构建字号控制器
  7273. @Builder
  7274. BuildFontControls(isPip: boolean) {
  7275. Column() {
  7276. if (isPip) {
  7277. Column() {
  7278. Row() {
  7279. Text('悬浮歌词')
  7280. .margin({ left: 18 })
  7281. .fontSize(15)
  7282. .fontColor(Color.White)
  7283. .fontWeight(480)
  7284. .layoutWeight(1)
  7285. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  7286. .selectedColor(this.themeColor)
  7287. .switchPointColor(Color.White)
  7288. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7289. .margin({ right: 18 })
  7290. .onChange((checked: boolean) => {
  7291. this.isOpenPip = checked;
  7292. if (this.isOpenPip) {
  7293. this.startPip()
  7294. } else {
  7295. this.stopPip()
  7296. }
  7297. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  7298. })
  7299. .width(50)
  7300. .height(30);
  7301. }
  7302. .height(55)
  7303. }
  7304. .backgroundColor(Color.Transparent)
  7305. .borderRadius(15)
  7306. .margin({
  7307. left: 30,
  7308. right: 30,
  7309. top: 0,
  7310. bottom: 20
  7311. })
  7312. .padding(0)
  7313. .border({
  7314. color: Color.White,
  7315. width: 1.8
  7316. })
  7317. }
  7318. Row() {
  7319. Text(`歌词居中:`)
  7320. .fontSize(14)
  7321. .fontColor(Color.White)
  7322. .margin({ left: 2 })
  7323. Row() {
  7324. ForEach(['居中', '居左'], (size: string, index: number) => {
  7325. Button(size)
  7326. .width(60)
  7327. .height(28)
  7328. .fontSize(12)
  7329. .fontColor('#FFFFFF')
  7330. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  7331. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  7332. .border({
  7333. color: (!isPip && this.currentLyricAlignMode === index) ||
  7334. (isPip && this.currentLyricAlignModePip === index) ?
  7335. '#007DFF' : '#DDDDDD',
  7336. width: 1.8
  7337. })
  7338. .onClick(() => {
  7339. this.setLyricAlignMode(index, isPip)
  7340. })
  7341. .margin({ left: 10, right: 8 })
  7342. })
  7343. }
  7344. .width('76%')
  7345. Blank()
  7346. }
  7347. .margin({
  7348. top: 10,
  7349. bottom: 10,
  7350. right: 20,
  7351. left: 20
  7352. })
  7353. if (isPip) {
  7354. Row() {
  7355. Text(`悬浮背景:`)
  7356. .fontSize(14)
  7357. .fontColor(Color.White)
  7358. Select([
  7359. { value: CommonConstants.PIP_LYRIC_BG[0] },
  7360. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  7361. .font({ size: 13, weight: FontWeight.Medium })
  7362. .fontColor(Color.White)
  7363. .margin({ left: 10 })
  7364. .selected(this.pipBgIndex)
  7365. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  7366. .onSelect(async (_index: number, text?: string | undefined) => {
  7367. this.pipBgIndex = _index
  7368. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  7369. if (this.pipBgIndex === 0) {
  7370. if (this.cover) {
  7371. this.pipBg = this.cover
  7372. } else {
  7373. this.pipBg = this.imageColor
  7374. }
  7375. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  7376. } else {
  7377. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  7378. }
  7379. })
  7380. Column() {
  7381. }
  7382. .backgroundColor(this.pipBg)
  7383. .margin({ left: 10, right: 10 })
  7384. .borderRadius(20)
  7385. .height(28)
  7386. .width(28)
  7387. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7388. Row() {
  7389. SymbolGlyph($r('sys.symbol.paintbrush'))
  7390. .fontColor([Color.White])
  7391. .effectStrategy(1)
  7392. Text(`选择颜色`)
  7393. .fontSize(13)
  7394. .margin({ left: 10 })
  7395. .fontColor(Color.White)
  7396. }
  7397. }
  7398. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  7399. .backgroundColor(Color.Transparent)
  7400. .border({
  7401. color: '#FFFFFF',
  7402. radius: 20,
  7403. width: 1.8
  7404. })
  7405. .height(36)
  7406. .width(110)
  7407. .onClick(() => {
  7408. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  7409. })
  7410. .bindPopup(this.isShowPipBgSelectColor, {
  7411. builder: this.SelectColor(false, isPip, true),
  7412. placement: Placement.Top,
  7413. mask: { color: '#33000000' },
  7414. enableArrow: false, //是否显示箭头
  7415. showInSubWindow: false,
  7416. onStateChange: (e) => {
  7417. if (!e.isVisible) {
  7418. this.isShowPipBgSelectColor = false
  7419. }
  7420. }
  7421. })
  7422. }
  7423. .width('76%')
  7424. .margin({ bottom: 5, right: 45, left: 20 })
  7425. }
  7426. if (!isPip) {
  7427. Row() {
  7428. Text(`高亮居中:`)
  7429. .fontSize(14)
  7430. .fontColor(Color.White)
  7431. Column() {
  7432. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  7433. .selectedColor(this.themeColor)
  7434. .switchPointColor(Color.White)
  7435. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7436. .onChange((checked: boolean) => {
  7437. this.isHightLightCenter = checked;
  7438. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  7439. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  7440. })
  7441. .width(50)
  7442. .height(30)
  7443. .alignSelf(ItemAlign.Start)
  7444. .margin({ left: 12 })
  7445. Blank()
  7446. }
  7447. .width('76%')
  7448. }
  7449. .margin({
  7450. left: 20,
  7451. right: 15,
  7452. top: 10,
  7453. bottom: 10
  7454. })
  7455. }
  7456. Row() {
  7457. Text(`歌词颜色:`)
  7458. .fontSize(14)
  7459. .fontColor(Color.White)
  7460. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  7461. .fontSize(15)
  7462. .fontColor(Color.White)
  7463. .margin({ left: 12, right: 12 })
  7464. Column() {
  7465. }
  7466. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  7467. .margin({ right: 12 })
  7468. .borderRadius(20)
  7469. .height(28)
  7470. .width(28)
  7471. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7472. Row() {
  7473. SymbolGlyph($r('sys.symbol.paintbrush'))
  7474. .fontColor([Color.White])
  7475. .effectStrategy(1)
  7476. Text(`选择颜色`)
  7477. .fontSize(13)
  7478. .margin({ left: 10 })
  7479. .fontColor(Color.White)
  7480. }
  7481. }
  7482. .backgroundColor(Color.Transparent)
  7483. .border({
  7484. color: '#FFFFFF',
  7485. radius: 20,
  7486. width: 1.8
  7487. })
  7488. .height(36)
  7489. .width(110)
  7490. .onClick(() => {
  7491. this.isShowSelectColor = !this.isShowSelectColor
  7492. })
  7493. .bindPopup(this.isShowSelectColor, {
  7494. builder: this.SelectColor(false, isPip),
  7495. placement: Placement.Top,
  7496. mask: { color: '#33000000' },
  7497. enableArrow: false, //是否显示箭头
  7498. showInSubWindow: false,
  7499. onStateChange: (e) => {
  7500. if (!e.isVisible) {
  7501. this.isShowSelectColor = false
  7502. }
  7503. }
  7504. })
  7505. }
  7506. .width('76%')
  7507. .margin({
  7508. top: 10,
  7509. bottom: 10,
  7510. right: 45,
  7511. left: 20
  7512. })
  7513. Row() {
  7514. Text(`高亮颜色:`)
  7515. .fontSize(14)
  7516. .fontColor(Color.White)
  7517. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  7518. .fontSize(15)
  7519. .fontColor(Color.White)
  7520. .margin({ left: 12, right: 12 })
  7521. Column() {
  7522. }
  7523. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  7524. .margin({ right: 12 })
  7525. .borderRadius(20)
  7526. .height(28)
  7527. .width(28)
  7528. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7529. Row() {
  7530. SymbolGlyph($r('sys.symbol.paintbrush'))
  7531. .fontColor([Color.White])
  7532. .effectStrategy(1)
  7533. Text(`选择颜色`)
  7534. .fontSize(13)
  7535. .margin({ left: 10 })
  7536. .fontColor(Color.White)
  7537. }
  7538. }
  7539. .backgroundColor(Color.Transparent)
  7540. .border({
  7541. color: '#FFFFFF',
  7542. radius: 20,
  7543. width: 1.8
  7544. })
  7545. .height(36)
  7546. .width(110)
  7547. .onClick(() => {
  7548. this.isShowHLSelectColor = !this.isShowHLSelectColor
  7549. })
  7550. .bindPopup(this.isShowHLSelectColor, {
  7551. builder: this.SelectColor(true, isPip),
  7552. placement: Placement.Top,
  7553. mask: { color: '#33000000' },
  7554. enableArrow: false, //是否显示箭头
  7555. showInSubWindow: false,
  7556. onStateChange: (e) => {
  7557. if (!e.isVisible) {
  7558. this.isShowHLSelectColor = false
  7559. }
  7560. }
  7561. })
  7562. }
  7563. .width('76%')
  7564. .margin({
  7565. top: 10,
  7566. bottom: 10,
  7567. right: 45,
  7568. left: 20
  7569. })
  7570. if (isPip) {
  7571. Row() {
  7572. Text(`显示宽度:`)
  7573. .fontSize(14)
  7574. .fontColor(Color.White)
  7575. Slider({
  7576. value: this.pipLyWidth,
  7577. min: 10,
  7578. max: 800,
  7579. step: 1,
  7580. style: SliderStyle.OutSet
  7581. })
  7582. .blockColor(this.themeColor)
  7583. .trackColor($r('app.color.speed_text_color'))
  7584. .selectedColor(Color.White)
  7585. .trackThickness(6)
  7586. .onChange((value: number) => {
  7587. this.pipLyWidth = value
  7588. if (this.pipController) {
  7589. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  7590. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  7591. }
  7592. })
  7593. .width('76%')
  7594. }
  7595. .margin({
  7596. left: 20,
  7597. right: 15,
  7598. top: 5,
  7599. bottom: 5
  7600. })
  7601. Row() {
  7602. Text(`显示高度:`)
  7603. .fontSize(14)
  7604. .fontColor(Color.White)
  7605. Slider({
  7606. value: this.pipLyHeight,
  7607. min: 10,
  7608. max: 1000,
  7609. step: 1,
  7610. style: SliderStyle.OutSet
  7611. })
  7612. .blockColor(this.themeColor)
  7613. .trackColor($r('app.color.speed_text_color'))
  7614. .selectedColor(Color.White)
  7615. .trackThickness(6)
  7616. .onChange((value: number) => {
  7617. this.pipLyHeight = value
  7618. if (this.pipController) {
  7619. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  7620. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  7621. }
  7622. })
  7623. .width('76%')
  7624. }
  7625. .margin({
  7626. left: 20,
  7627. right: 15,
  7628. top: 5,
  7629. bottom: 5
  7630. })
  7631. }
  7632. Row() {
  7633. Text(`歌词字号:`)
  7634. .fontSize(14)
  7635. .fontColor(Color.White)
  7636. Slider({
  7637. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  7638. min: 12,
  7639. max: 30,
  7640. step: 0.1,
  7641. style: SliderStyle.OutSet
  7642. })
  7643. .blockColor(this.themeColor)
  7644. .trackColor($r('app.color.speed_text_color'))
  7645. .selectedColor(Color.White)
  7646. .trackThickness(6)
  7647. .onChange((value: number) => {
  7648. this.setLyricTextSize(value, isPip)
  7649. })
  7650. .width('76%')
  7651. }
  7652. .margin({
  7653. left: 20,
  7654. right: 15,
  7655. top: 5,
  7656. bottom: 5
  7657. })
  7658. Row() {
  7659. Text(`高亮倍数:`)
  7660. .fontSize(14)
  7661. .fontColor(Color.White)
  7662. Slider({
  7663. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  7664. min: 1,
  7665. max: 2,
  7666. step: 0.1,
  7667. style: SliderStyle.OutSet
  7668. })
  7669. .blockColor(this.themeColor)
  7670. .trackColor($r('app.color.speed_text_color'))
  7671. .selectedColor(Color.White)
  7672. .trackThickness(6)
  7673. .onChange((value: number) => {
  7674. this.setHighLyricTextSize(value, isPip)
  7675. })
  7676. .width('76%')
  7677. }
  7678. .margin({
  7679. left: 20,
  7680. right: 15,
  7681. top: 5,
  7682. bottom: 5
  7683. })
  7684. Row() {
  7685. Text(`歌词间隙:`)
  7686. .fontSize(14)
  7687. .fontColor(Color.White)
  7688. Slider({
  7689. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  7690. min: 0,
  7691. max: 100,
  7692. step: 1,
  7693. style: SliderStyle.OutSet
  7694. })
  7695. .blockColor(this.themeColor)
  7696. .trackColor($r('app.color.speed_text_color'))
  7697. .selectedColor(Color.White)
  7698. .trackThickness(6)
  7699. .onChange((value: number) => {
  7700. this.setLyricLineSpace(value, isPip)
  7701. })
  7702. .width('76%')
  7703. }
  7704. .margin({
  7705. left: 20,
  7706. right: 15,
  7707. top: 5,
  7708. bottom: 5
  7709. })
  7710. //取值间隔为100,默认为400,取值越大,字体越粗
  7711. Row() {
  7712. Text(`歌词字重:`)
  7713. .fontSize(14)
  7714. .fontColor(Color.White)
  7715. Slider({
  7716. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  7717. min: 100,
  7718. max: 900,
  7719. step: 100,
  7720. style: SliderStyle.OutSet
  7721. })
  7722. .blockColor(this.themeColor)
  7723. .trackColor($r('app.color.speed_text_color'))
  7724. .selectedColor(Color.White)
  7725. .trackThickness(6)
  7726. .onChange((value: number) => {
  7727. if (isPip) {
  7728. this.lyricTextWeightPip = value
  7729. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  7730. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  7731. } else {
  7732. this.lyricTextWeight = value
  7733. this.lyricController.setTextWeight(this.lyricTextWeight)
  7734. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  7735. }
  7736. })
  7737. .width('76%')
  7738. }
  7739. .margin({
  7740. left: 20,
  7741. right: 15,
  7742. top: 5,
  7743. bottom: 5
  7744. })
  7745. if (!isPip) {
  7746. Row() {
  7747. Text(`歌词模糊:`)
  7748. .fontSize(14)
  7749. .fontColor(Color.White)
  7750. Slider({
  7751. value: isPip ? this.blurDegreePip : this.blurDegree,
  7752. min: 0,
  7753. max: 5,
  7754. step: 0.1,
  7755. style: SliderStyle.OutSet
  7756. })
  7757. .blockColor(this.themeColor)
  7758. .trackColor($r('app.color.speed_text_color'))
  7759. .selectedColor(Color.White)
  7760. .trackThickness(6)
  7761. .onChange((value: number) => {
  7762. this.setBlurDegree(value, isPip)
  7763. })
  7764. .width('76%')
  7765. }
  7766. .margin({
  7767. left: 20,
  7768. right: 15,
  7769. top: 5,
  7770. bottom: 15
  7771. })
  7772. }
  7773. Row() {
  7774. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  7775. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  7776. }
  7777. .justifyContent(FlexAlign.Center)
  7778. .margin({ top: 3, bottom: 10 })
  7779. }
  7780. }
  7781. private setBlurDegree(index: number, isPip: boolean) {
  7782. if (isPip) {
  7783. this.blurDegreePip = index
  7784. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  7785. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  7786. } else {
  7787. this.blurDegree = index
  7788. this.lyricController.setBlurDegree(this.blurDegree)
  7789. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  7790. }
  7791. }
  7792. private setLyricAlignMode(index: number, isPip: boolean) {
  7793. if (isPip) {
  7794. this.currentLyricAlignModePip = index
  7795. if (this.currentLyricAlignModePip === 1) {
  7796. this.lyricControllerXF.setAlignMode("left")
  7797. } else {
  7798. this.lyricControllerXF.setAlignMode("center")
  7799. }
  7800. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  7801. } else {
  7802. this.currentLyricAlignMode = index
  7803. if (this.currentLyricAlignMode === 1) {
  7804. this.lyricController.setAlignMode("left")
  7805. } else {
  7806. this.lyricController.setAlignMode("center")
  7807. }
  7808. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  7809. }
  7810. }
  7811. private setLyricTextSize(index: number, isPip: boolean) {
  7812. if (isPip) {
  7813. this.currentLyricSizePip = index
  7814. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  7815. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  7816. } else {
  7817. this.currentLyricSize = index
  7818. this.lyricController.setTextSize(this.currentLyricSize)
  7819. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  7820. }
  7821. }
  7822. private setHighLyricTextSize(scale: number, isPip: boolean) {
  7823. if (isPip) {
  7824. this.currentHightLyricSizePip = scale
  7825. this.lyricControllerXF
  7826. .setHighlightScale(this.currentHightLyricSizePip)
  7827. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  7828. } else {
  7829. this.currentHightLyricSize = scale
  7830. this.lyricController
  7831. .setHighlightScale(this.currentHightLyricSize)
  7832. PreferencesUtil.putSync('HighLyricTextSize', scale)
  7833. }
  7834. }
  7835. private setLyricLineSpace(index: number, isPip: boolean) {
  7836. if (isPip) {
  7837. this.currentLyricLineSpacePip = index
  7838. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  7839. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  7840. } else {
  7841. this.currentLyricLineSpace = index
  7842. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  7843. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  7844. }
  7845. }
  7846. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  7847. LogUtil.info('onecold isBG = ' + isBG)
  7848. if (isBG) { //如果是设置悬浮背景
  7849. this.pipBg = color
  7850. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  7851. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  7852. return
  7853. }
  7854. if (isPip) {
  7855. this.currentLyricColorPip = color
  7856. this.lyricControllerXF
  7857. .setTextColor(this.currentLyricColorPip)
  7858. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  7859. } else {
  7860. this.currentLyricColor = color
  7861. this.lyricController
  7862. .setTextColor(this.currentLyricColor)
  7863. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  7864. }
  7865. }
  7866. private changeLyricHightLightColor(color: string, isPip: boolean) {
  7867. if (isPip) {
  7868. this.currentHighLightLyricColorPip = color
  7869. this.lyricControllerXF
  7870. .setHighlightColor(this.currentHighLightLyricColorPip)
  7871. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  7872. } else {
  7873. this.currentHighLightLyricColor = color
  7874. this.lyricController
  7875. .setHighlightColor(this.currentHighLightLyricColor)
  7876. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  7877. }
  7878. }
  7879. // 构建时间控制器
  7880. @Builder
  7881. BuildTimeControls() {
  7882. Column() {
  7883. // 时间显示
  7884. Text(this.getTimeText())
  7885. .fontSize(18)
  7886. .fontColor(Color.White)
  7887. .margin({ bottom: 10 })
  7888. Row() {
  7889. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  7890. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  7891. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  7892. }
  7893. .justifyContent(FlexAlign.Center)
  7894. }
  7895. .margin({ top: 12, bottom: 8 })
  7896. }
  7897. // 精度按钮组件
  7898. @Builder
  7899. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  7900. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7901. Column() {
  7902. Image(icon)
  7903. .width(28)
  7904. .margin({ bottom: 5 })
  7905. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  7906. Text(label)
  7907. .fontSize(12)
  7908. .fontColor('#FFFFFF')
  7909. }
  7910. }
  7911. .backgroundColor(Color.Transparent)
  7912. .enabled(!this.isButtonDisabled(step))
  7913. .onClick(() => this.handlePrecisionAdjust(step))
  7914. .padding(5)
  7915. .width(66)
  7916. .height(66)
  7917. .margin({ left: 18, right: 18 })
  7918. .border({
  7919. color: '#FFFFFF',
  7920. width: 1.8
  7921. })
  7922. }
  7923. private handlePrecisionAdjust(step: number) {
  7924. if (step === 0) {
  7925. this.timeOffset = 0
  7926. return
  7927. }
  7928. // 精度处理:保留1位小数
  7929. const newOffset = Number((this.timeOffset + step).toFixed(5))
  7930. // 边界保护(±15.0秒)
  7931. if (newOffset < -30.0 || newOffset > 30.0) {
  7932. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  7933. return
  7934. }
  7935. // 状态更新
  7936. this.timeOffset = newOffset
  7937. }
  7938. // 按钮禁用逻辑
  7939. private isButtonDisabled(step: number): boolean {
  7940. const futureOffset = this.timeOffset + step
  7941. return (futureOffset < -30.0) || (futureOffset > 30.0)
  7942. }
  7943. // 时间显示文本升级
  7944. private getTimeText(): string {
  7945. const absValue = Math.abs(this.timeOffset)
  7946. return this.timeOffset === 0
  7947. ? '歌词时间已重置'
  7948. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  7949. }
  7950. // 导入 本地歌词 搜索歌词
  7951. @Builder
  7952. pushLyricButton(icon: Resource, step: number, label: string) {
  7953. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7954. Row() {
  7955. Image(icon)
  7956. .width(14)
  7957. .margin({ left: 13 })
  7958. Text(label)
  7959. .fontSize(12)
  7960. .margin({ left: 6 })
  7961. .fontColor('#FFFFFF')
  7962. }
  7963. }
  7964. .onClick(() => {
  7965. switch (step) {
  7966. case 0:
  7967. this.callFilePickerSelectFileForLyric()
  7968. break;
  7969. case 1:
  7970. //判断有没有设置api
  7971. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  7972. this.isLyricSetting = false
  7973. this.showTipsDialog()
  7974. return
  7975. }
  7976. if (StrUtil.isNotEmpty(this.videoUrl)) {
  7977. ToastUtil.showToast('正在获取')
  7978. this.isLyricSetting = false
  7979. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  7980. this.initLyric(lyricPath, true);
  7981. }
  7982. break;
  7983. }
  7984. })
  7985. .padding(5)
  7986. .width(110)
  7987. .backgroundColor(Color.Transparent)
  7988. .height(40)
  7989. .margin({ left: 6, right: 6 })
  7990. .border({
  7991. color: '#FFFFFF',
  7992. radius: 20,
  7993. width: 1.8
  7994. })
  7995. }
  7996. showVipDialog() {
  7997. DialogHelper.showCustomContentDialog({
  7998. dialogId: 'vip',
  7999. title: "友情提示",
  8000. autoCancel: false, //点击遮障层时,不关闭弹窗
  8001. backCancel: true, //点击返回键,不关闭弹窗
  8002. contentBuilder: () => {
  8003. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  8004. },
  8005. buttons: [],
  8006. })
  8007. }
  8008. //去赞助的自定义内容
  8009. @Builder
  8010. customVipBuilder(content: string) {
  8011. Column() {
  8012. Text(content)
  8013. .fontColor(Color.Gray)
  8014. .fontSize(16)
  8015. .alignSelf(ItemAlign.Start)
  8016. .margin({ bottom: 15 })
  8017. .fontSize(16)
  8018. Row() {
  8019. Button('取消')
  8020. .fontColor(Color.White)
  8021. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  8022. .height(50)
  8023. .layoutWeight(1)
  8024. .stateEffect(true)
  8025. .margin({ right: 6 })
  8026. .onClick(() => {
  8027. DialogHelper.closeDialog('vip'); //关闭弹框
  8028. })
  8029. Button('开通')
  8030. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  8031. .layoutWeight(1)
  8032. .height(50)
  8033. .backgroundColor(this.themeColor)
  8034. .stateEffect(true)
  8035. .margin({ left: 6 })
  8036. .onClick(() => {
  8037. DialogHelper.closeDialog('vip'); //关闭弹框
  8038. this.isShowPlay = false
  8039. this.mType = 1 //跳转到用户中心
  8040. // router.pushUrl({
  8041. // url: 'pages/VipPage'
  8042. // }, router.RouterMode.Single);
  8043. })
  8044. }
  8045. }
  8046. .width("100%")
  8047. .padding(10)
  8048. }
  8049. showTipsDialog() {
  8050. DialogHelper.showCustomContentDialog({
  8051. dialogId: 'tips',
  8052. title: "友情提示",
  8053. autoCancel: false, //点击遮障层时,不关闭弹窗
  8054. backCancel: true, //点击返回键,不关闭弹窗
  8055. contentBuilder: () => {
  8056. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  8057. },
  8058. buttons: [],
  8059. })
  8060. }
  8061. @Builder
  8062. customTipsBuilder(content: string) {
  8063. Column() {
  8064. Text(content)
  8065. .fontColor(Color.Gray)
  8066. .fontSize(16)
  8067. .alignSelf(ItemAlign.Start)
  8068. .margin({ bottom: 15 })
  8069. .fontSize(16)
  8070. Row() {
  8071. Button('取消')
  8072. .fontColor(Color.White)
  8073. .backgroundColor(this.themeColor)
  8074. .height(50)
  8075. .layoutWeight(1)
  8076. .stateEffect(true)
  8077. .margin({ right: 6 })
  8078. .onClick(() => {
  8079. DialogHelper.closeDialog('tips'); //关闭弹框
  8080. })
  8081. Button('跳转')
  8082. .fontColor(Color.White)//
  8083. .layoutWeight(1)
  8084. .height(50)
  8085. .backgroundColor(this.themeColor)
  8086. .stateEffect(true)
  8087. .margin({ left: 6 })
  8088. .onClick(() => {
  8089. DialogHelper.closeDialog('tips'); //关闭弹框
  8090. this.isShowEdit = false
  8091. this.longItemFilePath = ''
  8092. // if(this.isGridMusic&&!this.isShowPlay){
  8093. // this.longItemFilePath== ''
  8094. // }else{
  8095. // this.isShowEdit = false
  8096. // }
  8097. this.isShowPlay = false
  8098. this.mType = 3
  8099. // router.pushUrl({
  8100. // url: 'pages/SettingPage'
  8101. // }, router.RouterMode.Single);
  8102. })
  8103. }
  8104. }
  8105. .width("100%")
  8106. .padding(10)
  8107. }
  8108. @Builder
  8109. PlayMoreSheet() {
  8110. Column() {
  8111. this.MoreList()
  8112. }
  8113. .width('100%')
  8114. .height('100%')
  8115. }
  8116. @Builder
  8117. MoreList() {
  8118. Scroll() {
  8119. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  8120. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  8121. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8122. Row() {
  8123. if (more.id === 3&&this.currentSong) {
  8124. Image(more.image)
  8125. .width(24)
  8126. .height(24)
  8127. .margin({ left: 10, right: 10 })
  8128. Text(more.title)
  8129. .fontSize(16)
  8130. .fontColor(Color.White)
  8131. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  8132. height: this.isCoverOpacity() ? '95%' : '95%',
  8133. dragBar: true,
  8134. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8135. showClose: true,
  8136. blurStyle: BlurStyle.Thin,
  8137. backgroundColor: Color.Transparent,
  8138. title: { title: '歌曲信息' }
  8139. })
  8140. } else if (more.id === 15 && this.currentSong) { //编辑标签
  8141. Image(more.image)
  8142. .width(24)
  8143. .height(24)
  8144. .margin({ left: 10, right: 10 })
  8145. Text(more.title)
  8146. .fontSize(16)
  8147. .fontColor(Color.White)
  8148. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  8149. height: '99%',
  8150. dragBar: true,
  8151. showClose: true,
  8152. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8153. // blurStyle:BlurStyle.Thin,
  8154. // backgroundColor:Color.Transparent,
  8155. title: { title: '编辑标签' }
  8156. })
  8157. } else if (more.id === 5) { //定时关闭
  8158. Image(more.image)
  8159. .width(24)
  8160. .height(24)
  8161. .margin({ left: 10, right: 10 })
  8162. Text(more.title)
  8163. .fontSize(16)
  8164. .fontColor(Color.White)
  8165. .onClick(() => {
  8166. this.doMore(more.id)
  8167. })
  8168. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  8169. height: this.isCoverOpacity() ? '95%' : '95%',
  8170. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8171. dragBar: true,
  8172. showClose: true,
  8173. title: { title: $r('app.string.time_close') }
  8174. })
  8175. } else if (more.id === 2) { //歌词设置
  8176. Image(more.image)
  8177. .width(24)
  8178. .height(24)
  8179. .margin({ left: 10, right: 10 })
  8180. Text(more.title)
  8181. .fontSize(16)
  8182. .fontColor(Color.White)
  8183. } else if (more.id === 16) { //悬浮歌词设置
  8184. Image(more.image)
  8185. .width(24)
  8186. .height(24)
  8187. .margin({ left: 10, right: 10 })
  8188. Text(more.title)
  8189. .fontSize(16)
  8190. .fontColor(Color.White)
  8191. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  8192. height: this.isCoverOpacity() ? '95%' : '95%',
  8193. dragBar: true,
  8194. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8195. showClose: true,
  8196. blurStyle: BlurStyle.Thin,
  8197. backgroundColor: Color.Transparent,
  8198. title: { title: '悬浮歌词' }
  8199. })
  8200. } else if (more.id === 11) {
  8201. Image(more.image)
  8202. .width(24)
  8203. .height(24)
  8204. .margin({ left: 10, right: 10 })
  8205. Text(more.title)
  8206. .fontSize(16)
  8207. .fontColor(Color.White)
  8208. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  8209. height: this.isCoverOpacity() ? '95%' : '60%',
  8210. dragBar: true,
  8211. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8212. showClose: true,
  8213. blurStyle: BlurStyle.Thin,
  8214. backgroundColor: Color.Transparent,
  8215. title: { title: '跳过头尾' }
  8216. })
  8217. } else if (more.id === 12) { //投播
  8218. AVCastPicker({
  8219. customPicker: (): void => this.TPImageBuilder(more),
  8220. onStateChange: (state) => {
  8221. if (state == AVCastPickerState.STATE_APPEARING) {
  8222. console.log(' The picker starts showing.');
  8223. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  8224. console.log(' The picker finishes presenting.');
  8225. }
  8226. },
  8227. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  8228. sessionType: 'video'
  8229. })
  8230. .id('AVCastPicker')
  8231. } else {
  8232. Image(more.image)
  8233. .width(24)
  8234. .height(24)
  8235. .margin({ left: 10, right: 10 })
  8236. .onClick(() => {
  8237. this.doMore(more.id)
  8238. })
  8239. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  8240. .fontSize(16)
  8241. .fontColor(Color.White)
  8242. .onClick(() => {
  8243. this.doMore(more.id)
  8244. })
  8245. Select([//倍速
  8246. { value: '0.25x' },
  8247. { value: '0.5x' },
  8248. { value: '0.75x' },
  8249. { value: '1x' },
  8250. { value: '1.25x' },
  8251. { value: '1.5x' },
  8252. { value: '1.75x' },
  8253. { value: '2x' },
  8254. { value: '3x' }])
  8255. .font({ size: 16, weight: FontWeight.Medium })
  8256. .fontColor($r('sys.color.white'))
  8257. .margin({ left: 25 })
  8258. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  8259. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  8260. .value(Utility.optimizedFormat(this.playSpeed))
  8261. .onSelect(async (_index: number, text?: string | undefined) => {
  8262. let speed = parseFloat(text?.replace('x', '') || '1');
  8263. if (!CommonConstants.video_speed_list.includes(speed)) {
  8264. speed = 1;
  8265. }
  8266. this.playSpeed = speed
  8267. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  8268. })
  8269. Slider({
  8270. value: this.volume,
  8271. min: 0,
  8272. max: 1,
  8273. step: 0.1,
  8274. style: SliderStyle.OutSet
  8275. })
  8276. .margin({ left: 18, right: 8 })
  8277. .blockColor(this.themeColor)
  8278. .trackColor($r('app.color.speed_text_color'))
  8279. .selectedColor(Color.White)
  8280. .trackThickness(9)
  8281. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  8282. .onChange((value: number) => {
  8283. this.volume = value;
  8284. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  8285. PreferencesUtil.putSync('DefalutVolume',this.volume)
  8286. })
  8287. .layoutWeight(1)
  8288. Blank()
  8289. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  8290. .selectedColor(this.themeColor)
  8291. .switchPointColor(Color.White)
  8292. .margin({ right: 15 })
  8293. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8294. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  8295. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  8296. if (more.id == 6) {
  8297. this.isMusicMemoryPlay = checked;
  8298. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  8299. if (this.isMusicMemoryPlay) {
  8300. ToastUtil.showToast('记忆播放已开启')
  8301. } else {
  8302. ToastUtil.showToast('记忆播放已关闭')
  8303. }
  8304. }
  8305. })
  8306. .width(48)
  8307. .height(24);
  8308. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  8309. .selectedColor(this.themeColor)
  8310. .switchPointColor(Color.White)
  8311. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8312. .margin({ right: 15 })
  8313. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  8314. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  8315. if (more.id == 7) {
  8316. this.isMusicBGCover = checked;
  8317. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  8318. if (this.isMusicBGCover) {
  8319. ToastUtil.showToast('播放背景随音乐封面已开启')
  8320. } else {
  8321. ToastUtil.showToast('播放背景随音乐封面已关闭')
  8322. }
  8323. }
  8324. })
  8325. .width(48)
  8326. .height(24);
  8327. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  8328. .selectedColor(this.themeColor)
  8329. .switchPointColor(Color.White)
  8330. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8331. .margin({ right: 15 })
  8332. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  8333. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  8334. if (more.id == 8) {
  8335. this.isSavePlayMode = checked;
  8336. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  8337. if (this.isSavePlayMode) {
  8338. ToastUtil.showToast('保存播放模式已开启')
  8339. } else {
  8340. ToastUtil.showToast('保存播放模式已关闭')
  8341. }
  8342. }
  8343. })
  8344. .width(48)
  8345. .height(24);
  8346. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  8347. .selectedColor(this.themeColor)
  8348. .switchPointColor(Color.White)
  8349. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8350. .margin({ right: 15 })
  8351. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  8352. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  8353. if (more.id == 13) {
  8354. this.isCoverRectangle = checked;
  8355. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  8356. if (this.isCoverRectangle) {
  8357. ToastUtil.showToast('封面方形已开启')
  8358. this.animationRoFun()
  8359. } else {
  8360. ToastUtil.showToast('封面圆形已开启')
  8361. this.animationRoFun()
  8362. }
  8363. }
  8364. })
  8365. .width(48)
  8366. .height(24);
  8367. }
  8368. }
  8369. .width('100%')
  8370. .height(45)
  8371. .padding(15)
  8372. .backgroundColor(Color.Transparent)
  8373. .borderRadius(12)
  8374. .margin({ bottom: 6 })
  8375. }
  8376. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  8377. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  8378. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  8379. .backgroundColor(Color.Transparent)
  8380. .onClick(() => {
  8381. this.doMore(more.id)
  8382. })
  8383. });
  8384. }
  8385. .width('100%')
  8386. .padding(16)
  8387. }.margin({ bottom: 18 })
  8388. }
  8389. @Builder
  8390. TPImageBuilder(more: MoreItem): void {
  8391. Row() {
  8392. Image($r('app.media.tuoping'))
  8393. .width(22)
  8394. .height(22)
  8395. .margin({ left: 10, right: 10 })
  8396. Text(more.title)
  8397. .fontSize(16)
  8398. .fontColor(Color.White)
  8399. }
  8400. .width('100%')
  8401. .layoutWeight(1)
  8402. .alignItems(VerticalAlign.Center)
  8403. .justifyContent(FlexAlign.Start)
  8404. }
  8405. private moreItems: MoreItem[] = [
  8406. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  8407. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  8408. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  8409. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  8410. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  8411. // { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  8412. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  8413. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  8414. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  8415. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  8416. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  8417. { id: 4, image: $r('app.media.share2'), title: '分享' },
  8418. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  8419. { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  8420. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  8421. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  8422. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  8423. ];
  8424. @State isShowMoreView: boolean = false;
  8425. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  8426. @State isShowTimeCloseMore: boolean = false
  8427. @State isShowDetailMore: boolean = false
  8428. @State isMusicBGCover: boolean = true
  8429. @State isSavePlayMode: boolean = true
  8430. @State isLyricSetting: boolean = false
  8431. @State isJumpSetting: boolean = false
  8432. @State isShowEdit: boolean = false
  8433. @State showPipLyric: boolean = false
  8434. async setRingTone() {
  8435. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  8436. return
  8437. }
  8438. // 确定后的逻辑
  8439. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  8440. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  8441. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  8442. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  8443. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  8444. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  8445. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  8446. , this.videoUrl, this.name).then(res => {
  8447. LogUtil.info('onecold setFlag :' + res);
  8448. });
  8449. }
  8450. doMore(moreId: number) {
  8451. switch (moreId) {
  8452. case 2: //歌词
  8453. this.isLyricSetting = !this.isLyricSetting;
  8454. this.isShowMoreView = false
  8455. break;
  8456. case 3: //详情
  8457. this.isShowDetailMore = !this.isShowDetailMore;
  8458. break;
  8459. case 4: //分享
  8460. if (this.currentSong !== undefined) {
  8461. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  8462. }
  8463. this.isShowMoreView = false
  8464. break;
  8465. case 5: //定时关闭
  8466. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  8467. break;
  8468. case 10: //设为铃声
  8469. this.setRingTone()
  8470. this.isShowMoreView = false
  8471. break;
  8472. case 11: //跳过头尾
  8473. this.isJumpSetting = !this.isJumpSetting;
  8474. break;
  8475. case 13: //倍速
  8476. break;
  8477. case 14: //搜索封面
  8478. if (this.currentSong !== undefined) {
  8479. this.doSearchCover(this.currentSong)
  8480. }
  8481. this.isShowMoreView = false
  8482. break;
  8483. case 15: //编辑标签
  8484. this.setEditStrEmpty()
  8485. this.tempLyricContent = this.lyricContent
  8486. this.isShowEdit = !this.isShowEdit;
  8487. break;
  8488. case 16: //悬浮歌词
  8489. this.showPipLyric = !this.showPipLyric;
  8490. break;
  8491. case 17: //横屏模式
  8492. if (this.isLandscape) {
  8493. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  8494. } else {
  8495. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  8496. }
  8497. this.isShowMoreView = false
  8498. break;
  8499. }
  8500. }
  8501. /**
  8502. * 切换横竖屏
  8503. *
  8504. */
  8505. setOrientation(orientation: number) {
  8506. this.windowClass.setPreferredOrientation(orientation).then(() => {
  8507. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  8508. }).catch((err: BusinessError) => {
  8509. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  8510. });
  8511. }
  8512. /**
  8513. * 画中画功能(悬浮歌词功能)
  8514. *
  8515. */
  8516. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  8517. pipController?: PiPWindow.PiPController;
  8518. navigationId: string = '';
  8519. @State curState: string = '';
  8520. @State curError: ResourceStr = '';
  8521. @State pipBg: string = '#E8E8E8'
  8522. @State buttonAction: string = '';
  8523. //开启画中画功能
  8524. async startPip() {
  8525. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  8526. if (!this.pipController) {
  8527. await this.createPipController();
  8528. }
  8529. if (!this.pipController) {
  8530. Logger.info(`[${TAG}] pipController create error`);
  8531. return;
  8532. }
  8533. await this.pipController.startPiP();
  8534. }
  8535. async stopPip() {
  8536. if (!this.pipController) {
  8537. Logger.info(`[${TAG}] pipController is not exist`);
  8538. return;
  8539. }
  8540. this.isOpenPip = false
  8541. await this.pipController.stopPiP();
  8542. }
  8543. async createPipController() {
  8544. this.pipController = await PiPWindow.create({
  8545. context: getContext(this),
  8546. componentController: this.xcomponentController,
  8547. navigationId: this.navigationId,
  8548. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  8549. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  8550. customUIController: this.nodeController,
  8551. });
  8552. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  8553. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  8554. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  8555. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  8556. this.onStateChange(state, reason);
  8557. });
  8558. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  8559. this.onActionEvent(event, status);
  8560. });
  8561. }
  8562. destroyPipController() {
  8563. if (!this.pipController) {
  8564. return;
  8565. }
  8566. this.pipController.off('stateChange');
  8567. this.pipController.off('controlPanelActionEvent');
  8568. this.pipController = undefined;
  8569. }
  8570. onStateChange(state: PiPWindow.PiPState, reason: string) {
  8571. switch (state) {
  8572. case PiPWindow.PiPState.ABOUT_TO_START:
  8573. this.curState = 'ABOUT_TO_START';
  8574. this.curError = $r('app.string.current_error_hint');
  8575. break;
  8576. case PiPWindow.PiPState.STARTED:
  8577. this.curState = 'STARTED';
  8578. this.curError = $r('app.string.current_error_hint');
  8579. break;
  8580. case PiPWindow.PiPState.ABOUT_TO_STOP:
  8581. this.curState = 'ABOUT_TO_STOP';
  8582. this.curError = $r('app.string.current_error_hint');
  8583. break;
  8584. case PiPWindow.PiPState.STOPPED:
  8585. this.curState = 'STOPPED';
  8586. this.curError = $r('app.string.current_error_hint');
  8587. this.stopPip()
  8588. this.destroyPipController()
  8589. break;
  8590. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  8591. this.curState = 'ABOUT_TO_RESTORE';
  8592. this.curError = $r('app.string.current_error_hint');
  8593. break;
  8594. case PiPWindow.PiPState.ERROR:
  8595. this.curState = 'ERROR';
  8596. this.curError = reason;
  8597. break;
  8598. default:
  8599. break;
  8600. }
  8601. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  8602. }
  8603. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  8604. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  8605. switch (event) {
  8606. case 'playbackStateChanged':
  8607. if (status === 0) {
  8608. this.pause();
  8609. } else {
  8610. this.startPlayOrResumePlay();
  8611. }
  8612. break;
  8613. case 'nextVideo':
  8614. // 切换到下一个视频
  8615. this.playNext()
  8616. break;
  8617. case 'previousVideo':
  8618. // 切换到上一个视频
  8619. this.playPrevious()
  8620. break;
  8621. case 'previousVideo':
  8622. // 切换到上一个视频
  8623. this.playPrevious()
  8624. break;
  8625. default:
  8626. }
  8627. this.buttonAction = event + `-status:${status}`;
  8628. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  8629. }
  8630. /**
  8631. * 画中画功能(悬浮歌词功能)结束
  8632. *
  8633. */
  8634. async doSearchCover(item: VideoItem): Promise<string> {
  8635. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  8636. this.isShowMoreView = false;
  8637. this.showTipsDialog();
  8638. return ''; // Return empty string when no API is configured
  8639. }
  8640. if (!item) {
  8641. return ''; // Return empty string if item is undefined
  8642. }
  8643. const artist = item?.artist || ''; // Use empty string if artist is missing
  8644. return this.searchCover(item, item.name, artist); // Await is not needed here as we return the promise directly
  8645. }
  8646. /**
  8647. *api搜索封面
  8648. *item,根据title和artist
  8649. */
  8650. searchCover(item: VideoItem, title: string, artist: string): Promise<string> {
  8651. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  8652. LogUtil.debug("onecold res =" + res);
  8653. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  8654. if (item.filePath == this.currentSong?.filePath) {
  8655. this.cover = res;
  8656. if (this.currentSong) {
  8657. this.currentSong.pixelMapPath = res;
  8658. }
  8659. }
  8660. // Update pixel map path but always return res regardless of success
  8661. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  8662. if (success) {
  8663. this.doUpdateData();
  8664. console.log("onecold 更新音乐封面成功,数据库已同步");
  8665. } else {
  8666. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  8667. }
  8668. // Note: We don't resolve/reject here because we already returned res
  8669. });
  8670. LogUtil.debug("onecold this.cover =" + this.cover);
  8671. }
  8672. return res; // Always return res regardless of updatePixelMapPath result
  8673. });
  8674. }
  8675. @State jumpTopTime: number = 0
  8676. @State jumpEndTime: number = 0
  8677. @State isOpenJump: boolean = false
  8678. @Builder
  8679. JumpTopEndSheet() {
  8680. Scroll() {
  8681. Column() {
  8682. Column() {
  8683. Text('仅对本播放列表有效')
  8684. .fontSize(16)
  8685. .fontColor($r('app.color.text_color'))
  8686. // 跳过头尾
  8687. Column() {
  8688. Row() {
  8689. Text('跳过片头:')
  8690. .fontSize(16)
  8691. .fontColor($r('app.color.text_color'))
  8692. Text(this.jumpTopTime + 's')
  8693. .fontSize(16)
  8694. .fontColor($r('app.color.text_color'))
  8695. }
  8696. .margin({ bottom: 5 })
  8697. Row() {
  8698. Slider({
  8699. value: this.jumpTopTime,
  8700. min: 0,
  8701. max: 120,
  8702. step: 1,
  8703. style: SliderStyle.OutSet
  8704. })
  8705. .blockColor(this.themeColor)
  8706. .trackColor($r('app.color.speed_text_color'))
  8707. .selectedColor(Color.White)
  8708. .trackThickness(8)
  8709. .onChange((value: number) => {
  8710. this.jumpTopTime = value;
  8711. })
  8712. .width('85%')
  8713. }
  8714. .alignItems(VerticalAlign.Top)
  8715. }
  8716. .margin({ top: 10, bottom: 10 })
  8717. // 跳过头尾
  8718. Column() {
  8719. Row() {
  8720. Text('跳过片尾:')
  8721. .fontSize(16)
  8722. .fontColor($r('app.color.text_color'))
  8723. Text(this.jumpEndTime + 's')
  8724. .fontSize(16)
  8725. .fontColor($r('app.color.text_color'))
  8726. }
  8727. .margin({ bottom: 5 })
  8728. Row() {
  8729. Slider({
  8730. value: this.jumpEndTime,
  8731. min: 0,
  8732. max: 120,
  8733. step: 1,
  8734. style: SliderStyle.OutSet
  8735. })
  8736. .blockColor(this.themeColor)
  8737. .trackColor($r('app.color.speed_text_color'))
  8738. .selectedColor(Color.White)
  8739. .trackThickness(8)
  8740. .onChange((value: number) => {
  8741. this.jumpEndTime = value;
  8742. })
  8743. .width('85%')
  8744. }
  8745. .alignItems(VerticalAlign.Top)
  8746. }
  8747. .margin({ top: 10, bottom: 10 })
  8748. Row() {
  8749. Button('保存设置')
  8750. .fontColor(Color.White)
  8751. .layoutWeight(1)
  8752. .height(40)
  8753. .width(80)
  8754. .backgroundColor(this.themeColor)
  8755. .stateEffect(true)
  8756. .margin({ left: 0, bottom: 20 })
  8757. .onClick(async () => {
  8758. if (!Utility.isNoble()) {
  8759. this.isJumpSetting = false
  8760. this.isShowMoreView = false
  8761. this.showVipDialog()
  8762. return
  8763. }
  8764. if (this.currentSong === undefined) {
  8765. return
  8766. }
  8767. if (this.modeType === 0) {
  8768. let parentPath = FileUtil.getParentPath(this.videoUrl)
  8769. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  8770. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  8771. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  8772. } else if (this.modeType === 1) { //媒体库
  8773. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  8774. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  8775. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  8776. } else if (this.modeType === 2) { //艺术家
  8777. if (this.currentSong?.artist) {
  8778. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  8779. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  8780. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  8781. }
  8782. } else if (this.modeType === 3) { //专辑
  8783. if (this.currentSong?.album) {
  8784. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  8785. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  8786. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  8787. }
  8788. }
  8789. ToastUtil.showShort("保存成功")
  8790. this.isJumpSetting = false
  8791. })
  8792. }
  8793. .margin({
  8794. left: 38,
  8795. right: 38,
  8796. top: 10,
  8797. bottom: 10
  8798. })
  8799. .width(120)
  8800. .height(50)
  8801. }
  8802. }
  8803. }
  8804. .width('100%')
  8805. .height('100%')
  8806. }
  8807. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  8808. private onStateVastChange(state: AVCastPickerState) {
  8809. if (state == AVCastPickerState.STATE_APPEARING) {
  8810. console.log('The picker starts showing.');
  8811. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  8812. console.log('The picker finishes presenting.');
  8813. }
  8814. }
  8815. private showSelectLyric() {
  8816. DialogHelper.showActionSheetDialog({
  8817. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  8818. // sheets: ["本地歌词", "搜索歌词"],
  8819. sheets: [
  8820. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  8821. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  8822. ],
  8823. maskColor: Color.Transparent,
  8824. backgroundColor: $r('app.color.bg_card'),
  8825. transition: AnimationHelper.transitionInDown(666),
  8826. onAction: (index) => {
  8827. switch (index) {
  8828. case 0:
  8829. this.callFilePickerSelectFileForLyric()
  8830. break;
  8831. case 1:
  8832. if (StrUtil.isNotEmpty(this.videoUrl)) {
  8833. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  8834. this.initLyric(lyricPath);
  8835. }
  8836. break;
  8837. }
  8838. }
  8839. })
  8840. }
  8841. // 拉起picker选择文件管理器
  8842. async callFilePickerSelectFileForLyric(): Promise<void> {
  8843. try {
  8844. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  8845. DocumentSelectOptions.maxSelectNumber = 1
  8846. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  8847. let documentPicker = new picker.DocumentViewPicker();
  8848. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  8849. Logger.info(TAG,
  8850. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  8851. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  8852. this.saveVideoDatasLyric(DocumentSelectResult)
  8853. }
  8854. }).catch((err: BusinessError) => {
  8855. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  8856. });
  8857. } catch (err) {
  8858. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  8859. }
  8860. }
  8861. async saveVideoDatasLyric(uris: string[]) {
  8862. if (ArrayUtil.isEmpty(uris)) {
  8863. return
  8864. }
  8865. let newUris: string[] = [];
  8866. for (let i = 0; i < uris.length; i++) {
  8867. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  8868. Logger.info(TAG, 'filePath uri: ' + filePath);
  8869. newUris.push(filePath)
  8870. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  8871. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  8872. fileIo.copyFileSync(file.fd, file2.fd)
  8873. fileIo.closeSync(file);
  8874. fileIo.closeSync(file2);
  8875. this.initLyric(filePath)
  8876. }
  8877. }
  8878. private initDelayPlay(context: object) {
  8879. this.mContext = context;
  8880. }
  8881. startPipLyric() {
  8882. if (this.pipController) {
  8883. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  8884. PiPWindow.PiPControlStatus.PLAY);
  8885. }
  8886. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  8887. if (this.isOpenPip) {
  8888. this.startPip()
  8889. } else {
  8890. this.stopPip()
  8891. }
  8892. }
  8893. private startPlayOrResumePlay() {
  8894. this.startPipLyric()
  8895. this.mDestroyPage = false;
  8896. this.animationState = AnimationStatus.Running
  8897. LogUtils.getInstance().LOGI("startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  8898. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  8899. this.stopProgressTask();
  8900. this.startProgressTask();
  8901. this.play(this.videoUrl.toString());
  8902. }
  8903. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  8904. this.mIjkMediaPlayer.start();
  8905. this.setProgress()
  8906. this.CONTROL_PlayStatus = PlayStatus.PLAY
  8907. }
  8908. this.setIsPlaying(true)
  8909. this.updateSessionPlayState(true)
  8910. this.watchStatus();
  8911. this.updateLastPlayTimeStr(this.videoUrl)
  8912. }
  8913. updateLastPlayTimeStr(filePath: string) {
  8914. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  8915. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  8916. if (success) {
  8917. this.getHistoryList(false)
  8918. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  8919. } else {
  8920. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  8921. }
  8922. });
  8923. }
  8924. private completionNum(num: number): string | number {
  8925. if (num < 10) {
  8926. return '0' + num;
  8927. } else {
  8928. return num;
  8929. }
  8930. }
  8931. private stringForTime(timeMs: number): string {
  8932. let totalSeconds: number | string = (timeMs / 1000);
  8933. let newSeconds: number | string = totalSeconds % 60;
  8934. let minutes: number | string = (totalSeconds / 60) % 60;
  8935. let hours: number | string = totalSeconds / 3600;
  8936. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  8937. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  8938. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  8939. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  8940. if (this.isCurrentTime) {
  8941. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  8942. this.oldSeconds = newSeconds
  8943. } else {
  8944. newSeconds = this.oldSeconds
  8945. }
  8946. }
  8947. newSeconds = this.completionNum(newSeconds);
  8948. if (hours > 0) {
  8949. return hours + ":" + minutes + ":" + newSeconds;
  8950. } else {
  8951. return minutes + ":" + newSeconds;
  8952. }
  8953. }
  8954. private setProgress() {
  8955. let position = this.mIjkMediaPlayer.getCurrentPosition();
  8956. let duration = this.mIjkMediaPlayer.getDuration();
  8957. let pos = 0;
  8958. if (duration > 0) {
  8959. this.slideEnable = true;
  8960. let curPercent = position / duration;
  8961. pos = curPercent * 100;
  8962. if (pos > this.PROGRESS_MAX_VALUE) {
  8963. this.progressValue = this.PROGRESS_MAX_VALUE
  8964. } else {
  8965. this.progressValue = pos;
  8966. }
  8967. }
  8968. // LogUtils.getInstance()
  8969. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  8970. this.totalTime = this.stringForTime(duration);
  8971. if (position > duration) {
  8972. position = duration;
  8973. }
  8974. this.isCurrentTime = true;
  8975. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  8976. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  8977. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  8978. this.currentTime = this.stringForTime(position);
  8979. this.isCurrentTime = false
  8980. if (this.mIjkMediaPlayer.isPlaying()) {
  8981. this.randomColor =
  8982. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  8983. // 判断是否播放到结束时间
  8984. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  8985. if (position >= duration - this.jumpEndTime * 1000) {
  8986. this.playNext()
  8987. }
  8988. }
  8989. } else {
  8990. this.randomColor = 'rbg(0,0,0)'
  8991. }
  8992. }
  8993. private startProgressTask() {
  8994. let that = this;
  8995. this.updateProgressTimer = setInterval(() => {
  8996. //LogUtils.getInstance().LOGI("startProgressTask");
  8997. if (!that.mDestroyPage) {
  8998. that.setProgress();
  8999. }
  9000. }, 300);
  9001. }
  9002. private stopProgressTask() {
  9003. LogUtils.getInstance().LOGI("stopProgressTask");
  9004. clearInterval(this.updateProgressTimer);
  9005. }
  9006. private showLoadIng() {
  9007. this.loadingVisible = Visibility.Visible;
  9008. this.replayVisible = Visibility.None;
  9009. }
  9010. private hideLoadIng() {
  9011. this.loadingVisible = Visibility.None;
  9012. this.replayVisible = Visibility.None;
  9013. }
  9014. private showRePlay() {
  9015. this.loadingVisible = Visibility.None;
  9016. this.replayVisible = Visibility.Visible;
  9017. }
  9018. private async play(url: string) {
  9019. let that = this;
  9020. that.showLoadIng();
  9021. //设置XComponent回调的context
  9022. if (!!this.mContext) {
  9023. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  9024. }
  9025. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  9026. this.mIjkMediaPlayer.reset();
  9027. }
  9028. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  9029. //设置debug模式
  9030. this.mIjkMediaPlayer.setDebug(false);
  9031. //初始化配置
  9032. this.mIjkMediaPlayer.native_setup();
  9033. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  9034. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  9035. this.mIjkMediaPlayer.setVolume('1', '1');
  9036. }else{
  9037. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  9038. }
  9039. //设置视频源
  9040. this.mIjkMediaPlayer.setDataSource(url);
  9041. //设置视频源http请求头
  9042. let headers = new Map([
  9043. ["user_agent", "Mozilla/5.0 BiliDroid/7.30.0 (bbcallen@gmail.com)"],
  9044. ["referer", "https://www.bilibili.com"]
  9045. ]);
  9046. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  9047. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  9048. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  9049. // }
  9050. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  9051. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  9052. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  9053. const fileSize = await this.getFileSize(this.videoUrl);
  9054. let bufferSize = 1 * 1024 ; // 默认缓冲区大小为1MB
  9055. if (fileSize > 3 * 1024 * 1024 * 1024) { // 文件大于3GB
  9056. bufferSize = 25 * 1024 * 1024; // 设置缓冲区大小为25MB
  9057. }
  9058. // 使用软件解码(通常比硬件解码更节省内存)
  9059. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", '0');
  9060. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", '0');
  9061. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", '1024');
  9062. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzeduration", '500000');
  9063. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  9064. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  9065. //停止预读的最小帧数
  9066. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  9067. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  9068. // 设置其他缓冲相关选项
  9069. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  9070. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  9071. //启动预加载
  9072. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  9073. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  9074. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  9075. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  9076. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  9077. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  9078. // 因此需要播放器丢包,才不会累积延时
  9079. // 这个和第三个参数packet-buffering无关。
  9080. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  9081. // 无限制收流
  9082. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  9083. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  9084. // 屏幕常亮
  9085. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  9086. // 设置超时
  9087. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  9088. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  9089. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  9090. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  9091. // 变速播放
  9092. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  9093. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  9094. let Speed = this.mIjkMediaPlayer.getSpeed()
  9095. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  9096. //是否开启循环播放
  9097. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  9098. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  9099. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  9100. if (height === 0) {
  9101. return;
  9102. }
  9103. const va = width / height;
  9104. const vpa = that.videoParentAspectRatio;
  9105. if (vpa > va) {
  9106. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  9107. } else {
  9108. that.videoWidth = '100%';
  9109. }
  9110. if (width && height) {
  9111. that.videoAspectRatio = width / height;
  9112. }
  9113. LogUtils.getInstance()
  9114. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  9115. that.hideLoadIng();
  9116. }
  9117. }
  9118. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  9119. let mOnPreparedListener: OnPreparedListener = {
  9120. onPrepared: async () => {
  9121. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  9122. try {
  9123. // this.cover = this.songList[this.curIndex].pixelMapPath
  9124. // this.artist = this.songList[this.curIndex].artist
  9125. // this.videoUrl = this.songList[this.curIndex].filePath
  9126. let isBgCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  9127. if (isBgCover && this.cover !== undefined && StrUtil.isNotEmpty(this.cover)) {
  9128. this.setImageColor2(this.cover)
  9129. } else {
  9130. this.getImageColor();
  9131. }
  9132. //保存碰一碰分享的当前的歌曲
  9133. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  9134. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  9135. await this.initLyric(lyricPath);
  9136. setTimeout(() => {
  9137. this.avSessionController.initAvSession(false);
  9138. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  9139. this.setAvSessionListener();
  9140. this.updateSessionPlayState(true)
  9141. this.setCurrentPlayMode()
  9142. }, 500)
  9143. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  9144. let timeoutPlay = 0
  9145. if (StrUtil.isNotEmpty(this.videoUrl) &&
  9146. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  9147. timeoutPlay = 1000
  9148. }
  9149. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  9150. if (this.modeType === 0) { //文件夹
  9151. let parentPath = FileUtil.getParentPath(this.videoUrl)
  9152. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  9153. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  9154. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  9155. } else if (this.modeType === 1) { //媒体库
  9156. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  9157. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  9158. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  9159. } else if (this.modeType === 2) { //艺术家
  9160. if (this.currentSong?.artist) {
  9161. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  9162. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  9163. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  9164. }
  9165. } else if (this.modeType === 3) { //专辑
  9166. if (this.currentSong?.album) {
  9167. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  9168. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  9169. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  9170. }
  9171. }
  9172. this.duration = this.mIjkMediaPlayer.getDuration()
  9173. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  9174. if (this.mIjkMediaPlayer != null) {
  9175. if (this.jumpTopTime * 1000 <= this.duration) {
  9176. // 调用 seekTo 方法,跳到指定时间
  9177. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  9178. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  9179. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  9180. }
  9181. }, timeoutPlay)
  9182. } else {
  9183. // 提示用户无法跳过
  9184. ToastUtil.showToast('跳过时间超过视频时长');
  9185. }
  9186. }
  9187. } else {
  9188. this.jumpTopTime = 0
  9189. this.jumpEndTime = 0
  9190. console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  9191. console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  9192. console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  9193. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  9194. //记忆播放(每一首都会记忆播放)
  9195. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  9196. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  9197. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  9198. this.restorePlaybackPosition() //读取播放记忆功能
  9199. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  9200. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  9201. this.restorePlaybackPosition() //读取播放记忆功能
  9202. }
  9203. this.isFirstStartPlay = false
  9204. }, timeoutPlay)
  9205. } else {
  9206. this.isFirstStartPlay = false
  9207. }
  9208. }
  9209. this.saveLastPlayList()
  9210. } catch (error) {
  9211. let err: BusinessError = error as BusinessError;
  9212. console.error('onecold failed with err: ' + JSON.stringify(err));
  9213. }
  9214. }
  9215. }
  9216. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  9217. let mOnTimedTextListener: OnTimedTextListener = {
  9218. onTimedText: () => {
  9219. }
  9220. }
  9221. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  9222. let mOnCompletionListener: OnCompletionListener = {
  9223. onCompletion: () => {
  9224. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  9225. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  9226. this.playNext()
  9227. } else if (this.playType == 1) { //1:单片重复播放
  9228. this.CONTROL_PlayStatus = PlayStatus.INIT
  9229. that.startPlayOrResumePlay();
  9230. } else if (this.playType == 2) { //2:正常播放,单曲播完
  9231. that.showRePlay();
  9232. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  9233. that.progressValue = this.PROGRESS_MAX_VALUE;
  9234. that.slideEnable = false;
  9235. that.stop();
  9236. // ToastUtil.showToast('开始重新播放')
  9237. } else if (this.playType == 3) { //3:随机播放
  9238. this.randomPlay()
  9239. }
  9240. }
  9241. }
  9242. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  9243. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  9244. onBufferingUpdate: (percent: number) => {
  9245. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  9246. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  9247. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  9248. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  9249. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  9250. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  9251. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  9252. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  9253. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  9254. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  9255. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  9256. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  9257. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  9258. let Looping = this.mIjkMediaPlayer.isLooping()
  9259. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  9260. }
  9261. }
  9262. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  9263. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  9264. onSeekComplete: () => {
  9265. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  9266. that.startPlayOrResumePlay();
  9267. }
  9268. }
  9269. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  9270. let mOnInfoListener: OnInfoListener = {
  9271. onInfo: (what: number, extra: number) => {
  9272. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  9273. that.hideLoadIng();
  9274. }
  9275. }
  9276. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  9277. let mOnErrorListener: OnErrorListener = {
  9278. onError: (what: number, extra: number) => {
  9279. this.stopProgressTask();
  9280. LogUtils.getInstance().LOGI("OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  9281. that.hideLoadIng();
  9282. if (StrUtil.isNotEmpty(this.videoUrl) && !FileUtil.accessSync(this.videoUrl)) {
  9283. ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
  9284. } else {
  9285. ToastUtil.showToast(getContext()
  9286. .resourceManager
  9287. .getStringByNameSync("Honey_the_video_is_playing_errant_The_system_is_wandering"))
  9288. }
  9289. }
  9290. }
  9291. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  9292. this.mIjkMediaPlayer.setMessageListener();
  9293. this.mIjkMediaPlayer.prepareAsync();
  9294. this.mIjkMediaPlayer.start();
  9295. }
  9296. //保存最后播放的那首歌和已经对应的播放列表
  9297. saveLastPlayList() {
  9298. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  9299. PreferencesUtil.putSync('LastMusicList', this.songList)
  9300. }
  9301. // 清空播放记录
  9302. clearVideoHistory() {
  9303. this.table.clearPlayHistory((success: boolean, error?: string) => {
  9304. if (success) {
  9305. this.historyList = [];
  9306. this.updateListData(this.historyList)
  9307. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  9308. ToastUtil.showToast('清空播放记录成功')
  9309. } else {
  9310. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  9311. }
  9312. });
  9313. }
  9314. public async setAvSessionListener() {
  9315. if (!this.avSessionController) {
  9316. return;
  9317. }
  9318. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  9319. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  9320. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  9321. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  9322. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  9323. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  9324. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  9325. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  9326. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  9327. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  9328. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  9329. }
  9330. setLoopMode() {
  9331. let itype = this.playType + 1
  9332. if (itype >= 4) {
  9333. this.playType = 0
  9334. ToastUtil.showToast('连续播放')
  9335. } else if (itype === 1) {
  9336. this.playType = 1
  9337. ToastUtil.showToast('单曲循环')
  9338. } else if (itype === 2) {
  9339. this.playType = 2
  9340. ToastUtil.showToast('单曲播完')
  9341. } else if (itype === 3) {
  9342. this.playType = 3
  9343. ToastUtil.showToast('随机播放')
  9344. } else if (itype === 0) {
  9345. this.playType = 0
  9346. ToastUtil.showToast('连续播放')
  9347. }
  9348. PreferencesUtil.putSync('musicPlayType', this.playType)
  9349. this.setCurrentPlayMode()
  9350. }
  9351. private sessionSetLoopModeCallback = (mode: number) => {
  9352. if (this.mIjkMediaPlayer != null) {
  9353. ToastUtil.showToast('当前播放模式:' + mode)
  9354. Logger.info('onecold 当前播放模式= ' + mode)
  9355. let hmPlayMode = mode + 1
  9356. if (hmPlayMode >= 4) {
  9357. hmPlayMode = 0
  9358. }
  9359. if (hmPlayMode === 1) {
  9360. this.playType = 1
  9361. ToastUtil.showToast('单曲循环')
  9362. } else if (hmPlayMode === 0) {
  9363. this.playType = 2
  9364. ToastUtil.showToast('单曲播完')
  9365. } else if (hmPlayMode === 3) {
  9366. this.playType = 3
  9367. ToastUtil.showToast('随机播放')
  9368. } else if (hmPlayMode === 2) {
  9369. this.playType = 0
  9370. ToastUtil.showToast('连续播放')
  9371. }
  9372. PreferencesUtil.putSync('musicPlayType', this.playType)
  9373. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  9374. let playBackState: avSession.AVPlaybackState = {
  9375. loopMode: hmPlayMode,
  9376. };
  9377. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  9378. console.info(`set setLoopMode AVPlaybackState successfully`);
  9379. }).catch((err: BusinessError) => {
  9380. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  9381. });
  9382. }
  9383. }
  9384. setCurrentPlayMode() {
  9385. if (!this.avSessionController) {
  9386. return;
  9387. }
  9388. let mLoopMode = 0
  9389. switch (this.playType) {
  9390. case 0:
  9391. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  9392. break;
  9393. case 1:
  9394. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  9395. break;
  9396. case 2:
  9397. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  9398. break;
  9399. case 3:
  9400. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  9401. break;
  9402. }
  9403. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  9404. let playBState: avSession.AVPlaybackState = {
  9405. loopMode: mLoopMode,
  9406. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  9407. };
  9408. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  9409. console.info(`set setLoopMode AVPlaybackState successfully`);
  9410. }).catch((err: BusinessError) => {
  9411. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  9412. });
  9413. }
  9414. private sessionToggleFavoriteCallback = (assetId: string) => {
  9415. if (this.mIjkMediaPlayer != null && this.currentSong) {
  9416. console.info(`on toggleFavorite `);
  9417. // 应用收到收藏命令,进行收藏处理。
  9418. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  9419. this.doFav(this.currentSong)
  9420. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  9421. let playbackState: avSession.AVPlaybackState = {
  9422. isFavorite: !this.isFac,
  9423. };
  9424. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  9425. console.info(`SetAVPlaybackState successfully`);
  9426. }).catch((err: BusinessError) => {
  9427. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  9428. });
  9429. }
  9430. }
  9431. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  9432. device: avSession.OutputDeviceInfo) => {
  9433. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  9434. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  9435. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  9436. await this.startCasting();
  9437. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  9438. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  9439. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  9440. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  9441. if (device) {
  9442. this.endCasting();
  9443. }
  9444. }
  9445. };
  9446. private async startCasting() {
  9447. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  9448. this.setPlaybackStateChangeListener();
  9449. this.pause();
  9450. this.initQueueItem();
  9451. this.prepare();
  9452. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  9453. refToIsCasting?.set(true);
  9454. this.castSeek = true;
  9455. this.isCastPlaying = true;
  9456. }
  9457. async changeCasting() {
  9458. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  9459. this.initQueueItem();
  9460. this.prepare();
  9461. this.setPlaybackStateChangeListener();
  9462. this.isCastPlaying = true;
  9463. this.castSeek = true;
  9464. }
  9465. public endCasting() {
  9466. this.avSessionController.getAvSession()?.stopCasting();
  9467. this.stopCast();
  9468. this.isCastPlaying = false;
  9469. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  9470. refToIsCasting?.set(false);
  9471. this.pause();
  9472. this.setIsPlaying(false);
  9473. // if (this.curIndex === this.curSource.index) {
  9474. // this.play
  9475. // this.seek(this.currentTime * 1000);
  9476. // this.setIsPlaying(true);
  9477. // } else {
  9478. // this.pauseVideo();
  9479. // this.setIsPlaying(false);
  9480. // }
  9481. }
  9482. public setIsPlaying(isPlayer: boolean) {
  9483. this.isPlaying = isPlayer;
  9484. }
  9485. private setPlaybackStateChangeListener(): void {
  9486. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  9487. this.castController?.on('endOfStream', this.reloadCasting);
  9488. this.castController?.on('playNext', this.playNextCallback);
  9489. this.castController?.on('playPrevious', this.playPreviousCallback);
  9490. }
  9491. private updateSessionPlayState(isPlay: boolean): void {
  9492. // if(!this.isBgPlayOpen)
  9493. // return
  9494. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  9495. this.setAVSessionPlayState({
  9496. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  9497. position: {
  9498. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  9499. updateTime: new Date().getTime()
  9500. }
  9501. });
  9502. }
  9503. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  9504. this.avSessionController.setAvSessionPlayState(playbackState)
  9505. }
  9506. private positionChange(position: number) {
  9507. this.currentTime2 = position / 1000;
  9508. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  9509. }
  9510. private playDurationChange(duration: number) {
  9511. this.duration = duration;
  9512. this.durationTime = Math.floor(this.duration / 1000);
  9513. this.durationStringTime = secondToTime((this.durationTime));
  9514. }
  9515. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  9516. const duration = playbackState?.extras?.duration;
  9517. if (typeof duration === 'number') {
  9518. this.playDurationChange(duration as number);
  9519. }
  9520. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  9521. this.positionChange(playbackState?.position?.elapsedTime);
  9522. }
  9523. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  9524. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  9525. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  9526. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  9527. this.isCastPlaying = false;
  9528. }
  9529. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  9530. this.isCastPlaying = true;
  9531. }
  9532. };
  9533. private reloadCasting = async () => {
  9534. let item = this.songList[this.curIndex];
  9535. let uri = fileUri.getUriFromPath(item.filePath);
  9536. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  9537. // description.startPosition = 0;
  9538. this.castItem = {
  9539. itemId: this.curIndex,
  9540. description: {
  9541. assetId: item.filePath,
  9542. title: item.name,
  9543. artist: '',
  9544. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  9545. // mediaUri: item.filePath,
  9546. fdSrc: {
  9547. fd: file.fd
  9548. },
  9549. // 该字段大写,音频'AUDIO',视频'VIDEO'
  9550. mediaType: 'VIDEO',
  9551. mediaSize: item.videoSize,
  9552. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  9553. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  9554. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  9555. duration: this.duration,
  9556. // albumCoverUri: 'https://www.example.jpeg',
  9557. // albumTitle: '《ExampleAlbum》',
  9558. appName: this.appName,
  9559. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  9560. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  9561. }
  9562. };
  9563. this.prepare();
  9564. this.isCastPlaying = true;
  9565. };
  9566. public playNextCallback = (): void => {
  9567. this.playNext()
  9568. };
  9569. public playPreviousCallback = (): void => {
  9570. this.playPrevious()
  9571. };
  9572. async prepare() {
  9573. await this.castController?.prepare(this.castItem);
  9574. await this.castController?.start(this.castItem);
  9575. }
  9576. public initQueueItem() {
  9577. let item = this.songList[this.curIndex];
  9578. let time = this.currentTime;
  9579. let uri = fileUri.getUriFromPath(item.filePath);
  9580. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  9581. this.castItem = {
  9582. itemId: this.curIndex,
  9583. description: {
  9584. assetId: item.filePath,
  9585. title: item.name,
  9586. artist: '',
  9587. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  9588. fdSrc: {
  9589. fd: file.fd
  9590. },
  9591. // 该字段大写,音频'AUDIO',视频'VIDEO'
  9592. mediaType: 'AUDIO',
  9593. mediaSize: item.videoSize,
  9594. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  9595. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  9596. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  9597. duration: this.duration,
  9598. // albumCoverUri: 'https://www.example.jpeg',
  9599. // albumTitle: '《ExampleAlbum》',
  9600. appName: this.appName,
  9601. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  9602. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  9603. }
  9604. };
  9605. }
  9606. async stopCast() {
  9607. try {
  9608. this.castController?.off('playbackStateChange');
  9609. this.castController?.off('endOfStream');
  9610. this.castController?.off('playNext');
  9611. this.castController?.off('playPrevious');
  9612. this.castController?.off('error');
  9613. } catch (error) {
  9614. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  9615. }
  9616. }
  9617. private sessionPlayCallback = (): void => {
  9618. this.playOrPause()
  9619. };
  9620. private sessionPauseCallback = (): void => {
  9621. this.playOrPause()
  9622. };
  9623. private playOrPause() {
  9624. if (!this.debounce()) {
  9625. return;
  9626. }
  9627. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  9628. this.pause();
  9629. } else {
  9630. this.startPlayOrResumePlay();
  9631. this.playChange()
  9632. }
  9633. }
  9634. private sessionPlayNextCallback = (): void => {
  9635. this.playNext()
  9636. };
  9637. private sessionPlayPreviousCallback = (): void => {
  9638. this.playPrevious()
  9639. };
  9640. private sessionStopCallback = (): void => {
  9641. this.stop()
  9642. };
  9643. private sessionFastForwardCallback = (time?: number) => {
  9644. if (!time) {
  9645. return;
  9646. }
  9647. if (this.mIjkMediaPlayer != null) {
  9648. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  9649. let seeTime = curPosition + time * 1000;
  9650. // 限制 seekValue 在合法范围内
  9651. if (seeTime < 0) {
  9652. seeTime = 0;
  9653. } else if (seeTime > this.duration) {
  9654. seeTime = this.duration;
  9655. }
  9656. Logger.info('onecold seeTime= ' + seeTime)
  9657. this.setSeekToActionProgress(seeTime)
  9658. this.seekTo(seeTime + "")
  9659. }
  9660. };
  9661. /**
  9662. * Gesture method onActionUpdate.
  9663. *
  9664. * @param event Gesture event.手势拖动设置快进和后退
  9665. */
  9666. private setSeekToActionProgress(position: number) {
  9667. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  9668. let duration = this.mIjkMediaPlayer.getDuration();
  9669. let pos = 0;
  9670. if (duration > 0) {
  9671. this.slideEnable = true;
  9672. let curPercent = position / duration;
  9673. pos = curPercent * 100;
  9674. if (pos > this.PROGRESS_MAX_VALUE) {
  9675. this.progressValue = this.PROGRESS_MAX_VALUE
  9676. } else {
  9677. this.progressValue = pos;
  9678. }
  9679. }
  9680. // LogUtils.getInstance()
  9681. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  9682. this.totalTime = this.stringForTime(duration);
  9683. if (position > duration) {
  9684. position = duration;
  9685. }
  9686. this.isCurrentTime = true;
  9687. this.currentTime = this.stringForTime(position);
  9688. this.isCurrentTime = false
  9689. }
  9690. private sessionRewindCallback = (time?: number) => {
  9691. if (!time) {
  9692. return;
  9693. }
  9694. if (this.mIjkMediaPlayer != null) {
  9695. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  9696. let seeTime = curPosition - time * 1000;
  9697. // 限制 seekValue 在合法范围内
  9698. if (seeTime < 0) {
  9699. seeTime = 0;
  9700. } else if (seeTime > this.duration) {
  9701. seeTime = this.duration;
  9702. }
  9703. Logger.info('onecold seeTime= ' + seeTime)
  9704. this.setSeekToActionProgress(seeTime)
  9705. this.seekTo(seeTime + "")
  9706. }
  9707. };
  9708. private sessionSeekCallback = (seekTime: number) => {
  9709. if (this.mIjkMediaPlayer != null) {
  9710. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  9711. this.seekTo(seekTime + "")
  9712. }
  9713. };
  9714. private async getFileSize(filePath: string): Promise<number> {
  9715. try {
  9716. const stat = await fs.stat(filePath);
  9717. return stat.size;
  9718. } catch (err) {
  9719. console.error('Failed to get file size: ' + err.message);
  9720. return 0;
  9721. }
  9722. }
  9723. private pause() {
  9724. if (this.mIjkMediaPlayer.isPlaying()) {
  9725. this.savePlaybackPosition();
  9726. this.mIjkMediaPlayer.pause();
  9727. this.setProgress();
  9728. this.mDestroyPage = true;
  9729. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  9730. this.updateSessionPlayState(false)
  9731. this.playChange()
  9732. if (this.pipController) {
  9733. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  9734. PiPWindow.PiPControlStatus.PAUSE);
  9735. }
  9736. }
  9737. }
  9738. private stop() {
  9739. this.savePlaybackPosition();
  9740. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9741. this.mIjkMediaPlayer.stop();
  9742. this.mIjkMediaPlayer.release();
  9743. this.stopProgressTask();
  9744. this.updateSessionPlayState(false)
  9745. this.playChange()
  9746. this.watchStatus();
  9747. }
  9748. //保持记忆播放功能
  9749. private savePlaybackPosition() {
  9750. if (this.mIjkMediaPlayer != null) {
  9751. const position = this.mIjkMediaPlayer.getCurrentPosition();
  9752. // ToastUtil.showToast('保存记忆播放 = ' + position)
  9753. const duration = this.mIjkMediaPlayer.getDuration();
  9754. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  9755. // 如果播放位置接近视频末尾,则保存 position 为 0
  9756. const playbackPosition = (duration - position < threshold) ? 0 : position;
  9757. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  9758. }
  9759. }
  9760. //获取记忆播放功能
  9761. private restorePlaybackPosition() {
  9762. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  9763. // ToastUtil.showToast('position = ' + position)
  9764. if (this.mIjkMediaPlayer != null && position > 0) {
  9765. // ToastUtil.showToast('seekTo = ' + position)
  9766. this.seekTo(position + "");
  9767. }
  9768. }
  9769. private seekTo(value: string) {
  9770. if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  9771. ToastUtil.showToast('wma格式不支持拖动快进。')
  9772. return
  9773. }
  9774. this.mIjkMediaPlayer.seekTo(value);
  9775. // this.startPlayOrResumePlay()
  9776. // 在这里恢复计时器状态
  9777. this.setProgress()
  9778. // this.startProgressTask();
  9779. }
  9780. // 添加到下一首播放
  9781. private addToNextPlay(song: VideoItem) {
  9782. if (!this.debounce()) {
  9783. return;
  9784. }
  9785. if (this.currentSong) {
  9786. if (this.currentSong === song) {
  9787. ToastUtil.showToast('当前已经在播放这首歌了!')
  9788. return
  9789. }
  9790. }
  9791. // 如果未开始播放或队列为空
  9792. if (this.curIndex === -1 || this.songList.length === 0) {
  9793. this.songList = [song];
  9794. this.curIndex = 0;
  9795. this.doPlay(song)
  9796. return;
  9797. }
  9798. // 插入到当前索引+1的位置
  9799. const insertPos = this.curIndex + 1;
  9800. this.songList.splice(insertPos, 0, song);
  9801. this.songList = [...this.songList]; // 触发状态更新
  9802. this.sonDataSource.pushArrayData(this.songList)
  9803. ToastUtil.showToast('已添加至下一首播放')
  9804. }
  9805. //下一个
  9806. private playNext() {
  9807. if (!this.debounce()) {
  9808. return;
  9809. }
  9810. if (this.playType == 3) { //3:随机播放
  9811. this.randomPlay()
  9812. return;
  9813. }
  9814. if (ArrayUtil.isNotEmpty(this.songList)) {
  9815. if (this.curIndex == this.songList.length - 1) {
  9816. this.curIndex = 0;
  9817. } else {
  9818. this.curIndex++;
  9819. }
  9820. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9821. this.stop();
  9822. this.currentSong = this.songList[this.curIndex]
  9823. this.videoUrl = this.songList[this.curIndex].filePath;
  9824. this.artist = this.songList[this.curIndex].artist
  9825. this.name = this.songList[this.curIndex].name
  9826. //this.cover = this.songList[this.curIndex].pixelMapPath
  9827. this.changeImageAnimation()
  9828. }
  9829. }
  9830. changeImageAnimation() {
  9831. if(this.openSkipSongAnimate){
  9832. // 第一步:淡出动画
  9833. this.getUIContext()?.animateTo({
  9834. duration: 500,
  9835. curve: Curve.EaseOut,
  9836. }, () => {
  9837. this.opacityValueImage = 0.1;
  9838. if(this.isCoverRectangle){
  9839. this.scaleValueImage = 0.88
  9840. }
  9841. });
  9842. // 第二步:切换图片后淡入
  9843. setTimeout(() => {
  9844. this.cover = this.songList[this.curIndex].pixelMapPath
  9845. this.getUIContext()?.animateTo({
  9846. duration: 500,
  9847. curve: Curve.EaseIn,
  9848. }, () => {
  9849. this.opacityValueImage = 1;
  9850. this.scaleValueImage = 1 // 图标恢复到原始大小
  9851. this.startPlayOrResumePlay()
  9852. });
  9853. }, 500);
  9854. }else{
  9855. this.cover = this.songList[this.curIndex].pixelMapPath
  9856. this.startPlayOrResumePlay()
  9857. }
  9858. }
  9859. // 存储已播放的歌曲索引
  9860. private playedIndices: Set<number> = new Set();
  9861. //随机播放
  9862. private randomPlay() {
  9863. // if (!this.debounce()) {
  9864. // return;
  9865. // }
  9866. if (ArrayUtil.isNotEmpty(this.songList)) {
  9867. if (this.songList.length > 3) {
  9868. // 如果所有歌曲都播放过一次,清空已播放索引集合
  9869. if (this.playedIndices.size === this.songList.length) {
  9870. this.playedIndices.clear();
  9871. }
  9872. // 随机选择一个未播放的歌曲索引
  9873. let newIndex: number;
  9874. // 添加超时机制防止无限循环
  9875. let attempt = 0;
  9876. const maxAttempts = 100; // 根据需求调整
  9877. do {
  9878. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  9879. attempt++;
  9880. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  9881. if (attempt >= maxAttempts) {
  9882. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  9883. newIndex = Math.floor(Math.random() * this.songList.length);
  9884. }
  9885. this.curIndex = newIndex;
  9886. this.playedIndices.add(newIndex);
  9887. } else {
  9888. // 当歌曲数量小于或等于3时,直接播放下一首
  9889. if (this.curIndex == this.songList.length - 1) {
  9890. this.curIndex = 0;
  9891. } else {
  9892. this.curIndex++;
  9893. }
  9894. }
  9895. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9896. this.stop();
  9897. this.currentSong = this.songList[this.curIndex];
  9898. this.videoUrl = this.songList[this.curIndex].filePath;
  9899. this.name = this.songList[this.curIndex].name;
  9900. this.artist = this.songList[this.curIndex].artist
  9901. // this.cover = this.songList[this.curIndex].pixelMapPath
  9902. this.changeImageAnimation()
  9903. }
  9904. }
  9905. private playIndex(index: number) {
  9906. if (!this.debounce()) {
  9907. return;
  9908. }
  9909. if (ArrayUtil.isNotEmpty(this.songList)) {
  9910. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9911. this.stop();
  9912. this.currentSong = this.songList[this.curIndex]
  9913. this.videoUrl = this.songList[index].filePath;
  9914. this.name = this.songList[index].name
  9915. this.artist = this.songList[this.curIndex].artist
  9916. this.curIndex = index;
  9917. this.changeImageAnimation()
  9918. }
  9919. }
  9920. //上一个
  9921. private playPrevious() {
  9922. if (!this.debounce()) {
  9923. return;
  9924. }
  9925. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  9926. this.randomModePlayFromHistory()
  9927. return;
  9928. }
  9929. if (this.curIndex == 0) {
  9930. this.curIndex = this.songList.length - 1;
  9931. } else {
  9932. this.curIndex--;
  9933. }
  9934. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9935. this.stop();
  9936. this.currentSong = this.songList[this.curIndex]
  9937. this.videoUrl = this.songList[this.curIndex].filePath;
  9938. this.name = this.songList[this.curIndex].name
  9939. this.artist = this.songList[this.curIndex].artist
  9940. this.changeImageAnimation()
  9941. }
  9942. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  9943. private randomModePlayFromHistory() {
  9944. if (this.historyList.length >= 2) {
  9945. // 播放历史记录的第二首
  9946. const prevSong = this.historyList[1];
  9947. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  9948. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9949. this.stop();
  9950. this.currentSong = prevSong;
  9951. this.videoUrl = prevSong.filePath;
  9952. this.cover = prevSong.pixelMapPath
  9953. this.artist = prevSong.artist
  9954. this.name = prevSong.name;
  9955. this.startPlayOrResumePlay();
  9956. } else {
  9957. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  9958. if (this.curIndex === 0) {
  9959. this.curIndex = this.songList.length - 1;
  9960. } else {
  9961. this.curIndex--;
  9962. }
  9963. this.CONTROL_PlayStatus = PlayStatus.INIT;
  9964. this.stop();
  9965. this.currentSong = this.songList[this.curIndex];
  9966. this.videoUrl = this.songList[this.curIndex].filePath;
  9967. this.artist = this.songList[this.curIndex].artist
  9968. this.name = this.songList[this.curIndex].name;
  9969. this.changeImageAnimation()
  9970. }
  9971. }
  9972. debounce() {
  9973. const delay = 600;
  9974. let cur = new Date().getTime();
  9975. if (cur - this.last > delay) {
  9976. this.last = cur;
  9977. return true;
  9978. }
  9979. return false;
  9980. }
  9981. /**
  9982. * Sets whether the screen is a constant based on the playback status.
  9983. */
  9984. watchStatus() {
  9985. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  9986. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  9987. this.windowClass.setWindowKeepScreenOn(true);
  9988. } else {
  9989. this.windowClass.setWindowKeepScreenOn(false);
  9990. }
  9991. }
  9992. /**
  9993. * Volume gesture method onActionStart.
  9994. *
  9995. * @param event Gesture event.
  9996. */
  9997. private customDialogComponentIdMM: number = 0
  9998. @Builder
  9999. customDialogComponentMM() {
  10000. Column() {
  10001. Row() {
  10002. Blank()
  10003. Text('验证密码')
  10004. .fontSize(22)
  10005. .fontColor($r('app.color.pri_bg'))
  10006. .margin({ top: 18 })
  10007. Blank()
  10008. Image($r('app.media.close'))
  10009. .fillColor(Color.White)
  10010. .margin({ top: 18, right: 18 })
  10011. .width(20)
  10012. .onClick(() => {
  10013. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  10014. })
  10015. }
  10016. .width('100%') // 使Row占据整个宽度
  10017. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  10018. Verify({
  10019. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  10020. });
  10021. }.height('60%')
  10022. .backgroundColor($r('app.color.index_background'))
  10023. .justifyContent(FlexAlign.SpaceBetween)
  10024. }
  10025. private handleVerifyCompleted(isSuccess: boolean) {
  10026. if (isSuccess) {
  10027. console.log('验证成功');
  10028. // 在这里处理验证成功后的逻辑
  10029. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  10030. this.currentPath = this.lockPath
  10031. this.getSortedFiles(this.currentPath)
  10032. } else {
  10033. // console.log('验证失败');
  10034. ToastUtil.showToast('验证失败')
  10035. }
  10036. }
  10037. private showVerifyDialog() {
  10038. promptAction.openCustomDialog({
  10039. transition: TransitionEffect.asymmetric(
  10040. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  10041. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  10042. ,
  10043. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  10044. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  10045. ),
  10046. builder: () => {
  10047. this.customDialogComponentMM()
  10048. },
  10049. isModal: true,
  10050. autoCancel: true,
  10051. maskColor: Color.Transparent,
  10052. alignment: DialogAlignment.Bottom,
  10053. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  10054. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  10055. console.log("dialog onWillDismiss")
  10056. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  10057. dismissDialogAction.dismiss()
  10058. }
  10059. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  10060. dismissDialogAction.dismiss()
  10061. }
  10062. }
  10063. }).then((dialogId: number) => {
  10064. this.customDialogComponentIdMM = dialogId
  10065. })
  10066. }
  10067. //左滑操作 移动文件 重命名 删除等操作
  10068. @Builder
  10069. DeleteButton(item: VideoItem, index: number, filePath: string) {
  10070. Row() {
  10071. //加入收藏
  10072. Button() {
  10073. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  10074. .fillColor(Color.White)
  10075. .width(20)
  10076. }
  10077. .width(40)
  10078. .height(40)
  10079. .type(ButtonType.Circle)
  10080. .backgroundColor(this.themeColor)
  10081. .margin(5)
  10082. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  10083. .onClick(() => {
  10084. if (item) {
  10085. this.doFav(item)
  10086. }
  10087. })
  10088. //加入下一首播放
  10089. Button() {
  10090. Image($r('app.media.next_to_play'))
  10091. .fillColor(Color.White)
  10092. .width(20)
  10093. }
  10094. .width(40)
  10095. .height(40)
  10096. .type(ButtonType.Circle)
  10097. .backgroundColor(this.themeColor)
  10098. .margin(5)
  10099. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  10100. .onClick(() => {
  10101. this.addToNextPlay(item);
  10102. })
  10103. //复制文件
  10104. Button() {
  10105. Image($r('app.media.copy'))
  10106. .fillColor(Color.White)
  10107. .width(20)
  10108. }
  10109. .width(40)
  10110. .height(40)
  10111. .type(ButtonType.Circle)
  10112. .backgroundColor(this.themeColor)
  10113. .margin(5)
  10114. .id(filePath + 'copy')
  10115. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  10116. .onClick(() => {
  10117. this.showCopyDialog(false, item, index, filePath + 'copy');
  10118. })
  10119. //移动文件
  10120. Button() {
  10121. Image($r('app.media.cut'))
  10122. .fillColor(Color.White)
  10123. .width(20)
  10124. }
  10125. .width(40)
  10126. .height(40)
  10127. .type(ButtonType.Circle)
  10128. .backgroundColor(this.themeColor)
  10129. .margin(5)
  10130. .id(filePath)
  10131. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  10132. .onClick(() => {
  10133. this.showCutDialog(false, item, index, filePath);
  10134. })
  10135. Button() {
  10136. Image($r('app.media.cut_current'))
  10137. .fillColor(Color.White)
  10138. .width(20)
  10139. }
  10140. .width(40)
  10141. .height(40)
  10142. .type(ButtonType.Circle)
  10143. .backgroundColor(this.themeColor)
  10144. .margin(5)
  10145. .id(filePath + 'current')
  10146. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  10147. (this.isHasDir ? Visibility.Visible : Visibility.None))
  10148. .onClick(() => {
  10149. this.showCutDialog(true, item, index, filePath + 'current');
  10150. })
  10151. //重命名
  10152. Button() {
  10153. Image($r('app.media.rename2'))
  10154. .fillColor(Color.White)
  10155. .width(20)
  10156. }
  10157. .width(40)
  10158. .height(40)
  10159. .type(ButtonType.Circle)
  10160. .backgroundColor(this.themeColor)
  10161. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  10162. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  10163. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  10164. .margin(5)
  10165. .onClick(() => {
  10166. this.showReNameDialog(item, index + '', filePath)
  10167. })
  10168. Button() {
  10169. Image($r('app.media.delete2'))
  10170. .fillColor(Color.White)
  10171. .width(20)
  10172. }
  10173. .width(40)
  10174. .height(40)
  10175. .type(ButtonType.Circle)
  10176. .backgroundColor(this.themeColor)
  10177. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  10178. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  10179. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  10180. .margin(5)
  10181. .onClick(() => {
  10182. this.showWarnIsDeleteFile(item, index + '', filePath)
  10183. })
  10184. Button() {
  10185. Image($r('app.media.share2'))
  10186. .fillColor(Color.White)
  10187. .width(20)
  10188. }
  10189. .width(40)
  10190. .height(40)
  10191. .type(ButtonType.Circle)
  10192. .backgroundColor(this.themeColor)
  10193. .margin(5)
  10194. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  10195. .onClick(() => {
  10196. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  10197. })
  10198. }
  10199. }
  10200. /**
  10201. * 穿山甲banner广告
  10202. */
  10203. // private declare bannerAd: CSJNativeExpressAd;
  10204. // @State private status: string = "未加载"
  10205. // @State private isShowAd: boolean = false
  10206. // private declare mAdSlot: AdSlot;
  10207. // private mBiddingAdm = '' //服务端bidding才需要设置
  10208. // private expressLoadAdListener: NativeExpressAdListener = {
  10209. // /**
  10210. // * 加载失败的回调
  10211. // *
  10212. // * @param code
  10213. // * @param message
  10214. // */
  10215. // onError: (code: number, message: string) => {
  10216. // console.error("加载广告失败,code=" + code + ",message=" + message);
  10217. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  10218. // },
  10219. //
  10220. // /**
  10221. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  10222. // *
  10223. // * @param ads 返回的广告列表
  10224. // */
  10225. //
  10226. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  10227. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  10228. // if (ads && ads.length > 0) {
  10229. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  10230. // ad.setExpressInteractionListener({
  10231. // /**
  10232. // *广告的点击回调
  10233. // * @param type 广告的交互类型
  10234. // */
  10235. // onAdClicked: (type: number) => {
  10236. // console.log("BannerExpressAdPage==onAdClicked......");
  10237. // },
  10238. //
  10239. // /**
  10240. // * 广告的展示回调 每个广告仅回调一次
  10241. // * @param type 广告的交互类型
  10242. // */
  10243. // onAdShow: (type: number) => {
  10244. // console.log("BannerExpressAdPage==onAdShow......");
  10245. // },
  10246. //
  10247. // /**
  10248. // * 模板渲染失败
  10249. // */
  10250. // onRenderFail: (code: number, msg: string) => {
  10251. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  10252. // },
  10253. //
  10254. // /**
  10255. // * 模板渲染成功
  10256. // * @param width 返回view的宽 单位 vp
  10257. // * @param height 返回view的高 单位 vp
  10258. // */
  10259. // onRenderSuccess: (width: number, height: number) => {
  10260. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  10261. // this.bannerAd = ad;
  10262. // this.status = "广告加载完成待展示";
  10263. //
  10264. // this.showBannerAd()
  10265. // }
  10266. // })
  10267. // //渲染广告
  10268. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  10269. // this.setDislikeCallback(ad); //设置dislike
  10270. // ad.render(this.getUIContext())
  10271. // this.status = "广告加载中...";
  10272. // });
  10273. // }
  10274. // }
  10275. // }
  10276. //
  10277. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  10278. // ad.setDislikeCallback({
  10279. // /**
  10280. // * dislike show
  10281. // */
  10282. // onShow: () => {
  10283. // console.log("BannerExpressAdPage==dislike......show");
  10284. // },
  10285. //
  10286. // /**
  10287. // * @param position 选择的位置
  10288. // * @param value 选择的内容
  10289. // * @param enforceRemove 是否强制关闭广告
  10290. // */
  10291. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  10292. // this.isShowAd = false;
  10293. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  10294. // ",enforce=" + enforceRemove);
  10295. // },
  10296. //
  10297. // /**
  10298. // * 点击取消
  10299. // */
  10300. // onCancel: () => {
  10301. // console.log("BannerExpressAdPage==dislike......onCancel");
  10302. // }
  10303. //
  10304. // })
  10305. // }
  10306. /**
  10307. * 加载Banner广告
  10308. */
  10309. loadBannerAd(rit: string) {
  10310. // if (Utility.isNoble()) {
  10311. // return
  10312. // }
  10313. // if (!Utility.isPassInstallTime(2)) {
  10314. // return
  10315. // }
  10316. // this.isShowAd = false;
  10317. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  10318. // this.mAdSlot = new AdSlotBuilder()
  10319. // .setCodeId(rit)
  10320. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  10321. // .setAdCount(1)
  10322. // .setBidAdm(this.mBiddingAdm)
  10323. // .build()
  10324. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  10325. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  10326. // this.status = "广告加载中..."
  10327. }
  10328. /**
  10329. * 展示Banner广告
  10330. */
  10331. // showBannerAd() {
  10332. // if (!this.bannerAd) {
  10333. // return
  10334. // }
  10335. // this.isShowAd = true
  10336. // this.status = "已展示"
  10337. // }
  10338. /**
  10339. * 穿山甲广告代码结束
  10340. */
  10341. }
  10342. //视频气泡窗口的布局
  10343. @Builder
  10344. function customPopupBuilder(dataBu: BubbleBean) {
  10345. List() {
  10346. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  10347. ListItem() {
  10348. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10349. Row() {
  10350. Column() {
  10351. Image(dataBu.imageRes[index])
  10352. .height(28)
  10353. .fillColor(dataBu.color)
  10354. .alignSelf(ItemAlign.Center)
  10355. }
  10356. .width(32)
  10357. Text(item)
  10358. .padding({
  10359. top: 10,
  10360. bottom: 10,
  10361. right: 10,
  10362. left: 10
  10363. })
  10364. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  10365. .textAlign(TextAlign.Start)
  10366. .width("100%")
  10367. }
  10368. }
  10369. .backgroundColor($r('app.color.settings_background_main'))
  10370. .margin({ top: 6, bottom: 6 })
  10371. }
  10372. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  10373. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  10374. TransitionEffect.scale({ x: 0, y: 0 })))
  10375. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  10376. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  10377. .onClick(() => {
  10378. dataBu.onItemClick?.(index)
  10379. })
  10380. })
  10381. }
  10382. .width(120)
  10383. .divider({
  10384. strokeWidth: 1,
  10385. color: "#22FFFFFF"
  10386. })
  10387. }
  10388. // Function to calculate a hash for the file list
  10389. function simpleHash(fileList: string[]): string {
  10390. let hash = 0;
  10391. const str = fileList.join(',');
  10392. for (let i = 0; i < str.length; i++) {
  10393. const char = str.charCodeAt(i);
  10394. hash = (hash << 5) - hash + char;
  10395. hash |= 0; // Convert to 32bit integer
  10396. }
  10397. return hash.toString();
  10398. }
  10399. interface MoreItem {
  10400. id: number;
  10401. image: Resource;
  10402. title: string;
  10403. }
  10404. //视频气泡窗口的布局
  10405. @Builder
  10406. function cutPopupBuilder(dataBu: BubbleBean) {
  10407. Column() {
  10408. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  10409. .padding({
  10410. top: 10,
  10411. bottom: 10,
  10412. right: 10,
  10413. left: 10
  10414. })
  10415. .textAlign(TextAlign.Start)
  10416. .width(160)
  10417. .fontWeight(666)
  10418. .fontSize(16)
  10419. List() {
  10420. ForEach(dataBu.data, (item: string, index: number) => {
  10421. ListItem() {
  10422. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10423. Row() {
  10424. Column() {
  10425. Image($r('app.media.music_group'))
  10426. .height(28)
  10427. .fillColor(dataBu.color)
  10428. .alignSelf(ItemAlign.Center)
  10429. }
  10430. .width(32)
  10431. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  10432. .padding({
  10433. top: 10,
  10434. bottom: 10,
  10435. right: 10,
  10436. left: 10
  10437. })
  10438. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  10439. .fontSize(15)
  10440. }
  10441. }
  10442. .backgroundColor(Color.Transparent)
  10443. .margin({ top: 7, bottom: 7 })
  10444. }
  10445. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  10446. .animation({ duration: 500 }),
  10447. TransitionEffect.scale({ x: 0, y: 0 })))
  10448. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  10449. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  10450. .onClick(() => {
  10451. dataBu.onItemClick?.(index)
  10452. })
  10453. })
  10454. }
  10455. .width(150)
  10456. .divider({
  10457. strokeWidth: 1,
  10458. color: "#22FFFFFF"
  10459. })
  10460. }
  10461. .height(300)
  10462. .padding({
  10463. bottom: 30
  10464. })
  10465. }
  10466. function getFileDirName(filePath: string,rootPath:string): string{
  10467. if(filePath===rootPath){
  10468. return '首页'
  10469. }
  10470. let result = FileUtil.getFileName(filePath)
  10471. if(StrUtil.isEmpty(result))
  10472. return ''
  10473. if(result.startsWith('.'))
  10474. result = result.replace(/\./g, '')
  10475. return result
  10476. }