LocalMusic.ets 463 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433
  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 { Playlist } from '../viewmodel/Playlist';
  5. import { LengthMetrics, SegmentButton,borderRadiuses, SegmentButtonOptions } from '@kit.ArkUI';
  6. import {
  7. AppUtil,
  8. ArrayUtil,
  9. Base64Util,
  10. DateUtil,
  11. DeviceUtil,
  12. DisplayUtil,
  13. FileUtil,
  14. ImageUtil,
  15. LogUtil,
  16. MD5,
  17. PreferencesUtil,
  18. RandomUtil,
  19. StrUtil,
  20. ToastUtil
  21. } from '@pura/harmony-utils';
  22. import { imagePathToPixelMap } from '../common/util/CommUtils';
  23. import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  24. import { CommonConstants } from '../common/constants/CommonConstants';
  25. import { EventConstants } from '../common/constants/EventConstants';
  26. import Logger from '../common/util/Logger';
  27. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  28. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  29. import { BubbleBean } from '../viewmodel/BubbleBean';
  30. import { PopupPosition, XPopup } from '@chinalike/popup';
  31. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  32. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  33. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  34. import { MessageEvents, util, worker, ErrorEvent } from '@kit.ArkTS';
  35. import { Verify } from './Verify';
  36. import { taskpool } from '@kit.ArkTS';
  37. import { RotatingCover } from './RotatingCover';
  38. import { PlayConstants } from '../common/constants/PlayConstants';
  39. import { effectKit } from '@kit.ArkGraphics2D';
  40. import { ColorConversion } from '../common/util/ColorConversion';
  41. import { LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  42. import { AvSessionController } from '../controller/AvSessionController';
  43. import { repairAudioMetadata, convertDsfToWav, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
  44. import { FFMpegTags,Utility } from '../common/util/Utility';
  45. import { TagsContentCover } from '../view/TagsContentCover';
  46. import { ImageFancyModifier } from '../common/util/AttributeModifierUtil'
  47. import {
  48. // DeviceChangeReason,
  49. IjkMediaPlayer,
  50. InterruptEvent,
  51. InterruptHintType,
  52. LogUtils,
  53. OnBufferingUpdateListener,
  54. OnCompletionListener,
  55. OnErrorListener,
  56. OnInfoListener,
  57. OnPreparedListener,
  58. OnSeekCompleteListener,
  59. OnTimedTextListener,
  60. OnVideoSizeChangedListener
  61. } from '@ohos/ijkplayer';
  62. import { PlayStatus } from '../common/PlayStatus';
  63. import fs from '@ohos.file.fs';
  64. import { image } from '@kit.ImageKit';
  65. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  66. import { UniversalDetector } from '@ohos/juniversalchardet';
  67. import { SettingPage } from '../pages/SettingPage';
  68. import { secondToTime,getTransverterText } from '../common/util/CommUtils';
  69. import { CommonConstants2 } from '../common/util/CommonConstants2';
  70. import { hilog } from '@kit.PerformanceAnalysisKit';
  71. import { LazyDataSource } from '../common/util/LazyDataSource';
  72. import MediaTable from '../common/util/MediaTable';
  73. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  74. import ImageUtils from '../common/util/ImageUtils';
  75. import { ringtone } from '@kit.RingtoneKit';
  76. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  77. import { resourceManager } from '@kit.LocalizationKit';
  78. import { deviceInfo } from '@kit.BasicServicesKit';
  79. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  80. import app from '@system.app';
  81. import { TextNodeController } from './PipLyricTextBuilder';
  82. import { IndexerView } from './IndexerView';
  83. import { KeyCode } from '@kit.InputKit';
  84. import { KnockController } from '../controller/KnockController';
  85. import { DeleteComptent } from '../view/DeleteComptent';
  86. import { ABLoopComptent } from '../view/ABLoopComptent';
  87. import { FixMessyView } from '../view/FixMessyView';
  88. import { parseCueFile,CueTrack,CueInfo } from '../common/util/CueUtils';
  89. import { CueComptent } from '../view/CueComptent';
  90. import PlaylistTable from '../common/util/PlaylistTable';
  91. import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
  92. import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
  93. const TAG = 'LocalMusic';
  94. /**
  95. * 歌单播放事件数据
  96. */
  97. interface PlaylistEventData {
  98. playlistId: string;
  99. playlistName: string;
  100. songCount: number;
  101. startIndex: number;
  102. songFilePaths: string[];
  103. }
  104. const DEFAULT_INDEX =
  105. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  106. 'X', 'Y', 'Z']
  107. //排序类型
  108. function getTypeOrder(type: number) {
  109. switch (type) {
  110. case CommonConstants.TYPE_IS_DIR:
  111. return 1; // First
  112. case CommonConstants.TYPE_IS_CSJAD:
  113. return 2; // Middle
  114. case CommonConstants.TYPE_LOCAL:
  115. return 3; // Last
  116. default:
  117. return 4; // Unknown types, if any, go last
  118. }
  119. }
  120. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  121. // 定义接口
  122. interface HiCarAspectRatio {
  123. ratio: number;
  124. name: string;
  125. }
  126. interface GeneratedObjectLiteralInterface_1 {
  127. assetId: string;
  128. title: string;
  129. artist: string;
  130. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  131. mediaUri: string;
  132. // 该字段大写,音频'AUDIO',视频'VIDEO'
  133. mediaType: string;
  134. mediaSize: number;
  135. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  136. startPosition: number;
  137. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  138. duration: number;
  139. albumCoverUri: string;
  140. albumTitle: string;
  141. appName: string;
  142. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  143. drmScheme: string;
  144. }
  145. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  146. const ITEM_HEIGHT: number = 65; // 列表项中高度
  147. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  148. //功能强大的音乐播放器
  149. @Preview
  150. @Component
  151. export struct LocalMusic {
  152. @Consume currentSongList: Array<VideoItem>//当前歌单
  153. @Consume currentSongListName:string //当前歌单名称
  154. @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
  155. @State isRefreshing: boolean = false;
  156. @State maxRefreshingHeight: number = 100.0;
  157. private contentNode?: ComponentContent<Object> = undefined;
  158. @State ratioL: number = 1;
  159. @State mediaKuCount: number = 0;
  160. @State albumCount: number = 0;
  161. @State artistCount: number = 0;
  162. @State fastForwardSeconds: string = '10'
  163. @State isShowBackFast: boolean = true//快进快退按钮
  164. @State isCanAuto:boolean = true
  165. @State opacityValueImage: number = 1;
  166. @State tipPopup:boolean = false
  167. @Consume mType: number;
  168. @StorageProp('themeColor') themeColor: string =
  169. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  170. themeMode: number = 0;
  171. @State titleName: string = '首页'
  172. @State textStr: string = ''
  173. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  174. // private download_path: string = '';
  175. @Consume rootPath: string //音频根目录
  176. @Consume currentPath: string
  177. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  178. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  179. @State lockPath: string = ''
  180. @State favPath: string = ''
  181. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  182. @State historyPath: string = ''
  183. @State historyList: Array<VideoItem> = []
  184. @Consume isHistory: boolean
  185. static readonly HISTORY_MUSIC: string = 'music_historyList';
  186. private table: MediaTable = new MediaTable(getContext(this))
  187. private playlistTable: PlaylistTable | null = null
  188. @State allPlaylists: Playlist[] = []
  189. @State isZero: boolean = false
  190. @State fileList: Array<string> = []
  191. @State dirList: Array<VideoItem> = []
  192. @Consume videoLocalList: Array<VideoItem>
  193. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  194. @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  195. @State artistList: Array<VideoItem> = []; //艺术家文件
  196. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  197. @State albumList: Array<VideoItem> = []; //专辑文件
  198. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  199. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  200. @State imageOpacities: number[] = [];
  201. @Consume isCanBack: boolean
  202. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  203. @State showSingleLyric: boolean = false
  204. @State sortType: number = 4 //默认排序方式
  205. @State isShowSimi: boolean = false //是否显示私密音频
  206. @State isShowFAV: boolean = true //是否显示我的收藏
  207. @State isShowTitleBar: boolean = true //是否显示分类导航条
  208. @State isShowAllBar: boolean = true //是否显示播放全部条
  209. @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
  210. @State isShowHistory: boolean = true //是否显示最近播放
  211. @State @Watch('onColorModeChange') isCustomizeBg: boolean = false //自定义背景界面
  212. @State isGridMusic: boolean = false //是否网格布局
  213. @State isCircleBtn: boolean = false //是否圆形播放按钮
  214. @State twoFingerType: number = 3 //双支放大缩小的类型
  215. @State isScrollHide: boolean = false //是否滚动隐藏
  216. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  217. @State isStartAutoPlay: boolean = false //启动后自动播放
  218. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  219. @State isShowHeader: boolean = true
  220. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  221. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  222. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  223. @State isSwipe: boolean = false //listItem的左滑开关
  224. @State openSkipSongAnimate: boolean = true//切歌动画效果
  225. @State customizeBgPath: string | undefined = '';
  226. @State isDarkMode: boolean = false
  227. @State lyricTextWeight: number = 400
  228. @State lyricTextWeightPip: number = 400
  229. @State currentSwiperIndex: number = 0
  230. @State blurValue: number = 0 //背景模糊
  231. @State bgBrightness: number = 0 //背景亮度
  232. private listScroller: ListScroller = new ListScroller()
  233. private playListScroller: Scroller = new Scroller()
  234. @State isOneKeyTags:boolean = false
  235. @State isFixMessy:boolean = false
  236. @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
  237. @StorageProp('topRectHeight') topRectHeight: number = px2vp(AppUtil.getStatusBarHeight());
  238. @StorageProp('windowWidth') windowWidth: number = 0;
  239. @StorageProp('windowHeight') windowHeight: number = 0;
  240. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  241. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  242. private UNKONWN:string = '';
  243. private listArea: Area = {
  244. width: 0,
  245. height: 0,
  246. position: {},
  247. globalPosition: {}
  248. }
  249. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  250. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  251. //瀑布流的列数横竖屏动态切换
  252. onIsLandscapeChange() {
  253. if(this.isLandscape){
  254. this.columns = 4
  255. }else{
  256. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  257. }
  258. }
  259. onColorModeChange() {
  260. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  261. if (this.isCustomizeBg) {
  262. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  263. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  264. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  265. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  266. this.tabOptions.selectedBackgroundColor = Color.Transparent
  267. } else {
  268. if (!this.isDarkMode) {
  269. this.titleBarModel.setTitleBarBackground(this.themeColor)
  270. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  271. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  272. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  273. this.tabOptions.selectedBackgroundColor = this.themeColor
  274. } else {
  275. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  276. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  277. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  278. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  279. this.tabOptions.selectedBackgroundColor = $r('app.color.silvery')
  280. }
  281. }
  282. }
  283. //歌单id发生变化的时候回调
  284. onIDChange(){
  285. if(this.modeType==4){
  286. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  287. this.updateListData(this.currentSongList, true)
  288. this.titleBarModel.setTitleName(this.currentSongListName)
  289. this.isShowTitleBar = false
  290. }
  291. }
  292. onModeChange() {
  293. this.isFavMusic = false
  294. if (this.modeType === 2 || this.modeType === 3) {
  295. this.titleBarModel.setRightIcon(null)
  296. } else {
  297. this.titleBarModel.setRightIcon(($r('app.media.add')))
  298. }
  299. LogUtil.info('onecold onModeChange = ' + this.modeType)
  300. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  301. switch (this.modeType) {
  302. case 0:
  303. this.getSortedFiles(this.currentPath)
  304. break
  305. case 1:
  306. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  307. this.updateListData(this.mediaKuList)
  308. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  309. break
  310. case 2:
  311. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  312. this.updateListData(this.artistList)
  313. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  314. break
  315. case 3:
  316. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  317. this.updateListData(this.albumList)
  318. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  319. break
  320. case 4://歌单
  321. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  322. this.updateListData(this.currentSongList, true)
  323. this.titleBarModel.setTitleName(this.currentSongListName)
  324. this.isShowTitleBar = false
  325. break
  326. }
  327. }
  328. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  329. // @StorageLink('isPlay') isPlay: boolean = false;
  330. @StorageLink('isShowPlay') isShowPlay: boolean = false;
  331. @StorageLink('songList') songList: Array<VideoItem> = [];
  332. @State translateY: number = 0;
  333. @State isShowSheet: boolean = false;
  334. @State isShowSheetView: boolean = false;
  335. @State isShowTimeCloseView: boolean = false;
  336. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  337. @StorageLink('currIndex') curIndex: number = 0;
  338. @Consume isShowDrawer: boolean;
  339. @Consume offsetX: number;
  340. @State isFac: boolean = false;
  341. @State favList: Array<VideoItem> = []
  342. @Consume isFavMusic: boolean
  343. @State isClickedPLayAll: boolean = false;
  344. private scrollerForlist: ListScroller = new ListScroller();
  345. private knockController: KnockController | undefined = undefined;
  346. imagesF: ImageFrameInfo[] = [
  347. { src: $r("app.media.app_loading0") },
  348. { src: $r("app.media.app_loading1") },
  349. { src: $r("app.media.app_loading2") },
  350. { src: $r("app.media.app_loading3") },
  351. ]
  352. @State animationState: AnimationStatus = AnimationStatus.Initial
  353. // 缓存机制
  354. private cache: Map<string, Array<VideoItem>> = new Map();
  355. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  356. // 持久化缓存
  357. private async saveCacheToStorage() {
  358. const cacheArray = Array.from(this.cache.entries());
  359. const stringCacheArray = Array.from(this.stringCache.entries());
  360. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  361. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  362. }
  363. // 载入缓存
  364. private async loadCacheFromStorage() {
  365. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  366. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  367. if (cacheString) {
  368. const cacheArray: [string, Array<VideoItem>][] = JSON.parse(cacheString);
  369. this.cache = new Map(cacheArray);
  370. }
  371. if (stringCacheString) {
  372. const stringCacheArray: [string, string][] = JSON.parse(stringCacheString);
  373. this.stringCache = new Map(stringCacheArray);
  374. }
  375. }
  376. // 查找缓存
  377. private findCache(key: string): Array<VideoItem> | undefined {
  378. return this.cache.get(key);
  379. }
  380. // 查找字符串缓存
  381. private findStringCache(key: string): string | undefined {
  382. return this.stringCache.get(key);
  383. }
  384. // 添加缓存
  385. private addCache(key: string, value: Array<VideoItem>) {
  386. this.cache.set(key, value);
  387. }
  388. // 添加字符串缓存
  389. private addStringCache(key: string, value: string) {
  390. this.stringCache.set(key, value);
  391. }
  392. // 删除缓存
  393. private deleteCache(key: string) {
  394. this.cache.delete(key);
  395. this.saveCacheToStorage()
  396. }
  397. // 删除字符串缓存
  398. private deleteStringCache(key: string) {
  399. this.stringCache.delete(key);
  400. }
  401. // 多选机制
  402. @State selectedFiles: Array<VideoItem> = [];
  403. @State isMultiSelect: boolean = false;
  404. @State isAllSelected: boolean = false;
  405. @State appName: string = ''
  406. @State isHasDir: boolean = false
  407. @State packName: string = ''
  408. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  409. @State titleBarModel: TitleBar.Model = new TitleBar.Model()
  410. .setTitleTextStyle(FontStyle.Normal)
  411. .setTitleBarStyle(TitleBar.BarStyle.TRANSPARENT)
  412. .setLeftIcon($r('app.media.menu'))
  413. .setLeftIconWidth(26)
  414. .setLeftIconHeight(26)
  415. .setTitleName('首页')
  416. .setTitleFontSize(18)
  417. .setTitleFontColor(Color.White)
  418. .setTitleBarBackground(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  419. .setTitleBarBottomLineColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  420. .setLeftTitleStateNormalStyleColor(this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor)
  421. .setRightIcon($r('app.media.add'))
  422. .setOnRightClickListener(() => {
  423. this.showSheelDialog()
  424. })
  425. // .setOnTitleClickListener(() => {
  426. // this.showPupDialog()
  427. // })
  428. .setOnLeftClickListener(() => {
  429. this.doSwipBack()
  430. })
  431. doSwipBack() {
  432. this.isZero = false
  433. if (this.modeType !== 0 && this.isCanBack) {
  434. this.onModeChange()
  435. this.isCanBack = false
  436. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  437. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  438. setTimeout(() => {
  439. if (this.modeType == 2) {
  440. if (this.isGridMusic||this.twoFingerType==4) {
  441. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  442. let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
  443. if(this.twoFingerType==4){
  444. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  445. }else{
  446. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  447. }
  448. } else {
  449. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  450. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  451. }
  452. } else if (this.modeType == 3) {
  453. if (this.isGridMusic||this.twoFingerType==4) {
  454. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  455. let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 0
  456. if(this.twoFingerType==4){
  457. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  458. }else{
  459. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  460. }
  461. } else {
  462. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  463. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  464. }
  465. }
  466. }, 200)
  467. return
  468. }
  469. if (this.isHistory || this.isFavMusic) {
  470. this.isHistory = false
  471. this.getSortedFiles(this.currentPath)
  472. return
  473. }
  474. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  475. animateTo({ duration: 555 }, () => {
  476. // 动画闭包内控制Image组件的出现和消失
  477. this.isShowDrawer = !this.isShowDrawer
  478. this.offsetX = 0
  479. })
  480. return
  481. }
  482. //返回上一级歌单的滚动位置
  483. setTimeout(() => {
  484. if (this.modeType == 0) {
  485. if (this.isGridMusic||this.twoFingerType==4) {
  486. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  487. let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 0
  488. if(this.twoFingerType==4){
  489. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  490. }else{
  491. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  492. }
  493. } else {
  494. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  495. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  496. }
  497. }
  498. }, 300)
  499. this.currentPath = Utility.getParentDirectory(this.currentPath)
  500. Logger.info('this.currentPath2 = ' + this.currentPath)
  501. this.getSortedFiles(this.currentPath)
  502. }
  503. // 组件生命周期
  504. aboutToAppear() {
  505. // 初始化 PlaylistTable
  506. this.playlistTable = new PlaylistTable(getContext(this))
  507. this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
  508. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  509. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  510. this.tipPopup = !this.tipPopup
  511. PreferencesUtil.putSync('isFirstTiped',false)
  512. }
  513. this.initSetting()
  514. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  515. this.topRectHeight = px2vp(AppUtil.getStatusBarHeight());
  516. Utility.getAppName(getContext(this)).then((appName: string) => {
  517. this.appName = appName
  518. })
  519. this.packName = AppUtil.getBundleName()
  520. this.tabSelectedIndexes[0] = this.modeType//SegmentButton的索引
  521. this.loadCacheFromStorage(); // 加载文件夹缓存
  522. // 在首页初始化时读取媒体库,艺术家,专辑等缓存数据
  523. this.initLoadCache()
  524. this.mkDownLoadDir()
  525. let eventMusic: emitter.InnerEvent = { eventId: EventConstants.EVENT_AUDIO_OPEN }
  526. // 监听广播事件(打开其他应用处理)
  527. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  528. this.saveVideoDatas([eventData.data?.message], true)
  529. });
  530. //侧滑广播接收时间
  531. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_UPDATE }
  532. // 监听广播事件(打开其他应用处理)
  533. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  534. animateTo({ duration: 555 }, () => {
  535. this.doSwipBack()
  536. })
  537. });
  538. //ScanFilePage广播接收时间
  539. let eventScanUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_SCAN_UPDATE }
  540. // 监听ScanFilePage广播事件(更新数据库)
  541. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  542. this.doUpdateData()
  543. });
  544. // 监听歌单播放请求事件
  545. let eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY }
  546. emitter.on(eventPlaylistPlay, (eventData: emitter.EventData) => {
  547. Logger.info('heanup eventPlaylistPlay received - full eventData: ' + JSON.stringify(eventData))
  548. Logger.info('heanup eventPlaylistPlay received - eventData.data: ' + JSON.stringify(eventData.data))
  549. const data = eventData.data as Record<string, Object>
  550. if (!data) {
  551. Logger.error('heanup eventPlaylistPlay: eventData.data is undefined or null')
  552. return
  553. }
  554. // 检查歌单播放数据结构
  555. if (data.playlistId && data.songFilePaths && data.startIndex !== undefined) {
  556. Logger.info('heanup eventPlaylistPlay: 接收到歌单播放数据')
  557. // 手动构建数据对象以避免类型转换问题
  558. const playlistData: PlaylistEventData = {
  559. playlistId: data.playlistId as string,
  560. playlistName: data.playlistName as string,
  561. songCount: data.songCount as number,
  562. startIndex: data.startIndex as number,
  563. songFilePaths: data.songFilePaths as string[]
  564. }
  565. // 根据文件路径重新构建歌曲列表
  566. this.handlePlaylistPlayRequest(
  567. playlistData.playlistId,
  568. playlistData.playlistName,
  569. playlistData.songFilePaths,
  570. playlistData.startIndex
  571. )
  572. return
  573. }
  574. Logger.error('heanup eventPlaylistPlay: 接收到无效的数据结构')
  575. });
  576. let eventSetting: emitter.InnerEvent = { eventId: EventConstants.EVENT_SETTING_UPDATE }
  577. // 监听广播事件(通用设置配置更新)
  578. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  579. this.doChangeSetting()
  580. });
  581. let event: Callback<InterruptEvent> = (event) => {
  582. // LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  583. console.info(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
  584. this.savePlaybackPosition()
  585. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  586. this.pause();
  587. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  588. console.info(`onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
  589. console.info('onecold startPlayOrResumePlay 514')
  590. this.startPlayOrResumePlay();
  591. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  592. this.stop();
  593. }
  594. }
  595. this.mIjkMediaPlayer.on('audioInterrupt', event);
  596. // 音频设备断连回调处理
  597. // let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  598. // LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  599. // if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  600. // this.pause();
  601. // }
  602. // }
  603. // this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  604. this.makeWorker()
  605. //折叠屏的屏幕显示模式变化
  606. display.on('foldDisplayModeChange', (data) => {
  607. this.doChangeBarHeight()
  608. });
  609. display.on('foldStatusChange', (data) => {
  610. Logger.info('onecold foldStatusChange ')
  611. });
  612. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  613. // 读取 themeMode 并同步 currentColorMode
  614. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  615. this.applyThemeMode(this.themeMode)
  616. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  617. AppStorage.setOrCreate('themeColor', themeColor);
  618. this.themeColor = themeColor;
  619. this.doChangeSetting()
  620. this.windowClass.on('windowSizeChange', (size) => {
  621. LogUtil.info('onecold windowSizeChange')
  622. this.doChangeBarHeight()
  623. let viewWidth = px2vp(size.width);
  624. let viewHeight = px2vp(size.height);
  625. if(this.isPhoneLan()){
  626. this.is_auto_hide_progress = false
  627. if(this.isHiCar()){
  628. return
  629. }
  630. setTimeout(() => {
  631. this.is_auto_hide_progress = true
  632. }, 6000)
  633. }else{
  634. this.startAutoHide()
  635. }
  636. });
  637. this.eventHub.on('onStateChange', (fg: boolean) => {
  638. if (fg && this.curState === 'STARTED') {
  639. this.stopPip();
  640. }
  641. });
  642. }
  643. //载入媒体库,艺术家,专辑等缓存
  644. initLoadCache(){
  645. this.mediaKuCount = PreferencesUtil.getNumberSync('mediaKuCount', 0)
  646. this.artistCount = PreferencesUtil.getNumberSync('artistCount', 0)
  647. this.albumCount = PreferencesUtil.getNumberSync('albumCount', 0)
  648. let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
  649. let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
  650. if(ArrayUtil.isNotEmpty(cachedList)){
  651. this.mediaKuList = cachedList
  652. if(this.modeType==1){
  653. this.updateListData(this.mediaKuList)
  654. }
  655. }
  656. let artistListStr:string = PreferencesUtil.getStringSync('artistList', '[]');
  657. let artistCachedList = JSON.parse(artistListStr) as Array<VideoItem>;
  658. if(ArrayUtil.isNotEmpty(artistCachedList)){
  659. this.artistList = artistCachedList
  660. let artistMapStr:string = PreferencesUtil.getStringSync('artistMap', '[]');
  661. const parsedArray = JSON.parse(artistMapStr) as [string, VideoItem[]][];
  662. this.artistMap = new Map(parsedArray);
  663. // this.artistMap = JSON.parse(artistMapStr) as Map<string, VideoItem[]>;
  664. if(this.modeType==2){
  665. this.updateListData(this.artistList)
  666. }
  667. }
  668. let albumListStr:string = PreferencesUtil.getStringSync('albumList', '[]');
  669. let albumCachedList = JSON.parse(albumListStr) as Array<VideoItem>;
  670. if(ArrayUtil.isNotEmpty(albumCachedList)){
  671. this.albumList = albumCachedList
  672. let albumMapStr:string = PreferencesUtil.getStringSync('albumMap', '[]');
  673. const parsedArray = JSON.parse(albumMapStr) as [string, VideoItem[]][];
  674. this.albumMap = new Map(parsedArray);
  675. if(this.modeType==3){
  676. this.updateListData(this.albumList)
  677. }
  678. }
  679. }
  680. startAutoHide() {
  681. if(this.isHiCar()){
  682. return
  683. }
  684. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  685. console.info('onecold startAutoHide')
  686. this.is_auto_hide_progress = false
  687. setTimeout(() => {
  688. this.is_auto_hide_progress = true
  689. }, 6000)
  690. }
  691. }
  692. applyThemeMode(mode: number) {
  693. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  694. if (mode === 1) {
  695. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  696. } else if (mode === 2) {
  697. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  698. }
  699. AppStorage.setOrCreate('currentColorMode', colorMode)
  700. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  701. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  702. AppStorage.setOrCreate('themeMode', mode)
  703. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  704. // 只有强制浅色/深色时才主动设置
  705. const context = getContext(this) as common.UIAbilityContext
  706. context.getApplicationContext().setColorMode(colorMode)
  707. }
  708. initSetting() {
  709. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  710. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  711. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  712. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, false)
  713. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  714. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  715. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  716. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  717. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  718. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  719. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  720. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  721. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  722. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 2)
  723. this.isCoverTop = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP, true)
  724. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  725. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  726. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  727. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  728. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  729. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  730. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  731. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  732. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  733. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  734. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  735. this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
  736. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  737. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  738. this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
  739. this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
  740. if(this.volumeSmall){
  741. this.volume = 0.5
  742. }else{
  743. this.volume = 1
  744. }
  745. //如果是hicar连接状态,这些都是false
  746. if(this.isHiCar()){
  747. this.isShowTitleBar = false//不显示导航栏
  748. this.columns=4
  749. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  750. {
  751. this.isShowHeader = false//二级菜单不显示头部
  752. this.isGridMusic= false//用list不用网格
  753. this.isCoverTopBig = false
  754. }
  755. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  756. }
  757. if (this.isSavePlayMode) {
  758. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  759. }
  760. if (this.isCustomizeBg) {
  761. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  762. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  763. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  764. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  765. } else {
  766. if (!this.isDarkMode) {
  767. this.titleBarModel.setTitleBarBackground(this.themeColor)
  768. this.titleBarModel.setTitleBarBottomLineColor(this.themeColor)
  769. this.titleBarModel.setRightTitleStateNormalStyleColor(this.themeColor)
  770. this.titleBarModel.setLeftTitleStateNormalStyleColor(this.themeColor)
  771. } else {
  772. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  773. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  774. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  775. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  776. }
  777. }
  778. }
  779. doChangeSetting() {
  780. this.initSetting()
  781. this.deleteCache(this.currentPath)
  782. if (this.modeType === 0) {
  783. this.getSortedFiles(this.currentPath)
  784. }
  785. }
  786. doChangeBarHeight() {
  787. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  788. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  789. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  790. this.setBarHeightNormal()
  791. }
  792. }
  793. onPageShow() {
  794. this.knockController?.immersiveListening();
  795. app.setImageCacheCount(100);
  796. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  797. app.setImageRawDataCacheSize(104857600);
  798. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  799. }
  800. //开启线程查看各个数据库
  801. makeWorker() {
  802. setTimeout(() => {
  803. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  804. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  805. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  806. // workerInstance.postMessage({
  807. // code: 1,
  808. // data1: this.context,
  809. // data2: this.rootPath,
  810. // data3: this.lockPath,
  811. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  812. // data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  813. // });
  814. PreferencesUtil.putSync('isFirstApp', false)
  815. } else {
  816. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  817. workerInstance.postMessage({ code: 3, data: this.context });
  818. workerInstance.postMessage({ code: 4, data: this.context });
  819. this.getHistoryList(false)
  820. }
  821. }, 1000)
  822. workerInstance.onmessage = (e: MessageEvents): void => {
  823. switch (e.data.code) {
  824. case 101: //第一次扫描文件夹入库
  825. ToastUtil.showToast('刷新同步数据库成功!')
  826. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  827. this.doUpdateData()
  828. break;
  829. case 102: //查询媒体库列表
  830. this.isRefreshing = false
  831. this.mediaKuList = e.data.data
  832. Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
  833. Utility.doSortListAscending(this.mediaKuList)
  834. // AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  835. if (this.modeType === 1) {
  836. this.updateListData(this.mediaKuList)
  837. }
  838. PreferencesUtil.putSync('mediaKuCount', this.mediaKuList.length)
  839. // 处理媒体库前100条记录,列表长度并存储到PreferencesUtil
  840. if (ArrayUtil.isNotEmpty(this.mediaKuList)&&this.mediaKuList.length > 100) {
  841. // 只保存前100条记录到缓存中
  842. let truncatedList = this.mediaKuList.slice(0, 100);
  843. PreferencesUtil.putSync('mediaKuList', JSON.stringify(truncatedList));
  844. } else {
  845. PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
  846. }
  847. break;
  848. case 103: //收到查询艺术家列表
  849. this.isRefreshing = false
  850. this.artistMap = e.data.data1;
  851. this.artistList = e.data.data2;
  852. PreferencesUtil.putSync('artistCount', this.artistList.length)
  853. // 处理艺术家前100条记录,列表长度并存储到PreferencesUtil
  854. if (ArrayUtil.isNotEmpty(this.artistList)&&this.artistList.length > 100) {
  855. // 只保存前100条记录到缓存中
  856. let truncatedList = this.artistList.slice(0, 100);
  857. PreferencesUtil.putSync('artistList', JSON.stringify(truncatedList));
  858. } else {
  859. PreferencesUtil.putSync('artistList', JSON.stringify(this.artistList));
  860. }
  861. // 处理并缓存前60条艺术家数据
  862. const sortedEntries = Array.from(this.artistMap.entries())
  863. .sort((a, b) => b[1].length - a[1].length)
  864. .slice(0, 60);
  865. PreferencesUtil.putSync('artistMap', JSON.stringify(sortedEntries));
  866. break;
  867. case 104: //收到查询专辑列表
  868. this.isRefreshing = false
  869. this.albumMap = e.data.data1;
  870. this.albumList = e.data.data2
  871. //查询完毕在启动是否自动播放
  872. if (this.isStartAutoPlay&&this.isCanAuto) {
  873. this.isCanAuto = false
  874. console.info('onecold startPlayOrResumePlay 757')
  875. this.startPlayOrResumePlay()
  876. }
  877. PreferencesUtil.putSync('albumCount', this.albumList.length)
  878. // 处理专辑前100条记录,列表长度并存储到PreferencesUtil
  879. if (ArrayUtil.isNotEmpty(this.albumList)&&this.albumList.length > 100) {
  880. // 只保存前100条记录到缓存中
  881. let truncatedList = this.albumList.slice(0, 100);
  882. PreferencesUtil.putSync('albumList', JSON.stringify(truncatedList));
  883. } else {
  884. PreferencesUtil.putSync('albumList', JSON.stringify(this.albumList));
  885. }
  886. const mapArrayAlbum = Array.from(this.albumMap.entries())
  887. .sort((a, b) => b[1].length - a[1].length)
  888. .slice(0, 60);
  889. PreferencesUtil.putSync('albumMap', JSON.stringify(mapArrayAlbum));
  890. break;
  891. }
  892. };
  893. // 在调用terminate后,执行onexit
  894. workerInstance.onexit = (code) => {
  895. console.log("main thread terminate");
  896. }
  897. //若Worker处于已销毁或正在销毁等非运行状态时,调用其功能接口,会抛出相应的错误。
  898. // 使用Worker模块时,需要在主线程中注册onerror接口,否则当worker线程出现异常时会发生jscrash问题。
  899. workerInstance.onerror = (err: ErrorEvent) => {
  900. console.log("onerror" + err.message);
  901. }
  902. // let context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
  903. //碰一碰分享的监听
  904. this.knockController = KnockController.getInstance(this.context);
  905. this.knockController?.immersiveListening();
  906. }
  907. onPageHide(): void {
  908. this.knockController?.immersiveDisableListening();
  909. }
  910. @State isFirstStartPlay: boolean = false
  911. //获取download_path
  912. async mkDownLoadDir() {
  913. const documentViewPicker = new picker.DocumentViewPicker()
  914. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  915. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  916. this.currentPath = this.rootPath
  917. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  918. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  919. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  920. Logger.info('onecold rootPath = ' + this.rootPath)
  921. Logger.info('onecold lockPath = ' + this.lockPath)
  922. if (!FileUtil.accessSync(this.lockPath)) {
  923. FileUtil.mkdirSync(this.lockPath)
  924. }
  925. if (!FileUtil.accessSync(this.favPath)) {
  926. FileUtil.mkdirSync(this.favPath)
  927. }
  928. if (!FileUtil.accessSync(this.historyPath)) {
  929. FileUtil.mkdirSync(this.historyPath)
  930. }
  931. this.getSortedFiles(this.rootPath).then(() => {
  932. this.isFavMusic = false
  933. //穿山甲
  934. // this.loadBannerAd(CSJUtil.getBannerID())
  935. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  936. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  937. if (ArrayUtil.isEmpty(this.songList)) {
  938. this.songList = this.getCurFileList()
  939. } else {
  940. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  941. }
  942. if (ArrayUtil.isNotEmpty(this.songList)) {
  943. this.isFirstStartPlay = true
  944. this.sonDataSource.pushArrayData(this.songList)
  945. if (this.currentSong === undefined) {
  946. this.isFirstStartPlay = false
  947. this.currentSong = this.songList[0]
  948. }
  949. this.videoUrl = this.currentSong.filePath
  950. this.name = this.currentSong.name
  951. this.cover = this.currentSong.pixelMapPath
  952. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  953. } else {
  954. this.name = '空空如也'
  955. }
  956. })
  957. this.getFavList(false)
  958. }
  959. getFavList(isFavRefresh: boolean) {
  960. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  961. this.favList = result
  962. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  963. this.videoLocalList = this.favList
  964. this.updateListData(this.videoLocalList)
  965. }
  966. })
  967. }
  968. getHistoryList(isRefresh: boolean) {
  969. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  970. this.historyList = result
  971. // for (let i = 0; i < this.historyList.length; i++) {
  972. //
  973. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  974. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  975. // }
  976. if (isRefresh) {
  977. this.videoLocalList = this.historyList
  978. this.updateListData(this.videoLocalList, true)
  979. }
  980. })
  981. }
  982. // 组件消失生命周期
  983. aboutToDisappear() {
  984. console.info('LifeCycleComponent aboutToDisappear');
  985. this.knockController?.immersiveDisableListening();
  986. this.curIndex = 0
  987. emitter.off(EventConstants.EVENT_AUDIO_OPEN);
  988. emitter.off(EventConstants.EVENT_SCAN_UPDATE);
  989. emitter.off(EventConstants.EVENT_SWIPE_BACK_UPDATE);
  990. emitter.off(EventConstants.EVENT_SETTING_UPDATE);
  991. this.mDestroyPage = true;
  992. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  993. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  994. this.stop();
  995. }
  996. this.mIjkMediaPlayer.off('audioInterrupt');
  997. if (workerInstance) {
  998. workerInstance.terminate();
  999. }
  1000. this.stopPip();
  1001. this.destroyPipController()
  1002. }
  1003. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean) {
  1004. this.isFavMusic = false
  1005. console.info('onecold getSortedFiles 1 curPath '+curPath)
  1006. if (isWorkerPost) {
  1007. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1008. }
  1009. if (this.modeType !== 0) {
  1010. this.openMusic(isOpen, destPath)
  1011. return
  1012. }
  1013. console.info('onecold getSortedFiles 2')
  1014. this.isCanBack = false
  1015. this.currentPath = curPath
  1016. console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
  1017. this.titleBarModel.setTitleName(getFileDirName(this.currentPath, this.rootPath))
  1018. if (curPath === this.rootPath) {
  1019. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1020. } else {
  1021. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  1022. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  1023. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  1024. }
  1025. }
  1026. // Get the current file list and calculate its hash
  1027. this.fileList = FileUtil.listFileSync(curPath);
  1028. const currentHash = simpleHash(this.fileList);
  1029. // Check cache
  1030. const cachedValue = this.findCache(curPath);
  1031. Logger.info('onecold cachedValue = ' + cachedValue)
  1032. const cachedHash = this.findStringCache(curPath + '_hash');
  1033. const cachedDirList = this.findCache(curPath + "_dirList");
  1034. if (cachedValue !== undefined) {
  1035. // this.videoLocalList = cachedValue;
  1036. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  1037. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  1038. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  1039. }
  1040. this.updateListData(cachedValue)
  1041. }
  1042. if (cachedDirList !== undefined) {
  1043. this.dirList = cachedDirList
  1044. }
  1045. //通过当前hash值和缓存hash判断list有没有变化
  1046. if (cachedValue && cachedHash === currentHash) {
  1047. return;
  1048. }
  1049. this.fileList = FileUtil.listFileSync(curPath)
  1050. let directories: Array<VideoItem> = [];
  1051. let files: Array<VideoItem> = [];
  1052. for (let i = 0; i < this.fileList.length; i++) {
  1053. console.info(`The name of file: ${this.fileList[i]}`);
  1054. let path = curPath + '/' + this.fileList[i]
  1055. if (FileUtil.isDirectory(path)) {
  1056. let item: VideoItem =
  1057. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  1058. '')
  1059. if (this.isShowDir(item.name)) {
  1060. directories.push(item);
  1061. }
  1062. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1063. // Utility.doSortListAscending(directories)
  1064. } else {
  1065. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  1066. let item: VideoItem =
  1067. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  1068. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  1069. files.push(item);
  1070. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1071. // this.doSortListAscending(files)
  1072. }
  1073. }
  1074. }
  1075. }
  1076. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  1077. if (this.currentPath !== this.lockPath) {
  1078. files = result;
  1079. }
  1080. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1081. Utility.doSortListAscending(files)
  1082. if (this.currentPath === this.rootPath) {
  1083. this.dirList = directories
  1084. this.addCache(curPath + "_dirList", this.dirList);
  1085. }
  1086. //插入广告先注释掉
  1087. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  1088. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  1089. // directories.push(adItem)
  1090. // }
  1091. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  1092. this.videoLocalList = directories.concat(files);
  1093. this.updateListData(this.videoLocalList)
  1094. if (ArrayUtil.isNotEmpty(files)) {
  1095. if (this.currentPath != this.rootPath) {
  1096. if (files) {
  1097. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  1098. }
  1099. }
  1100. // 缓存结果
  1101. this.addCache(curPath, this.videoLocalList);
  1102. await this.saveCacheToStorage(); // 保存缓存至本地存储
  1103. this.addStringCache(curPath + '_hash', currentHash);
  1104. }
  1105. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  1106. // for (let i = 0; i < this.videoLocalList.length; i++) {
  1107. //
  1108. // console.info(`onecold gengxin 1: ${this.videoLocalList[i].pixelMapPath}`);
  1109. //
  1110. // }
  1111. // this.setButtonStatus()
  1112. this.openMusic(isOpen, destPath)
  1113. });
  1114. }
  1115. //第三方app打开天天静听导入音乐后播放
  1116. openMusic(isOpen?: boolean, destPath?: string){
  1117. if (isOpen&&destPath) {
  1118. if (destPath === undefined) {
  1119. // 处理 destPath 为 undefined 的情况
  1120. return
  1121. }
  1122. if (destPath.endsWith('.lrc')) {
  1123. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  1124. if (StrUtil.isNotEmpty(this.videoUrl)) {
  1125. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  1126. this.initLyric(lyricPath);
  1127. }
  1128. return
  1129. }
  1130. let item2 = new VideoItem(Utility.getMediaNameByUri(destPath), destPath, destPath, 0, 0, '')
  1131. this.doPlay(item2,0,false,true)
  1132. this.isShowPlay = true
  1133. }
  1134. }
  1135. //扫描文件夹入库
  1136. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  1137. const files = FileUtil.listFileSync(curPath);
  1138. let mediaItems: VideoItem[] = [];
  1139. Logger.info('onecold scanDirectory start ')
  1140. for (const file of files) {
  1141. const fPath = `${curPath}/${file}`;
  1142. if (fPath === this.lockPath) {
  1143. Logger.info(`Skipping locked path: ${fPath}`);
  1144. continue;
  1145. }
  1146. if (FileUtil.isDirectory(fPath)) {
  1147. // Recursively scan subdirectories
  1148. const subDirItems = await this.scanDirectory(fPath);
  1149. mediaItems = mediaItems.concat(subDirItems);
  1150. } else {
  1151. Logger.info('onecold scanDirectory filePath = ' + fPath)
  1152. // Process media files
  1153. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  1154. let mediaItem: VideoItem =
  1155. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1156. mediaItems.push(mediaItem);
  1157. this.table.insert(mediaItem, (id: number) => {
  1158. });
  1159. }
  1160. }
  1161. }
  1162. return mediaItems;
  1163. }
  1164. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  1165. animateTo({ duration: 888 }, () => {
  1166. this.opacityItem = 0;
  1167. });
  1168. setTimeout(() => {
  1169. this.videoLocalList = mList;
  1170. if (!noSort) {
  1171. if (this.modeType === 0 || this.modeType === 1) {
  1172. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1173. this.doSortType(this.sortType)
  1174. }
  1175. }
  1176. this.dataSource.pushArrayData(this.videoLocalList)
  1177. animateTo({ duration: 888 }, () => {
  1178. this.opacityItem = 1;
  1179. });
  1180. this.setButtonStatus()
  1181. }, 200);
  1182. }
  1183. //排序模式和多选模式
  1184. showPupDialog() {
  1185. if (this.modeType === 2 || this.modeType === 3) {
  1186. this.titleBarModel.setRightIcon(null)
  1187. } else {
  1188. this.titleBarModel.setRightIcon(($r('app.media.add')))
  1189. }
  1190. let dataBean = new BubbleBean()
  1191. dataBean.data = ["首页", "媒体库", "艺术家", "专辑", "同步数据"]
  1192. dataBean.color = this.themeColor
  1193. dataBean.modeType = this.modeType
  1194. dataBean.imageRes =
  1195. [$r('app.media.home_press'), $r('app.media.kp_music'), $r('app.media.music_menu'), $r('app.media.llq'),
  1196. $r('app.media.refresh')]
  1197. let pup: XPopup;
  1198. if (this.isDarkMode) {
  1199. pup = XPopup.Builder()
  1200. .setPopupPosition(PopupPosition.BOTTOM)
  1201. .atView('pup_positon_music')
  1202. .setBackgroundColor(Color.Black)
  1203. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  1204. .show()
  1205. } else {
  1206. pup = XPopup.Builder()
  1207. .setPopupPosition(PopupPosition.BOTTOM)
  1208. .atView('pup_positon_music')
  1209. .setBackgroundColor(Color.White)
  1210. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  1211. .show()
  1212. }
  1213. dataBean.onItemClick = (i) => {
  1214. XPopup.dismissTop()
  1215. switch (i) {
  1216. case 0: //首页
  1217. this.modeType = 0
  1218. this.getSortedFiles(this.currentPath)
  1219. break
  1220. case 1:
  1221. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1222. this.modeType = 1
  1223. this.updateListData(this.mediaKuList)
  1224. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  1225. break
  1226. case 2:
  1227. this.modeType = 2
  1228. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1229. this.updateListData(this.artistList)
  1230. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  1231. break
  1232. case 3:
  1233. this.modeType = 3
  1234. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  1235. this.updateListData(this.albumList)
  1236. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  1237. break
  1238. case 4: //同步数据
  1239. // this.asyncCurrentPathData()
  1240. break
  1241. }
  1242. }
  1243. }
  1244. getCurFileList(): Array<VideoItem> {
  1245. if(this.isSearchMode){
  1246. return this.filteredList
  1247. }
  1248. let files: Array<VideoItem> = [];
  1249. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1250. for (let i = 0; i < this.videoLocalList.length; i++) {
  1251. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  1252. files.push(this.videoLocalList[i]);
  1253. }
  1254. }
  1255. }
  1256. return files
  1257. }
  1258. setButtonStatus() {
  1259. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1260. this.isZero = false
  1261. } else {
  1262. this.isZero = true
  1263. }
  1264. if (this.currentPath !== this.rootPath &&
  1265. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  1266. this.isHasDir = true //不为空,说明有子文件夹
  1267. } else {
  1268. this.isHasDir = false
  1269. }
  1270. }
  1271. showRankDialog() {
  1272. if ((this.modeType === 2&&!this.isCanBack) || (this.modeType === 3&&!this.isCanBack)) {
  1273. //动作面板
  1274. DialogHelper.showBottomSheetDialog({
  1275. title: "请选择排序模式",
  1276. maskColor: Color.Transparent,
  1277. // sheets: ["按名称升序", "按名称降序"],
  1278. sheets: [
  1279. { value: '按名称升序', fontColor: $r('app.color.text_color') },
  1280. { value: '按名称降序', fontColor: $r('app.color.text_color') },
  1281. { value: '按数量升序', fontColor: $r('app.color.text_color') },
  1282. { value: '按数量降序', fontColor: $r('app.color.text_color') },
  1283. ],
  1284. backgroundColor: $r('app.color.bg_card'),
  1285. height: '45%',
  1286. transition: AnimationHelper.transitionInDown(555),
  1287. onAction: (index) => {
  1288. switch (index) {
  1289. case 0:
  1290. Utility.doSortListAscending(this.videoLocalList,this.isShowFileName)
  1291. break;
  1292. case 1:
  1293. Utility.doSortListDescending(this.videoLocalList,this.isShowFileName)
  1294. break;
  1295. case 2:
  1296. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  1297. // 1. Sort by type first
  1298. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  1299. if (typeOrder !== 0) {
  1300. return typeOrder;
  1301. }
  1302. // 2. Then sort by artist count (numeric comparison)
  1303. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  1304. if(this.modeType === 2){
  1305. sortMap = this.artistMap
  1306. }else{
  1307. sortMap = this.albumMap
  1308. }
  1309. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  1310. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  1311. return aArtistCount - bArtistCount;
  1312. });
  1313. break;
  1314. case 3:
  1315. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  1316. // 1. Sort by type first
  1317. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  1318. if (typeOrder !== 0) {
  1319. return typeOrder;
  1320. }
  1321. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  1322. if(this.modeType === 2){
  1323. sortMap = this.artistMap
  1324. }else{
  1325. sortMap = this.albumMap
  1326. }
  1327. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  1328. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  1329. return bArtistCount - aArtistCount;
  1330. });
  1331. break;
  1332. }
  1333. this.updateListData(this.videoLocalList)
  1334. }
  1335. })
  1336. return
  1337. }
  1338. //动作面板
  1339. DialogHelper.showBottomSheetDialog({
  1340. title: "请选择排序模式",
  1341. maskColor: Color.Transparent,
  1342. height: '75%',
  1343. // sheets: ["按艺术家升序", "按艺术家降序", "按专辑升序", "按专辑降序", "按名称升序", "按名称降序", "按添加时间升序","按添加时间降序"],
  1344. sheets: [
  1345. { value: "按艺术家升序", fontColor: $r('app.color.text_color') },
  1346. { value: "按艺术家降序", fontColor: $r('app.color.text_color') },
  1347. { value: "按专辑升序", fontColor: $r('app.color.text_color') },
  1348. { value: "按专辑降序", fontColor: $r('app.color.text_color') },
  1349. { value: "按名称升序", fontColor: $r('app.color.text_color') },
  1350. { value: "按名称降序", fontColor: $r('app.color.text_color') },
  1351. { value: "按添加时间升序", fontColor: $r('app.color.text_color') },
  1352. { value: "按添加时间降序", fontColor: $r('app.color.text_color') },
  1353. ],
  1354. backgroundColor: $r('app.color.bg_card'),
  1355. transition: AnimationHelper.transitionInDown(555),
  1356. onAction: (index) => {
  1357. this.doSortType(index)
  1358. PreferencesUtil.put(SettingPage.SORT_TYPE, index)
  1359. this.updateListData(this.videoLocalList, true)
  1360. }
  1361. })
  1362. }
  1363. doSortType(index: number) {
  1364. switch (index) {
  1365. case 0:
  1366. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1367. // 类型排序优先级
  1368. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1369. if (typeOrder !== 0) {
  1370. return typeOrder;
  1371. }
  1372. // 处理艺术家可能为undefined的字符串比较
  1373. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1374. const artistB = b.artist?.trim() || '';
  1375. return artistA.localeCompare(artistB);
  1376. });
  1377. break;
  1378. case 1:
  1379. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1380. // 类型排序优先级
  1381. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1382. if (typeOrder !== 0) {
  1383. return typeOrder;
  1384. }
  1385. // 处理艺术家可能为undefined的字符串比较
  1386. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1387. const artistB = b.artist?.trim() || '';
  1388. return artistB.localeCompare(artistA);
  1389. });
  1390. break;
  1391. case 2:
  1392. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1393. // 类型排序优先级
  1394. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1395. if (typeOrder !== 0) {
  1396. return typeOrder;
  1397. }
  1398. // 处理专辑可能为undefined的字符串比较
  1399. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1400. const albumB = b.album?.trim() || '';
  1401. return albumA.localeCompare(albumB);
  1402. });
  1403. break;
  1404. case 3:
  1405. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  1406. // 类型排序优先级
  1407. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1408. if (typeOrder !== 0) {
  1409. return typeOrder;
  1410. }
  1411. // 处理专辑可能为undefined的字符串比较
  1412. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1413. const albumB = b.album?.trim() || '';
  1414. return albumB.localeCompare(albumA);
  1415. });
  1416. break;
  1417. case 4:
  1418. Utility.doSortListAscending(this.videoLocalList,this.isShowFileName)
  1419. break;
  1420. case 5:
  1421. Utility.doSortListDescending(this.videoLocalList,this.isShowFileName)
  1422. break;
  1423. case 6:
  1424. this.videoLocalList.sort((a, b) => {
  1425. // First, sort by type
  1426. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1427. if (typeOrder !== 0) {
  1428. return typeOrder;
  1429. }
  1430. // If types are the same, sort by cTime in ascending order
  1431. return a.cTime.localeCompare(b.cTime);
  1432. });
  1433. break;
  1434. case 7:
  1435. this.videoLocalList.sort((a, b) => {
  1436. // First, sort by type
  1437. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1438. if (typeOrder !== 0) {
  1439. return typeOrder;
  1440. }
  1441. // If types are the same, sort by cTime in descending order
  1442. return b.cTime.localeCompare(a.cTime);
  1443. });
  1444. break;
  1445. }
  1446. }
  1447. showSheelDialog() {
  1448. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  1449. // this.showTips()
  1450. // return
  1451. // }
  1452. this.showAddDialog()
  1453. }
  1454. showAddDialog() {
  1455. if (this.modeType === 2 || this.modeType === 3) {
  1456. return
  1457. }
  1458. DialogHelper.showActionSheetDialog({
  1459. title: "请选择添加方式(建议歌词文件一起导入)",
  1460. // sheets: ["新建歌单", "手动导入", "自动导入"],
  1461. sheets: [
  1462. { value: "新建歌单", fontColor: $r('app.color.text_color') },
  1463. { value: "手动导入", fontColor: $r('app.color.text_color') },
  1464. { value: "自动导入", fontColor: $r('app.color.text_color') },
  1465. { value: "全选导入", fontColor: $r('app.color.text_color') },
  1466. ],
  1467. maskColor: Color.Transparent,
  1468. backgroundColor: $r('app.color.bg_card'),
  1469. transition: AnimationHelper.transitionInDown(555),
  1470. onAction: (index) => {
  1471. switch (index) {
  1472. case 0:
  1473. if (this.modeType === 0) {
  1474. this.showMkDialog()
  1475. } else {
  1476. ToastUtil.showToast('请切换到首页才能新建歌单!')
  1477. }
  1478. break;
  1479. case 1:
  1480. this.callFilePickerSelectFile()
  1481. break;
  1482. case 2:
  1483. this.showTips()
  1484. break;
  1485. case 3:
  1486. this.goSelectMusic()
  1487. break;
  1488. }
  1489. }
  1490. })
  1491. }
  1492. //拉起音频
  1493. goSelectMusic() {
  1494. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  1495. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  1496. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  1497. ) {
  1498. ToastUtil.showToast('暂时不支持该设备')
  1499. return
  1500. }
  1501. try {
  1502. let documentSelectOptions = new picker.DocumentSelectOptions();
  1503. documentSelectOptions.authMode = true
  1504. documentSelectOptions.multiAuthMode = true
  1505. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  1506. let documentPicker = new picker.DocumentViewPicker(this.context);
  1507. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  1508. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  1509. this.saveVideoDatas(documentSelectResult)
  1510. }
  1511. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  1512. JSON.stringify(documentSelectResult));
  1513. }).catch((err: BusinessError) => {
  1514. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  1515. });
  1516. } catch (error) {
  1517. let err: BusinessError = error as BusinessError;
  1518. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1519. }
  1520. }
  1521. async showTips() {
  1522. DialogHelper.showTipsDialog({
  1523. title: '使用提示:自动导入教程',
  1524. content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  1525. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  1526. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  1527. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  1528. onAction: (action) => {
  1529. if (action == DialogAction.TWO) {
  1530. PreferencesUtil.putSync('isFirstMusic', false)
  1531. router.pushUrl({
  1532. url: 'pages/ScanFilePage'
  1533. });
  1534. }
  1535. }
  1536. })
  1537. }
  1538. showMkDialog() {
  1539. DialogHelper.showTextInputDialog({
  1540. title: '新建歌单',
  1541. maskColor: Color.Transparent,
  1542. text: '',
  1543. transition: AnimationHelper.transitionInDown(666),
  1544. onChange: (text) => {
  1545. console.error("onChange: " + text);
  1546. },
  1547. onAction: (action, dialogId, content) => {
  1548. // ToastUtil.showToast('content = ' +content)
  1549. if (action == DialogAction.TWO) {
  1550. const newName = content
  1551. const newPath = this.currentPath + '/' + newName
  1552. FileUtil.mkdir(newPath, true).then(() => {
  1553. this.cache.delete(this.currentPath); // 删除目标路径缓存
  1554. this.getSortedFiles(this.currentPath)
  1555. }).catch((error: BusinessError) => {
  1556. console.error(error.message);
  1557. });
  1558. }
  1559. }
  1560. })
  1561. }
  1562. @State progress: number = 0;
  1563. async saveVideoDatas(uris: string[], isOpen?: boolean) {
  1564. if (ArrayUtil.isEmpty(uris)) {
  1565. return;
  1566. }
  1567. let newUris: string[] = [];
  1568. this.progress = 0
  1569. DialogHelper.showLoadingProgress({
  1570. progress: this.progress,
  1571. backCancel: false,
  1572. autoCancel: false,
  1573. loadColor: this.themeColor,
  1574. fontColor: this.themeColor
  1575. });
  1576. // 计算所有文件的总大小
  1577. let totalSize = 0;
  1578. for (let uri of uris) {
  1579. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  1580. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  1581. await fileIo.close(sourceFile.fd);
  1582. }
  1583. let totalRead = 0;
  1584. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  1585. Logger.info(TAG, 'destPath uri: ' + destPath);
  1586. for (let i = 0; i < uris.length; i++) {
  1587. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  1588. Logger.info(TAG, 'filePath uri: ' + filePath);
  1589. newUris.push(filePath);
  1590. try {
  1591. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  1592. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  1593. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  1594. const buffer = new ArrayBuffer(buffSize);
  1595. let len = await fileIo.read(sourceFile.fd, buffer);
  1596. while (len > 0) {
  1597. await fileIo.write(destFile.fd, buffer.slice(0, len));
  1598. totalRead += len;
  1599. // 计算总进度
  1600. this.progress = Math.floor((totalRead / totalSize) * 100);
  1601. DialogHelper.updateLoading('正在导入', this.progress);
  1602. len = await fileIo.read(sourceFile.fd, buffer);
  1603. }
  1604. await fileIo.close(sourceFile.fd);
  1605. await fileIo.close(destFile.fd);
  1606. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  1607. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  1608. let mediaItem: VideoItem =
  1609. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1610. this.table.insert(mediaItem, (id: number) => {
  1611. // 删除目标路径缓存
  1612. this.cache.delete(this.currentPath);
  1613. this.getSortedFiles(this.currentPath, true, destPath, isOpen)
  1614. });
  1615. }
  1616. }
  1617. } catch (error) {
  1618. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  1619. }
  1620. }
  1621. DialogHelper.closeLoading()
  1622. this.isZero = false
  1623. // setTimeout(() => {
  1624. // // 删除目标路径缓存
  1625. // this.cache.delete(this.currentPath);
  1626. // this.getSortedFiles(this.currentPath,true,destPath,isOpen)
  1627. // }, 500);
  1628. Logger.info(TAG, 'scan select video result:' + newUris)
  1629. }
  1630. //拉起音频
  1631. // goSelectMusic(){
  1632. //
  1633. // try {
  1634. // let audioSelectOptions = new picker.AudioSelectOptions();
  1635. // let audioPicker = new picker.AudioViewPicker(this.context);
  1636. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  1637. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  1638. // this.saveVideoDatas(audioSelectResult)
  1639. // }
  1640. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  1641. // }).catch((err: BusinessError) => {
  1642. //
  1643. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  1644. // });
  1645. // } catch (error) {
  1646. // let err: BusinessError = error as BusinessError;
  1647. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1648. // }
  1649. //
  1650. //
  1651. //
  1652. // }
  1653. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  1654. if (!item) {
  1655. return undefined;
  1656. }
  1657. try {
  1658. let selectUris: Array<string> = [];
  1659. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  1660. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  1661. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  1662. photoSelectOptions.maxSelectNumber = 1;
  1663. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  1664. selectUris = photoSelectResult.photoUris;
  1665. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  1666. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  1667. console.info('file fd: ' + file.fd);
  1668. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  1669. let imagePath = this.context.filesDir + FileUtil.separator + name
  1670. imagePath = fileUri.getUriFromPath(imagePath)
  1671. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  1672. fileIo.copyFileSync(file.fd, file2.fd)
  1673. fileIo.closeSync(file);
  1674. fileIo.closeSync(file2);
  1675. if (item.filePath == this.currentSong?.filePath) {
  1676. this.cover = imagePath
  1677. }
  1678. if (item) {
  1679. item.pixelMapPath = imagePath
  1680. }
  1681. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  1682. if (success) {
  1683. this.doUpdateData()
  1684. console.log("onecold 更新音乐封面成功,数据库已同步");
  1685. } else {
  1686. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  1687. }
  1688. });
  1689. LogUtil.debug("onecold this.cover =" + this.cover)
  1690. return FileUtil.getFilePath(imagePath); // Return the image path here
  1691. } catch (err) {
  1692. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  1693. return undefined;
  1694. }
  1695. }
  1696. // 拉起picker选择文件管理器
  1697. async callFilePickerSelectFile(): Promise<void> {
  1698. try {
  1699. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  1700. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  1701. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  1702. } else {
  1703. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  1704. }
  1705. let documentPicker = new picker.DocumentViewPicker();
  1706. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  1707. Logger.info(TAG,
  1708. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  1709. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  1710. this.saveVideoDatas(DocumentSelectResult)
  1711. }
  1712. }).catch((err: BusinessError) => {
  1713. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  1714. });
  1715. } catch (err) {
  1716. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  1717. }
  1718. }
  1719. //重命名的对话框
  1720. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  1721. DialogHelper.showTextInputDialog({
  1722. title: '重命名',
  1723. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  1724. maskColor: Color.Transparent,
  1725. backgroundColor: Color.Grey,
  1726. transition: AnimationHelper.transitionInDown(666),
  1727. onChange: (text) => {
  1728. console.error("onChange: " + text);
  1729. },
  1730. onAction: (action, dialogId, content) => {
  1731. // ToastUtil.showToast('content = ' +content)
  1732. if (action == DialogAction.TWO) {
  1733. const newName = content
  1734. const newPath = this.currentPath + '/' + newName
  1735. console.log("onecold item = " + item.type);
  1736. this.doReName(index, newName, filePath, newPath, item)
  1737. }
  1738. }
  1739. })
  1740. }
  1741. //剪切 移动到另个文件夹的对话框
  1742. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1743. Logger.info('onecold showCutDialog')
  1744. let mList: Array<string> = []
  1745. let rPath = this.rootPath
  1746. if (isCurrent) {
  1747. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1748. rPath = this.currentPath
  1749. } else {
  1750. mList = Utility.getNameList(this.dirList);
  1751. rPath = this.rootPath
  1752. }
  1753. let dataBean = new BubbleBean()
  1754. dataBean.data = mList
  1755. dataBean.color = this.themeColor
  1756. dataBean.onItemClick = (i) => {
  1757. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1758. Logger.info('newPath = ' + newPath)
  1759. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  1760. ToastUtil.showToast('移动成功')
  1761. this.table.deleteData(item, () => {
  1762. });
  1763. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1764. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1765. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1766. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1767. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1768. this.table.insert(newItem, (id: number) => {
  1769. //加入数据库
  1770. });
  1771. }
  1772. this.cache.delete(this.currentPath); // 删除原路径缓存
  1773. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1774. this.getSortedFiles(this.currentPath, true)
  1775. }).catch((error: BusinessError) => {
  1776. console.error(error.message);
  1777. });
  1778. XPopup.dismissTop()
  1779. }
  1780. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1781. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1782. popupPosition = PopupPosition.TOP
  1783. }
  1784. if (index <= 3) {
  1785. popupPosition = PopupPosition.BOTTOM
  1786. }
  1787. let pup: XPopup
  1788. if (this.isDarkMode) {
  1789. pup = XPopup.Builder()
  1790. .setPopupPosition(popupPosition)
  1791. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  1792. .setBackgroundColor(Color.Black)
  1793. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1794. .show()
  1795. } else {
  1796. pup = XPopup.Builder()
  1797. .setPopupPosition(popupPosition)
  1798. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  1799. .setBackgroundColor(Color.White)
  1800. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1801. .show()
  1802. }
  1803. }
  1804. //复制 到另个文件夹的对话框
  1805. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1806. Logger.info('onecoldv showCopyDialog')
  1807. let mList: Array<string> = []
  1808. let rPath = this.rootPath
  1809. if (isCurrent) {
  1810. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1811. rPath = this.currentPath
  1812. } else {
  1813. mList = Utility.getNameList(this.dirList);
  1814. rPath = this.rootPath
  1815. }
  1816. let dataBean = new BubbleBean()
  1817. dataBean.data = mList
  1818. dataBean.isCopy = true
  1819. dataBean.color = this.themeColor
  1820. dataBean.onItemClick = (i) => {
  1821. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1822. Logger.info('newPath = ' + newPath)
  1823. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  1824. ToastUtil.showToast('复制成功')
  1825. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1826. this.getSortedFiles(this.currentPath)
  1827. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1828. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1829. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1830. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1831. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1832. this.table.insert(newItem, (id: number) => {
  1833. //加入数据库
  1834. });
  1835. }
  1836. }).catch((error: BusinessError) => {
  1837. console.error(error.message);
  1838. });
  1839. XPopup.dismissTop()
  1840. }
  1841. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1842. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1843. popupPosition = PopupPosition.TOP
  1844. }
  1845. if (index <= 3) {
  1846. popupPosition = PopupPosition.BOTTOM
  1847. }
  1848. let pup: XPopup
  1849. if (this.isDarkMode) {
  1850. pup = XPopup.Builder()
  1851. .setPopupPosition(popupPosition)
  1852. .atView(id)
  1853. .setMaxHeight('60%')
  1854. .setBackgroundColor(Color.Black)
  1855. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1856. .show();
  1857. } else {
  1858. pup = XPopup.Builder()
  1859. .setPopupPosition(popupPosition)
  1860. .atView(id)
  1861. .setMaxHeight('60%')
  1862. .setBackgroundColor(Color.White)
  1863. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1864. .show();
  1865. }
  1866. }
  1867. //重命名索引index的视频
  1868. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  1869. FileUtil.rename(oldPath, newPath).then(async () => {
  1870. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1871. if (info.type === CommonConstants.TYPE_IS_DIR) {
  1872. //如果是文件夹先删除源数据,再添加新数据
  1873. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  1874. if (success) {
  1875. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  1876. } else {
  1877. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  1878. }
  1879. });
  1880. this.scanDirectory(newPath)
  1881. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  1882. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  1883. if (success) {
  1884. console.log(" onecold 重命名成功,数据库已同步");
  1885. } else {
  1886. console.error(" onecold 重命名数据库失败原因: " + error);
  1887. }
  1888. });
  1889. }
  1890. let mediaItem: VideoItem =
  1891. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1892. this.videoLocalList[index] = mediaItem;
  1893. }
  1894. this.cache.delete(this.currentPath)
  1895. this.getSortedFiles(this.currentPath, true)
  1896. }).catch((error: BusinessError) => {
  1897. console.error(error.message);
  1898. });
  1899. }
  1900. build() {
  1901. Scroll() {
  1902. Column() {
  1903. if (!this.isShowCoverHeader()) {
  1904. Column() {
  1905. Line().width('100%').height('100%')
  1906. }
  1907. .height(this.topRectHeight)
  1908. .backgroundColor(this.isCustomizeBg ? Color.Transparent :
  1909. (this.isDarkMode ? $r('app.color.title_bar_bg') : this.themeColor))
  1910. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  1911. TitleBar({ model: $titleBarModel })
  1912. .id('pup_positon_music')
  1913. }
  1914. Stack() {
  1915. Column() {
  1916. XComponent({
  1917. id: 'xcomponentId',
  1918. type: 'surface',
  1919. libraryname: 'ijkplayer_napi',
  1920. controller: this.xcomponentController
  1921. })
  1922. .onLoad((event?: object) => {
  1923. if (!!event) {
  1924. this.initDelayPlay(event);
  1925. }
  1926. })
  1927. .onKeyEvent((event?: KeyEvent) => {
  1928. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  1929. if (!event || event.type !== KeyType.Down) {
  1930. return;
  1931. }
  1932. //空格键 Space key controls pause/play
  1933. if (event.keyCode === KeyCode.KEYCODE_SPACE) {
  1934. console.info('onecold playOrPause 1999')
  1935. this.playOrPause()
  1936. }
  1937. // Right-click to fast forward
  1938. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  1939. this.sessionFastForwardCallback(15);
  1940. }
  1941. // Left-click to rewind
  1942. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  1943. this.sessionRewindCallback(15);
  1944. }
  1945. })
  1946. .onDestroy(() => {
  1947. })
  1948. .width('100%')// .width(this.videoWidth)
  1949. .aspectRatio(this.videoAspectRatio)
  1950. }
  1951. .aspectRatio(this.videoAspectRatio)
  1952. .justifyContent(FlexAlign.Center)
  1953. .backgroundColor(Color.Transparent)
  1954. .visibility(Visibility.Hidden)
  1955. .height(CommonConstants.FULL_PERCENT)
  1956. .width(CommonConstants.FULL_PERCENT)
  1957. .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
  1958. height:this.isLandscape?'80%': '43%',
  1959. dragBar: true,
  1960. showClose: true,
  1961. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  1962. blurStyle:BlurStyle.Thin,
  1963. backgroundColor:Color.Transparent,
  1964. title: { title: 'AB循环' }
  1965. })
  1966. Stack() {
  1967. Row() {
  1968. Blank()
  1969. .layoutWeight(1)
  1970. IndexerView(
  1971. {
  1972. indexArray: DEFAULT_INDEX,
  1973. selectedIndex: this.selectedIndex,
  1974. textSize: 12,
  1975. selectedColor: "#ff419ee5",
  1976. normalColor: "#ffa0a0a0",
  1977. floatSelectedTextColor: "#ffffff",
  1978. floatSelectedViewColor: "#ff419ee5",
  1979. onIndexChanged: (index) => {
  1980. this.listScroller.scrollToIndex(index)
  1981. }
  1982. })
  1983. .width(24)
  1984. .height("50%")
  1985. }.visibility(Visibility.None)
  1986. Column() {
  1987. if (!this.isShowCoverHeader()) {
  1988. this.tabTitle()
  1989. }
  1990. if(this.twoFingerType==4){
  1991. this.getWaterView()
  1992. }else{
  1993. if(this.isGridMusic){
  1994. this.getGridView()
  1995. }else {
  1996. this.getList()
  1997. }
  1998. }
  1999. if (this.modeType == 0) {
  2000. Column() {
  2001. Button('同步数据', { type: ButtonType.Capsule, stateEffect: true })
  2002. .width(130)
  2003. .height(50)
  2004. .margin({ top: 100, bottom: 40 })
  2005. .backgroundColor(this.themeColor)
  2006. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2007. .onClick(() => {
  2008. this.asyncCurrentPathData()
  2009. })
  2010. }
  2011. .height(100)
  2012. .position({ top: 260 })
  2013. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  2014. .animation({ duration: 500 }),
  2015. TransitionEffect.scale({ x: 0, y: 0 })))
  2016. .justifyContent(FlexAlign.Center)
  2017. .opacity(this.isZero ? 1 : 0)
  2018. .visibility(this.isZero && !this.isFavMusic && !this.isHistory
  2019. && this.modeType === 0 ? Visibility.Visible : Visibility.None)
  2020. .animation({
  2021. duration: 500,
  2022. curve: 'ease-in-out' // 可选动画曲线
  2023. })
  2024. .width('100%')
  2025. }
  2026. }
  2027. .layoutWeight(1)
  2028. .height('100%')
  2029. }
  2030. .layoutWeight(1)
  2031. .height('100%')
  2032. Row() {
  2033. Button(this.isAllSelected ? '全不选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  2034. .width(50)
  2035. .height(50)
  2036. .fontSize(13)
  2037. .margin({ top: 10, bottom: 10, right: 6 })
  2038. .backgroundColor(this.themeColor)
  2039. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2040. .onClick(() => {
  2041. if (this.isAllSelected) {
  2042. // 全不选
  2043. this.selectedFiles = [];
  2044. } else {
  2045. // 全选
  2046. this.selectedFiles = [...this.getCurFileList()];
  2047. }
  2048. this.isAllSelected = !this.isAllSelected;
  2049. })
  2050. Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
  2051. .width(90)
  2052. .height(50)
  2053. .fontSize(13)
  2054. .margin({ top: 10, bottom: 10, right: 6 })
  2055. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2056. .backgroundColor(this.themeColor)
  2057. .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
  2058. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2059. })
  2060. .onClick(() => {
  2061. this.isOneKeyTags = !this.isOneKeyTags
  2062. })
  2063. Button('乱码修复', { type: ButtonType.Capsule, stateEffect: true })
  2064. .width(90)
  2065. .height(50)
  2066. .fontSize(13)
  2067. .margin({ top: 10, bottom: 10, right: 6 })
  2068. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2069. .backgroundColor(this.themeColor)
  2070. .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
  2071. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2072. })
  2073. .onClick(() => {
  2074. this.isFixMessy = !this.isFixMessy
  2075. })
  2076. // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  2077. // .width('35%')
  2078. // .height(60)
  2079. // .id('music_cut')
  2080. // .margin({ top: 10, bottom: 10, right: 6 })
  2081. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2082. // .backgroundColor(this.themeColor)
  2083. // .onClick(() => {
  2084. // this.showCutDialogForMultipleFiles(false, 'music_cut')
  2085. // })
  2086. //
  2087. // Button('移动', { type: ButtonType.Circle, stateEffect: true })
  2088. // .width('35%')
  2089. // .height(60)
  2090. // .id('music_cut_current')
  2091. // .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  2092. // .margin({ top: 10, bottom: 10, right: 6 })
  2093. // .backgroundColor(this.themeColor)
  2094. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2095. // .onClick(() => {
  2096. //
  2097. // this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  2098. // })
  2099. // Button('复制', { type: ButtonType.Circle, stateEffect: true })
  2100. // .width('35%')
  2101. // .height(60)
  2102. // .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  2103. // .margin({ top: 10, bottom: 10, right: 6 })
  2104. // .backgroundColor(this.themeColor)
  2105. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2106. // .onClick(() => {
  2107. // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  2108. // })
  2109. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  2110. .width(50)
  2111. .height(50)
  2112. .fontSize(13)
  2113. .margin({ top: 10, bottom: 10, right: 6 })
  2114. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  2115. .backgroundColor(this.themeColor)
  2116. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2117. .onClick(() => {
  2118. this.showWarnIsDelete()
  2119. })
  2120. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  2121. .width(50)
  2122. .height(50)
  2123. .fontSize(13)
  2124. .margin({ top: 10, bottom: 10, right: 6 })
  2125. .backgroundColor(this.themeColor)
  2126. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2127. .onClick(() => {
  2128. this.selectedFiles = [];
  2129. this.isAllSelected = false
  2130. this.isMultiSelect = false
  2131. })
  2132. }
  2133. .width('100%')
  2134. .justifyContent(FlexAlign.Center)
  2135. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2136. .opacity(this.isMultiSelect ? 1 : 0)
  2137. .animation({
  2138. duration: 666,
  2139. curve: 'ease-in-out' // 可选动画曲线
  2140. })
  2141. .position(this.isShowCoverHeader() ? { bottom: 78 }
  2142. : { bottom: this.isPhoneLan() ? 130 : 170 }) // 将 Row 固定在底部
  2143. }
  2144. .width('100%')
  2145. .height('100%')
  2146. .alignContent(Alignment.Top)
  2147. Column() {
  2148. this.PlayController()
  2149. }
  2150. .hitTestBehavior(HitTestMode.Transparent)
  2151. .position({ bottom: 0 }) // 将 Row 固定在底部
  2152. .opacity(this.barBottomOpacity)
  2153. }
  2154. .width('100%')
  2155. .height('100%')
  2156. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  2157. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  2158. .backgroundImagePosition(Alignment.Center)
  2159. .backdropBlur(this.blurValue)
  2160. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  2161. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  2162. }
  2163. }
  2164. @Builder
  2165. TagsContentCoverBuilder() {
  2166. Scroll() {
  2167. Column() {
  2168. TagsContentCover(
  2169. {
  2170. selectedFiles:this.selectedFiles,
  2171. isOneKeyTags:this.isOneKeyTags,
  2172. onTagsResult:(result: boolean)=>{
  2173. this.isMultiSelect = false
  2174. if(result){//如果嵌入成功,更新数据
  2175. this.doUpdateData()
  2176. }
  2177. }
  2178. }
  2179. )
  2180. }
  2181. }
  2182. .width('100%')
  2183. .height('100%')
  2184. }
  2185. @Builder
  2186. FixMessyViewBuilder() {
  2187. Scroll() {
  2188. Column() {
  2189. FixMessyView(
  2190. {
  2191. selectedFiles:this.selectedFiles,
  2192. isFixMessy:this.isFixMessy,
  2193. onFixResult:(result: boolean)=>{
  2194. this.isMultiSelect = false
  2195. if(result){//如果嵌入成功,更新数据
  2196. this.doUpdateData()
  2197. }
  2198. }
  2199. }
  2200. )
  2201. }
  2202. }
  2203. .width('100%')
  2204. .height('100%')
  2205. }
  2206. asyncCurrentPathData() {
  2207. if (this.modeType == 0) {
  2208. workerInstance.postMessage({
  2209. code: 1,
  2210. data1: this.context,
  2211. data2: this.currentPath,
  2212. data3: this.lockPath,
  2213. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  2214. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  2215. });
  2216. }
  2217. }
  2218. // 处理文件选择的函数
  2219. handleFileSelection(item: VideoItem, checked: boolean) {
  2220. if (checked) {
  2221. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  2222. this.selectedFiles.push(item);
  2223. }
  2224. } else {
  2225. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  2226. if (index > -1) {
  2227. this.selectedFiles.splice(index, 1);
  2228. }
  2229. }
  2230. }
  2231. private deleteComponentId: number = 0
  2232. //多选删除文件
  2233. showWarnIsDelete(){
  2234. this.getUIContext().getPromptAction().openCustomDialog({
  2235. builder: () => {
  2236. this.deleteComptentBuilder()
  2237. },
  2238. isModal:true,
  2239. showInSubWindow:false,
  2240. maskColor: Color.Transparent,
  2241. dialogTransition: // 设置弹窗内容显示的过渡效果
  2242. TransitionEffect.translate({ x: 0, y: 290, z: 0 })
  2243. .animation({ duration: 600, curve: Curve.Smooth }),
  2244. maskTransition: // 设置蒙层显示的过渡效果
  2245. TransitionEffect.opacity(0)
  2246. .animation({ duration: 600, curve: Curve.Smooth })
  2247. }).then((dialogId: number) => {
  2248. this.deleteComponentId = dialogId
  2249. })
  2250. .catch((error: BusinessError) => {
  2251. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  2252. })
  2253. }
  2254. @Builder
  2255. deleteComptentBuilder(){
  2256. DeleteComptent({
  2257. selectedFiles:this.selectedFiles,
  2258. onCancel:()=>{
  2259. this.isMultiSelect = false
  2260. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  2261. },
  2262. onDeleteResult:(result: boolean)=>{
  2263. this.isMultiSelect = false
  2264. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  2265. if(result){//如果删除成功,更新数据
  2266. this.selectedFiles = [];
  2267. this.isAllSelected = false
  2268. this.cache.delete(this.currentPath);
  2269. this.getSortedFiles(this.currentPath, true);
  2270. }
  2271. }
  2272. })
  2273. }
  2274. //多选移动文件
  2275. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  2276. Logger.info('onecold showCutDialogForMultipleFiles')
  2277. let mList: Array<string> = []
  2278. let rPath = this.rootPath
  2279. if (isCurrent) {
  2280. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2281. rPath = this.currentPath
  2282. } else {
  2283. mList = Utility.getNameList(this.dirList);
  2284. rPath = this.rootPath
  2285. }
  2286. let dataBean = new BubbleBean();
  2287. dataBean.data = mList;
  2288. dataBean.color = this.themeColor
  2289. dataBean.onItemClick = (i) => {
  2290. const newDirPath = rPath + '/' + mList[i];
  2291. // Logger.info('newDirPath = ' + newDirPath)
  2292. this.selectedFiles.forEach((item) => {
  2293. const newPath = newDirPath + '/' + item.fileName;
  2294. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  2295. ToastUtil.showToast('移动成功');
  2296. this.table.deleteData(item, () => {
  2297. this.cache.delete(this.currentPath); // 删除原路径缓存
  2298. this.cache.delete(newDirPath); // 删除目标路径缓存
  2299. this.getSortedFiles(this.currentPath, true);
  2300. });
  2301. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2302. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2303. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2304. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2305. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2306. this.table.insert(newItem, (id: number) => {
  2307. //加入数据库
  2308. });
  2309. }
  2310. }).catch((error: Error) => {
  2311. console.error(error.message);
  2312. });
  2313. });
  2314. this.isMultiSelect = false
  2315. this.selectedFiles = [];
  2316. this.isAllSelected = false
  2317. XPopup.dismissTop();
  2318. };
  2319. let pup: XPopup
  2320. if (this.isDarkMode) {
  2321. pup = XPopup.Builder()
  2322. .setPopupPosition(PopupPosition.TOP)
  2323. .atView(viewId)
  2324. .setBackgroundColor(Color.Black)
  2325. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2326. .show();
  2327. } else {
  2328. pup = XPopup.Builder()
  2329. .setPopupPosition(PopupPosition.TOP)
  2330. .atView(viewId)
  2331. .setBackgroundColor(Color.White)
  2332. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2333. .show();
  2334. }
  2335. }
  2336. /**
  2337. * 加载所有歌单
  2338. */
  2339. async loadAllPlaylists() {
  2340. try {
  2341. this.allPlaylists = await this.playlistTable?.queryAllPlaylists()!
  2342. LogUtil.info('heanup Loaded playlists: ' + this.allPlaylists.length)
  2343. } catch (error) {
  2344. LogUtil.error('heaunp Failed to load playlists: ' + error.message)
  2345. }
  2346. }
  2347. /**
  2348. * 显示添加到歌单对话框
  2349. */
  2350. async showAddToPlaylistDialog(item: VideoItem) {
  2351. // 加载最新的歌单列表
  2352. await this.loadAllPlaylists()
  2353. showAddToPlaylistDialog(
  2354. item,
  2355. this.allPlaylists,
  2356. async (playlistId: string) => {
  2357. // 添加歌曲到歌单
  2358. const success = await this.playlistTable?.addSongToPlaylist(playlistId, item.filePath)
  2359. if (success) {
  2360. ToastUtil.showToast('已添加到歌单')
  2361. // 重新加载歌单列表
  2362. await this.loadAllPlaylists()
  2363. } else {
  2364. ToastUtil.showToast('歌曲已在该歌单中')
  2365. }
  2366. },
  2367. () => {
  2368. LogUtil.info('取消添加到歌单')
  2369. },
  2370. () => {
  2371. // 创建新歌单
  2372. showCreatePlaylistDialog(
  2373. async (name: string, description: string) => {
  2374. const success = await this.playlistTable?.createPlaylist(name, description)
  2375. if (success) {
  2376. ToastUtil.showToast('歌单创建成功')
  2377. // 重新加载歌单列表并打开添加对话框
  2378. await this.loadAllPlaylists()
  2379. await this.showAddToPlaylistDialog(item)
  2380. } else {
  2381. ToastUtil.showToast('歌单创建失败')
  2382. }
  2383. }
  2384. )
  2385. }
  2386. )
  2387. }
  2388. doFav(item: VideoItem) {
  2389. LogUtil.info('onecold doFav isFav=' + item.isFav)
  2390. let isFav = 0
  2391. if (Utility.getIsFav(this.favList, item)) {
  2392. isFav = 0
  2393. } else {
  2394. isFav = 1
  2395. }
  2396. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  2397. if (result) {
  2398. if (isFav === 1) {
  2399. ToastUtil.showToast('收藏成功');
  2400. } else {
  2401. ToastUtil.showToast('取消收藏成功');
  2402. }
  2403. this.deleteCache(this.currentPath)
  2404. this.getFavList(false)
  2405. if (this.modeType === 0 && !this.isFavMusic) {
  2406. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  2407. this.getSortedFiles(this.currentPath)
  2408. }
  2409. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  2410. workerInstance.postMessage({ code: 3, data: this.context });
  2411. workerInstance.postMessage({ code: 4, data: this.context });
  2412. }
  2413. })
  2414. }
  2415. //多选复制文件
  2416. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  2417. console.log('onecold showCopyDialogForMultipleFiles');
  2418. let mList: Array<string> = []
  2419. let rPath = this.rootPath
  2420. if (isCurrent) {
  2421. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2422. rPath = this.currentPath
  2423. } else {
  2424. mList = Utility.getNameList(this.dirList);
  2425. rPath = this.rootPath
  2426. }
  2427. let dataBean = new BubbleBean();
  2428. dataBean.data = mList;
  2429. dataBean.isCopy = true
  2430. dataBean.color = this.themeColor
  2431. dataBean.onItemClick = (i) => {
  2432. const newDirPath = rPath + '/' + mList[i];
  2433. // Logger.info('newDirPath = ' + newDirPath)
  2434. this.selectedFiles.forEach((item) => {
  2435. const newPath = newDirPath + '/' + item.fileName;
  2436. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2437. ToastUtil.showToast('复制成功');
  2438. this.cache.delete(newDirPath); // 删除目标路径缓存
  2439. this.getSortedFiles(this.currentPath);
  2440. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2441. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2442. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2443. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2444. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2445. this.table.insert(newItem, (id: number) => {
  2446. //加入数据库
  2447. });
  2448. }
  2449. }).catch((error: Error) => {
  2450. console.error(error.message);
  2451. });
  2452. });
  2453. this.isMultiSelect = false
  2454. this.selectedFiles = [];
  2455. this.isAllSelected = false
  2456. XPopup.dismissTop();
  2457. };
  2458. let pup: XPopup
  2459. if (this.isDarkMode) {
  2460. pup = XPopup.Builder()
  2461. .setPopupPosition(PopupPosition.TOP)
  2462. .atView(viewId)
  2463. .setBackgroundColor(Color.Black)
  2464. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2465. .show();
  2466. } else {
  2467. pup = XPopup.Builder()
  2468. .setPopupPosition(PopupPosition.TOP)
  2469. .atView(viewId)
  2470. .setBackgroundColor(Color.White)
  2471. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2472. .show();
  2473. }
  2474. }
  2475. @Builder
  2476. private DirItem(item: VideoItem, index?: number) {
  2477. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2478. Row() {
  2479. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  2480. $r('app.media.music_group'))
  2481. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  2482. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  2483. .fillColor(this.themeColor)// .fontSize(33)
  2484. .alt($r('app.media.music_group'))
  2485. .borderRadius('100%')
  2486. .clip(true)
  2487. .margin({ left: 20, top: 8, bottom: 8 })
  2488. Column() {
  2489. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  2490. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2491. .maxLines(1)// .width('88%')
  2492. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  2493. .animation({
  2494. duration: 555,
  2495. curve: 'ease-in-out',
  2496. })
  2497. .transition({
  2498. type: TransitionType.Insert,
  2499. opacity: 0,
  2500. translate: { x: 160 }
  2501. })
  2502. .margin({ left: 10, right: 20 })
  2503. .fontColor($r('app.color.text_color'))
  2504. Row() {
  2505. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  2506. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2507. .padding({ top: 8 })
  2508. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  2509. .fontColor($r('app.color.text_color'))
  2510. .margin({ left: 10 })
  2511. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  2512. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2513. .padding({ top: 8 })
  2514. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2515. .fontColor($r('app.color.text_color'))
  2516. .margin({ left: 10 })
  2517. Blank()
  2518. }
  2519. }
  2520. .height('100%')
  2521. .layoutWeight(1)
  2522. .justifyContent(FlexAlign.Center)
  2523. .alignItems(HorizontalAlign.Start)
  2524. Blank()
  2525. Image($r('app.media.arrow_right'))
  2526. .height(25)
  2527. .margin({ right: 10 })
  2528. .alignSelf(ItemAlign.Center)
  2529. .id(item.filePath)
  2530. }
  2531. }
  2532. .backgroundColor(Color.Transparent)
  2533. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2534. .width('100%')
  2535. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  2536. .opacity(this.opacityItem) // 绑定透明度
  2537. }
  2538. isShowDir(dirName: string) {
  2539. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  2540. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  2541. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  2542. if (dirName === undefined) {
  2543. return true
  2544. }
  2545. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  2546. return this.isShowSimi
  2547. }
  2548. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  2549. return this.isShowFAV
  2550. }
  2551. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  2552. return this.isShowHistory
  2553. }
  2554. return true
  2555. }
  2556. @State opacityItem: number = 1; // 控制透明度的状态变量
  2557. @Builder
  2558. private MusicItem(item: VideoItem, index?: number) {
  2559. Button({ type: ButtonType.Normal, stateEffect: true }) {
  2560. Row() {
  2561. Stack() {
  2562. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  2563. .fillColor(this.themeColor)
  2564. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  2565. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  2566. .alt($r('app.media.music_red'))
  2567. .borderRadius('100%')
  2568. .clip(true)
  2569. .draggable(false)
  2570. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  2571. .autoResize(true) // 重采样,可减少内存占用
  2572. .opacity(this.opacityItem)// 绑定透明度
  2573. .margin({ left: 20 })
  2574. .gesture(LongPressGesture()
  2575. .onAction(async () => {
  2576. //如果是专辑和艺术家的首页,不能长按
  2577. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2578. return
  2579. //如果是我的收藏 最近播放等也不能长按
  2580. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2581. item.name === LocalMusic.STR_HISTORY_MUSIC
  2582. )
  2583. return
  2584. this.longItemFilePath = item.filePath
  2585. this.tempLyricContent = await this.getLyricContent(item)
  2586. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2587. })
  2588. .onActionEnd((event: GestureEvent) => {
  2589. }))
  2590. .onClick(()=>{
  2591. this.doPlay(item,index)
  2592. this.isShowPlay = true
  2593. })
  2594. }
  2595. Column() {
  2596. Column() {
  2597. Text(this.isShowFileName?item.fileName :item.name)
  2598. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2599. .maxLines(1)
  2600. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  2601. .animation({
  2602. duration: 555,
  2603. curve: 'Linear',
  2604. })
  2605. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2606. $r('app.color.text_color'))
  2607. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2608. .padding({right:25})
  2609. .bindPopup(this.longItemFilePath === item.filePath, {
  2610. builder: this.MenuBuilder(item,index,item.filePath),
  2611. placement: Placement.Top,
  2612. // autoCancel: true,
  2613. mask: {color:'#33000000'},
  2614. // popupColor: Color.Yellow,
  2615. enableArrow: false,//是否显示箭头
  2616. showInSubWindow: false,
  2617. onStateChange: (e) => {
  2618. if (!e.isVisible) {
  2619. this.longItemFilePath = ''
  2620. this.tempLyricContent = ''
  2621. }
  2622. }
  2623. })
  2624. .gesture(LongPressGesture()
  2625. .onAction(async () => {
  2626. //如果是专辑和艺术家的首页,不能长按
  2627. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2628. return
  2629. //如果是我的收藏 最近播放等也不能长按
  2630. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2631. item.name === LocalMusic.STR_HISTORY_MUSIC
  2632. )
  2633. return
  2634. this.longItemFilePath = item.filePath
  2635. this.tempLyricContent = await this.getLyricContent(item)
  2636. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2637. })
  2638. .onActionEnd((event: GestureEvent) => {
  2639. })
  2640. )
  2641. Row() {
  2642. Column(){
  2643. Text(item.md5Str?.includes('Lossless')?
  2644. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  2645. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  2646. .padding({ top: 3,right:6,left:6,bottom:3 })
  2647. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2648. $r('app.color.text_color'))
  2649. .fontWeight(500)
  2650. .borderRadius(12)
  2651. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  2652. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2653. .backgroundColor('#FFC107')
  2654. }
  2655. .padding({ top: 8 })
  2656. Text(StrUtil.isEmpty(item.artist) ? item.duration
  2657. :this.twoFingerType==2? item.artist +' ' + item.duration
  2658. : item.artist + ' ' + item?.duration)
  2659. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2660. .padding({ top: 8 ,right:25})
  2661. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  2662. .maxLines(1)
  2663. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  2664. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2665. Color.Gray)
  2666. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  2667. Blank()
  2668. Text(this.isShowFileName?item.duration:item.size)
  2669. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2670. .padding({ top: 8 })
  2671. .maxLines(1)
  2672. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  2673. ? Visibility.Visible : Visibility.None)
  2674. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  2675. Color.Gray)
  2676. .margin({ left: 10 })
  2677. }
  2678. .gesture(LongPressGesture()
  2679. .onAction(async () => {
  2680. //如果是专辑和艺术家的首页,不能长按
  2681. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  2682. return
  2683. //如果是我的收藏 最近播放等也不能长按
  2684. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  2685. item.name === LocalMusic.STR_HISTORY_MUSIC
  2686. )
  2687. return
  2688. this.longItemFilePath = item.filePath
  2689. this.tempLyricContent = await this.getLyricContent(item)
  2690. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  2691. })
  2692. .onActionEnd((event: GestureEvent) => {
  2693. })
  2694. )
  2695. }
  2696. .height('100%')
  2697. .width('100%')
  2698. .margin({ right: 10 })
  2699. .justifyContent(FlexAlign.Center)
  2700. .alignItems(HorizontalAlign.Start)
  2701. }
  2702. .height('100%')
  2703. .margin({ left: 5 })
  2704. .layoutWeight(1)
  2705. Column() {
  2706. Checkbox({ name: 'checkbox' + index })
  2707. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  2708. .selectedColor(this.themeColor)
  2709. .shape(CheckBoxShape.CIRCLE)
  2710. .opacity(this.isMultiSelect ? 1 : 0)
  2711. .animation({
  2712. duration: 666,
  2713. curve: 'Smooth' // 可选动画曲线
  2714. })
  2715. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2716. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  2717. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  2718. .width(22)
  2719. .height(22)
  2720. ImageAnimator()
  2721. .images(this.imagesF)// 动画数组
  2722. .duration(1000)// 持续
  2723. .state(this.animationState)// 动画状态
  2724. .fillMode(FillMode.Forwards)
  2725. .width(18)
  2726. .margin({ right: 20, top: 8, bottom: 8 })
  2727. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  2728. Visibility.None)
  2729. .height(18)
  2730. .iterations(-1) // 播放次数
  2731. }
  2732. }
  2733. }
  2734. .backgroundColor(Color.Transparent)
  2735. .width('100%')
  2736. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2737. }
  2738. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  2739. @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
  2740. buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
  2741. direction: Direction.Ltr,
  2742. buttonPadding:{top:12,bottom:12},
  2743. backgroundColor: Color.Transparent,
  2744. fontSize:14,
  2745. selectedFontSize:15,
  2746. selectedFontColor:Color.White,
  2747. selectedBackgroundColor: this.themeColor,
  2748. localizedTextPadding: {
  2749. end: LengthMetrics.vp(20),
  2750. start: LengthMetrics.vp(20)
  2751. }
  2752. })
  2753. @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
  2754. //当胶囊按钮的选择发生变化时调用此函数
  2755. capsuleSelectedIndexesChanged() {
  2756. this.modeType = this.tabSelectedIndexes[0]
  2757. }
  2758. @Builder
  2759. tabTitle() {
  2760. Column({ space: 2 }) {
  2761. SegmentButton({ options: this.tabOptions, selectedIndexes: $tabSelectedIndexes })
  2762. Line()
  2763. .width('100%')
  2764. .height(1)
  2765. .backgroundColor($r('app.color.index_background'))
  2766. .opacity(this.barOpacity)
  2767. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  2768. }
  2769. .width('100%')
  2770. .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  2771. }
  2772. // @Builder
  2773. // tabTitle() {
  2774. // Column() {
  2775. // // 使用 Stack 布局来实现绝对定位效果
  2776. // Stack() {
  2777. // // 背景动画容器
  2778. // Row() {
  2779. // ForEach(this.tabs, (i: string, index) => {
  2780. // Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2781. // Flex()
  2782. // .backgroundColor(this.isDarkMode ? $r('app.color.tab_item_bg') : this.themeColor)
  2783. // .borderRadius(20)
  2784. // .padding(10)
  2785. // .margin(6)
  2786. // .width('100%')
  2787. // .height('100%')
  2788. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2789. // .visibility(this.modeType === index ? Visibility.Visible : Visibility.None)
  2790. // .opacity(this.modeType === index ? 1 : 0)
  2791. // .animation({
  2792. // duration: 666,
  2793. // playMode: PlayMode.Normal,
  2794. // curve: 'ease-in-out'
  2795. // });
  2796. // }
  2797. // .layoutWeight(1)
  2798. // .margin({
  2799. // left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5,
  2800. // right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5, bottom: 1
  2801. // });
  2802. // });
  2803. // }
  2804. // .width('100%')
  2805. // .height(50);
  2806. //
  2807. // // 导航栏容器
  2808. // Row() {
  2809. // ForEach(this.tabs, (item: string, index) => {
  2810. // Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2811. // Text(item)
  2812. // .fontSize(16)
  2813. // .fontColor(this.modeType === index ? Color.White : $r('app.color.text_color'))
  2814. // .padding(15)
  2815. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2816. // .onClick(() => {
  2817. // this.modeType = index;
  2818. // // this.onModeChange();
  2819. // });
  2820. // }
  2821. // .layoutWeight(1)
  2822. // .stateStyles({
  2823. // pressed: { opacity: 0.6 } // 按压反馈
  2824. // });
  2825. // });
  2826. // }
  2827. // .width('100%')
  2828. // .height(this.topBarHeight)
  2829. // .opacity(this.barOpacity)
  2830. // .backgroundColor(Color.Transparent);
  2831. //
  2832. // }
  2833. // .width('100%')
  2834. // .height(this.topBarHeight)
  2835. // .opacity(this.barOpacity)
  2836. //
  2837. // Line()
  2838. // .width('100%')
  2839. // .height(1)
  2840. // .backgroundColor($r('app.color.index_background'))
  2841. // .opacity(this.barOpacity)
  2842. // .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  2843. // }
  2844. // .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  2845. // }
  2846. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  2847. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  2848. isShowCoverHeader() {
  2849. if (!this.isShowHeader) {
  2850. return false
  2851. }
  2852. if (this.modeType == 0) {
  2853. if (this.isHistory || this.isFavMusic) {
  2854. return true
  2855. }
  2856. if (this.currentPath != this.rootPath) {
  2857. return true
  2858. }
  2859. }
  2860. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  2861. }
  2862. @Builder
  2863. coverHeader() {
  2864. if (this.isShowCoverHeader()) {
  2865. Column() {
  2866. Stack() {
  2867. // 居中标题
  2868. Text('')
  2869. .fontSize(18)
  2870. .fontColor(Color.White)
  2871. .align(Alignment.Center)
  2872. // 左右按钮
  2873. Row() {
  2874. Image($r('app.media.left_back_white'))
  2875. .width(28)
  2876. .height(28)
  2877. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2878. .margin({ left: 12, right: 8 })
  2879. .onClick(() => {
  2880. animateTo({ duration: 555 }, () => {
  2881. this.doSwipBack()
  2882. })
  2883. })
  2884. Blank().flexGrow(1)
  2885. if (this.modeType == 0 && !this.isHistory && !this.isFavMusic) {
  2886. Image($r('app.media.add'))
  2887. .width(25)
  2888. .height(25)
  2889. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  2890. .margin({ left: 8, right: 15 })
  2891. .onClick(() => {
  2892. this.showAddDialog()
  2893. })
  2894. }
  2895. }
  2896. .height(48)
  2897. .width('100%')
  2898. .alignItems(VerticalAlign.Center)
  2899. }
  2900. .height(48)
  2901. .width('100%')
  2902. Row() {
  2903. Column() {
  2904. Image(this.currentTitleCover)
  2905. .height(100)
  2906. .width(100)
  2907. .alt(this.imageLabel)
  2908. .borderRadius(8)
  2909. .clickEffect({ level: ClickEffectLevel.HEAVY })
  2910. }
  2911. .alignItems(HorizontalAlign.Start)
  2912. .margin({ left: 30, top: 3, bottom: 15 })
  2913. Column() {
  2914. Column() {
  2915. Text(this.currentTitleName)
  2916. .fontSize(16)
  2917. .maxLines(1)
  2918. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  2919. .fontWeight(FontWeight.Bold)
  2920. .fontColor($r('app.color.text_color'))
  2921. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  2922. if (this.modeType == 3 && ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2923. Text(`艺术家:${this.videoLocalList[0].artist}`)
  2924. .fontSize(14)
  2925. .padding({ top: 8 })
  2926. .maxLines(1)
  2927. .fontWeight(FontWeight.Bold)
  2928. .fontColor($r('app.color.text_color'))
  2929. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  2930. if(this.videoLocalList[0].genre){
  2931. Text(`风格:${this.videoLocalList[0].genre}`)
  2932. .fontSize(14)
  2933. .padding({ top: 8 })
  2934. .maxLines(1)
  2935. .visibility(StrUtil.isEmpty(this.videoLocalList[0].genre)||
  2936. this.videoLocalList[0].genre.includes(this.UNKONWN)
  2937. ?Visibility.None:Visibility.Visible)
  2938. .fontWeight(FontWeight.Bold)
  2939. .fontColor($r('app.color.text_color'))
  2940. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  2941. }
  2942. if(this.videoLocalList[0].year){
  2943. Text(`发行时间:${this.videoLocalList[0].year}`)
  2944. .fontSize(14)
  2945. .padding({ top: 8 })
  2946. .maxLines(1)
  2947. .visibility(StrUtil.isEmpty(this.videoLocalList[0].year)||
  2948. this.videoLocalList[0].year.includes(this.UNKONWN)
  2949. ?Visibility.None:Visibility.Visible)
  2950. .fontWeight(FontWeight.Bold)
  2951. .fontColor($r('app.color.text_color'))
  2952. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  2953. }
  2954. }
  2955. if(this.modeType != 3){
  2956. Row() {
  2957. Text(`共${this.videoLocalList.length}首歌`)
  2958. .fontSize(13)
  2959. .fontWeight(FontWeight.Bold)
  2960. .padding({ top: 8 })
  2961. .fontColor($r('app.color.text_color'))
  2962. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  2963. Blank()
  2964. }
  2965. }
  2966. }
  2967. .height('100%')
  2968. .width('100%')
  2969. .justifyContent(FlexAlign.Center)
  2970. .alignItems(HorizontalAlign.Start)
  2971. }
  2972. .height('100%')
  2973. .layoutWeight(1)
  2974. .margin({ left: 20 })
  2975. }
  2976. this.listViewTitle()
  2977. }
  2978. .backgroundImage(this.getCoverTitleBg())
  2979. .height(250)
  2980. .width('100%')
  2981. .backgroundImageSize({ height: '100%', width: '100%' })
  2982. .backgroundBlurStyle(this.isCustomizeBg ? BlurStyle.NONE : BlurStyle.BACKGROUND_ULTRA_THICK)
  2983. .padding({ top: this.topRectHeight, bottom: this.bottomBarHeight + 48 })
  2984. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  2985. .justifyContent(FlexAlign.SpaceBetween)
  2986. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.7, y: 0.7 }).animation({ duration: 500 }),
  2987. TransitionEffect.scale({ x: 0, y: 0 })))
  2988. } else {
  2989. this.listViewTitle()
  2990. }
  2991. }
  2992. getCoverTitleBg(): ResourceStr | image.PixelMap {
  2993. if (this.isCustomizeBg) {
  2994. return ('rgba(255,255,255,0.2)')
  2995. }
  2996. if (this.isDarkMode) {
  2997. return $r('app.color.user_center_card_background')
  2998. }
  2999. return this.currentTitleCover
  3000. }
  3001. @Builder
  3002. listViewTitle() {
  3003. Column() {
  3004. Row({ space: 8 }) {
  3005. Row({ space: 8 }) {
  3006. Image($r("app.media.hm_playlist"))
  3007. .width(25)
  3008. .margin({ left: 8 })
  3009. .fillColor(this.themeColor)
  3010. Text(this.artistList.length ==100 ? `共找到${this.artistCount}位艺术家`
  3011. :`共找到${this.artistList.length}位艺术家`)
  3012. .fontColor($r('app.color.text_color'))
  3013. .fontSize(14)
  3014. .opacity(this.opacityItem)
  3015. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  3016. Text(this.albumList.length ==100 ? `共找到${this.albumCount+''}张专辑`
  3017. :`共找到${this.albumList.length}张专辑`)
  3018. .fontColor($r('app.color.text_color'))
  3019. .opacity(this.opacityItem)
  3020. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  3021. .fontSize(14)
  3022. }
  3023. .layoutWeight(1)
  3024. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  3025. Row() {
  3026. TextInput({
  3027. placeholder: this.modeType === 2 ? '输入艺术家名称...' : '输入专辑名称...',
  3028. text: this.searchText
  3029. })
  3030. .height(35)
  3031. .onChange((value: string) => {
  3032. this.onSearchInput(value);
  3033. })
  3034. .layoutWeight(1)
  3035. Text(`取消`)
  3036. .margin({ left: 10, right: 10 })
  3037. .fontColor($r('app.color.text_color'))
  3038. .fontSize(16)
  3039. .onClick(() => {
  3040. this.isSearchMode = false
  3041. this.searchText = ''
  3042. if (this.modeType === 2) {
  3043. this.updateListData(this.artistList)
  3044. } else {
  3045. this.updateListData(this.albumList)
  3046. }
  3047. })
  3048. }
  3049. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  3050. .animation({
  3051. duration: 666,
  3052. curve: 'ease-in-out' // 可选动画曲线
  3053. })
  3054. Blank()
  3055. Image($r("app.media.search"))
  3056. .width(25)
  3057. .visibility(this.modeType === 2 || this.modeType === 3 ? Visibility.Visible : Visibility.None)
  3058. .animation({
  3059. duration: 666,
  3060. curve: 'ease-in-out' // 可选动画曲线
  3061. })// .opacity(this.opacityItem)
  3062. .fillColor(this.themeColor)
  3063. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3064. .onClick(() => {
  3065. this.isSearchMode = true
  3066. })
  3067. Image($r("app.media.top_rank"))
  3068. .width(25)// .opacity(this.opacityItem)
  3069. .fillColor(this.themeColor)
  3070. .animation({
  3071. duration: 666,
  3072. curve: 'ease-in-out' // 可选动画曲线
  3073. })
  3074. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3075. .onClick(() => {
  3076. this.showRankDialog()
  3077. })
  3078. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  3079. .width(25)
  3080. .animation({
  3081. duration: 666,
  3082. curve: 'ease-in-out' // 可选动画曲线
  3083. })
  3084. .fillColor(this.themeColor)
  3085. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3086. .onClick(() => {
  3087. this.isGridMusic = !this.isGridMusic
  3088. })
  3089. }
  3090. .visibility(((this.modeType === 2 || this.modeType === 3) && !this.isCanBack) ? Visibility.Visible :
  3091. Visibility.None)
  3092. .width('100%')
  3093. .padding(10)
  3094. .height(50)
  3095. .border({
  3096. width: { bottom: 1 },
  3097. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  3098. })
  3099. Row({ space: 8 }) {
  3100. Row({ space: 8 }) {
  3101. Image($r("app.media.hm_play"))
  3102. .width(25)
  3103. .margin({ left: 8 })
  3104. .fillColor(this.themeColor)
  3105. Text(`播放全部`)
  3106. .fontColor($r('app.color.text_color'))
  3107. .fontSize(14)
  3108. .animation({
  3109. duration: 666,
  3110. curve: 'ease-in-out' // 可选动画曲线
  3111. })
  3112. if(Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length>0){
  3113. Text(this.modeType==1&&Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length==100?
  3114. `(${this.mediaKuCount}首)`
  3115. :`(${Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length}首)`)
  3116. .fontColor($r('app.color.text_color'))
  3117. .fontSize(14)
  3118. .opacity(this.opacityItem)
  3119. .animation({
  3120. duration: 666,
  3121. curve: 'ease-in-out' // 可选动画曲线
  3122. })
  3123. }
  3124. }
  3125. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3126. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  3127. .animation({
  3128. duration: 666,
  3129. curve: 'ease-in-out' // 可选动画曲线
  3130. })
  3131. // .backgroundColor(this.isClickedPLayAll ? $r('app.color.button_click') : Color.Transparent)
  3132. .onTouch((event: TouchEvent) => {
  3133. if (event.type === TouchType.Down) {
  3134. this.isClickedPLayAll = true;
  3135. } else if (event.type === TouchType.Up || event.type === TouchType.Cancel) {
  3136. this.isClickedPLayAll = false;
  3137. }
  3138. })
  3139. .onClick(() => {
  3140. // ToastUtil.showToast('当前的手机的折叠状态 ='+DisplayUtil.getFoldStatus())
  3141. if (this.modeType === 0) {
  3142. const playList = this.getCurFileList();
  3143. const item = Utility.getPlayItem(playList, this.playType);
  3144. if (item) { // 显式检查undefined
  3145. this.doPlay(item);
  3146. }
  3147. } else {
  3148. const item = Utility.getPlayItem(this.mediaKuList, this.playType);
  3149. if (item) {
  3150. this.doPlay(item);
  3151. }
  3152. }
  3153. })
  3154. Row() {
  3155. TextInput({ placeholder: '输入名称...', text: this.searchText })
  3156. .height(35)
  3157. .onChange((value: string) => {
  3158. this.onSearchInput(value);
  3159. })
  3160. .layoutWeight(1)
  3161. Text(`取消`)
  3162. .margin({ left: 10, right: 10 })
  3163. .fontColor($r('app.color.text_color'))
  3164. .fontSize(16)
  3165. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3166. .onClick(() => {
  3167. this.isSearchMode = false
  3168. this.searchText = ''
  3169. if(this.modeType==0){
  3170. this.updateListData(this.videoLocalList)
  3171. } else if(this.modeType==1){
  3172. this.updateListData(this.mediaKuList)
  3173. } else if(this.modeType==2&&!this.isCanBack){
  3174. this.updateListData(this.artistList)
  3175. } else if(this.modeType==3&&!this.isCanBack){
  3176. this.updateListData(this.albumList)
  3177. }
  3178. })
  3179. }
  3180. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  3181. .animation({
  3182. duration: 666,
  3183. curve: 'ease-in-out' // 可选动画曲线
  3184. })
  3185. Blank()
  3186. Image($r("app.media.search"))
  3187. .width(25)// .visibility(this.modeType===1?Visibility.Visible:Visibility.None)
  3188. .animation({
  3189. duration: 666,
  3190. curve: 'ease-in-out' // 可选动画曲线
  3191. })// .opacity(this.opacityItem)
  3192. .fillColor(this.themeColor)
  3193. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3194. .onClick(() => {
  3195. this.isSearchMode = true
  3196. })
  3197. Image($r("app.media.refresh"))
  3198. .fillColor(this.themeColor)
  3199. .width(25)
  3200. .visibility(this.isHistory || this.isCanBack || this.isSearchMode ? Visibility.None : Visibility.Visible)
  3201. .animation({
  3202. duration: 666,
  3203. curve: 'ease-in-out' // 可选动画曲线
  3204. })
  3205. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3206. .onClick(() => {
  3207. if (this.isFavMusic) {
  3208. this.getFavList(true)
  3209. } else {
  3210. if(this.modeType == 0){
  3211. this.asyncCurrentPathData()
  3212. }else if(this.modeType ==1){
  3213. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  3214. }
  3215. }
  3216. })
  3217. Image($r("app.media.top_rank"))
  3218. .width(25)
  3219. .visibility(this.isHistory || this.isSearchMode ? Visibility.None :
  3220. Visibility.Visible)// .opacity(this.opacityItem)
  3221. .animation({
  3222. duration: 666,
  3223. curve: 'ease-in-out' // 可选动画曲线
  3224. })
  3225. .fillColor(this.themeColor)
  3226. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3227. .onClick(() => {
  3228. this.showRankDialog()
  3229. })
  3230. Image(this.isMultiSelect ? $r("app.media.cancel_multi") : $r("app.media.top_flower"))
  3231. .width(24)
  3232. .visibility(this.isHistory || this.isSearchMode ? Visibility.None : Visibility.Visible)
  3233. .animation({
  3234. duration: 666,
  3235. curve: 'ease-in-out' // 可选动画曲线
  3236. })
  3237. .fillColor(this.themeColor)
  3238. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3239. .onClick(() => {
  3240. this.isMultiSelect = !this.isMultiSelect
  3241. })
  3242. SymbolGlyph($r('sys.symbol.trash'))
  3243. .fontColor([this.themeColor])
  3244. .fontSize(25)
  3245. .effectStrategy(1)
  3246. .visibility(this.isHistory ? Visibility.Visible : Visibility.None)
  3247. .animation({
  3248. duration: 666,
  3249. curve: 'ease-in-out' // 可选动画曲线
  3250. })
  3251. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3252. .onClick(() => {
  3253. this.clearVideoHistory() //清空播放记录
  3254. })
  3255. Image(this.isGridMusic ? $r('app.media.list') : $r("app.media.grid"))
  3256. .width(24)
  3257. .animation({
  3258. duration: 666,
  3259. curve: 'ease-in-out' // 可选动画曲线
  3260. })
  3261. .fillColor(this.themeColor)
  3262. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  3263. .bindPopup($$this.tipPopup, {
  3264. builder: this.popupBuilder,
  3265. placement: Placement.Bottom,
  3266. maskColor: 0x33000000,
  3267. enableArrow: true,
  3268. onStateChange: (e) => {
  3269. if (!e.isVisible) {
  3270. this.tipPopup = false;
  3271. }
  3272. }
  3273. })
  3274. .onClick(() => {
  3275. if(this.twoFingerType==4){
  3276. this.isGridMusic = false
  3277. this.twoFingerType=3
  3278. }else{
  3279. this.isGridMusic = !this.isGridMusic
  3280. }
  3281. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  3282. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  3283. })
  3284. }
  3285. .width('100%')
  3286. .padding(10)
  3287. .height(50)
  3288. .visibility(this.modeType === 0 || this.modeType === 1 || this.isCanBack ? Visibility.Visible : Visibility.None)
  3289. .border({
  3290. width: { bottom: 1 },
  3291. color: this.isCustomizeBg ? Color.Transparent : '#12ec5c87'
  3292. })
  3293. }
  3294. .visibility(this.isShowAllBar ? Visibility.Visible : Visibility.None)
  3295. }
  3296. // 第二步:popup构造器定义弹框内容
  3297. @Builder popupBuilder() {
  3298. Column({ space: 2 }) {
  3299. Text('友情提示:双指缩放可以放大缩小列表')
  3300. .fontSize(12)
  3301. .fontWeight(FontWeight.Regular)
  3302. .fontColor($r('app.color.text_color'))
  3303. }
  3304. .justifyContent(FlexAlign.SpaceAround)
  3305. .width(220)
  3306. .height(55)
  3307. .padding(15)
  3308. }
  3309. //搜索功能的实现
  3310. @State searchText: string = ''; // 用户输入内容
  3311. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  3312. @State isSearchMode: boolean = false
  3313. // 实时搜索逻辑(带防抖)
  3314. private onSearchInput(value: string) {
  3315. this.searchText = value.trim();
  3316. let mSearchList: Array<VideoItem> = []
  3317. switch (this.modeType) {
  3318. case 0:
  3319. // mSearchList = this.videoLocalList
  3320. // break;
  3321. case 1:
  3322. mSearchList = this.mediaKuList
  3323. break;
  3324. case 2:
  3325. mSearchList = this.artistList
  3326. break;
  3327. case 3:
  3328. mSearchList = this.albumList
  3329. break;
  3330. }
  3331. // 新增条件判断:空输入时显示所有数据
  3332. if (this.searchText === '') {
  3333. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  3334. } else {
  3335. this.filteredList = mSearchList.filter((item: VideoItem) => {
  3336. //支持模糊匹配和艺术家 专辑匹配
  3337. const regex = new RegExp(this.searchText.toLowerCase().replace(/\s+/g, '.*'), 'i');
  3338. return regex.test(item.name.toLowerCase())||
  3339. regex.test(item.fileName?.toLowerCase() ?? "") ||
  3340. regex.test(item.artist?.toLowerCase() ?? "") ||
  3341. regex.test(item.album?.toLowerCase() ?? "")
  3342. });
  3343. }
  3344. this.updateListData(this.filteredList);
  3345. // this.isSearchMode = false; // 根据业务需求决定是否启用
  3346. }
  3347. @State dragItem: number = -1
  3348. @State scaleItem: number = -1
  3349. @State neighborItem: number = -1
  3350. @State neighborScale: number = -1
  3351. @State offsetY: number = 0
  3352. private dragRefOffset: number = 0
  3353. private ITEM_INTV: number = 78
  3354. scaleSelect(item: number): number {
  3355. if (this.scaleItem === item) {
  3356. return 1.05
  3357. } else if (this.neighborItem === item) {
  3358. return this.neighborScale
  3359. } else {
  3360. return 1
  3361. }
  3362. }
  3363. itemMove(index: number, newIndex: number): void {
  3364. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  3365. return;
  3366. }
  3367. let tmp = this.videoLocalList.splice(index, 1);
  3368. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  3369. this.dataSource.pushArrayData(this.videoLocalList)
  3370. }
  3371. //瀑布流布局 支持双指缩放
  3372. @State columns: number = 2;
  3373. @State waterFlowScale: number = 1;
  3374. @State imageScale: number = 1;
  3375. @State waterFlowOpacity: number = 1;
  3376. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  3377. private columnChanged: boolean = false;
  3378. private oldColumn: number = this.columns;
  3379. private pinchTime: number = 0;
  3380. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  3381. changeColumns(scale: number) {
  3382. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  3383. this.columns--;
  3384. this.columnChanged = true;
  3385. } else if (scale < 1 && this.columns < 4) {
  3386. this.columns++;
  3387. this.columnChanged = true;
  3388. }
  3389. }
  3390. @Builder
  3391. getWaterView(){
  3392. Scroll(this.scroller) {
  3393. Column() {
  3394. if(this.isShowCoverHeader()){
  3395. this.coverHeader()
  3396. }else {
  3397. this.listViewTitle()
  3398. }
  3399. WaterFlow({
  3400. scroller:this.waterScroller,
  3401. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  3402. }) {
  3403. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  3404. FlowItem() {
  3405. this.MusicWaterCardItem(item,index)
  3406. }
  3407. .width('100%')
  3408. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  3409. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  3410. {
  3411. preview: MenuPreviewMode.IMAGE,
  3412. previewAnimationOptions: { scale: [0.8, 1.0] },
  3413. })
  3414. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  3415. {
  3416. preview: MenuPreviewMode.IMAGE,
  3417. previewAnimationOptions: { scale: [0.8, 1.0] },
  3418. })
  3419. .transition(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }))
  3420. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  3421. TransitionEffect.scale({ x: 0, y: 0 })))
  3422. .gesture(
  3423. GestureGroup(GestureMode.Exclusive,
  3424. SwipeGesture({ direction: SwipeDirection.Horizontal })
  3425. .onAction((event: GestureEvent) => {
  3426. if (event) {
  3427. // this.sideBarController.openSideBar()
  3428. }
  3429. }),
  3430. TapGesture({ count: 1, fingers: 1 })
  3431. .onAction(async () => {
  3432. })
  3433. )
  3434. )
  3435. }, (item: VideoItem) => item.filePath)
  3436. }
  3437. // .columnsTemplate('repeat(auto-fit, 160)')
  3438. .id('waterflow') // 设置id用于截图
  3439. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  3440. .columnsGap(12) // 列间距
  3441. .rowsGap(16) // 行间距
  3442. .cachedCount(6)
  3443. .margin(
  3444. this.isHiCar()?{bottom:this.bottomBarHeight+90}:
  3445. {bottom:this.isShowCoverHeader()? this.topBarHeight+35:
  3446. this.isCoverOpacity()?this.topBarHeight+this.bottomBarHeight+78
  3447. :this.topBarHeight+this.bottomBarHeight+108})
  3448. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3449. .animation({ duration: 500, curve: Curve.Ease }))
  3450. .scrollBar(BarState.Off)
  3451. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  3452. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  3453. .edgeEffect(EdgeEffect.Spring, { alwaysEnabled: true })
  3454. .width('100%')
  3455. .height('100%')
  3456. .padding(10)
  3457. .opacity(this.waterFlowOpacity)
  3458. .scale({
  3459. x: this.waterFlowScale,
  3460. y: this.waterFlowScale,
  3461. centerX: 0,
  3462. centerY: 0
  3463. })
  3464. .onAppear(() => {
  3465. this.scroller.scrollEdge(Edge.Top)
  3466. })
  3467. .nestedScroll({
  3468. scrollForward: NestedScrollMode.PARENT_FIRST,
  3469. scrollBackward: NestedScrollMode.SELF_FIRST
  3470. })
  3471. .priorityGesture(
  3472. PinchGesture()
  3473. .onActionStart((event: GestureEvent) => {
  3474. // 双指捏合手势识别成功时截图
  3475. this.pinchTime = event.timestamp;
  3476. this.columnChanged = false;
  3477. this.oldColumn = this.columns;
  3478. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  3479. if (error) {
  3480. console.info('error:' + JSON.stringify(error));
  3481. return;
  3482. }
  3483. this.waterFlowSnapshot = pixmap;
  3484. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  3485. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  3486. if (this.oldColumn ===4) {
  3487. this.twoFingerType =3
  3488. this.isGridMusic = true
  3489. }else if (this.oldColumn ===1) {
  3490. this.twoFingerType =1
  3491. this.isGridMusic = false
  3492. }
  3493. return;
  3494. }
  3495. })
  3496. })
  3497. .onActionUpdate((event: GestureEvent) => {
  3498. // 手势更新:处理缩放逻辑和视觉效果
  3499. // 边界限制:防止超出列数范围时继续缩放
  3500. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  3501. return;
  3502. }
  3503. // 节流处理:避免过于频繁的更新,提升性能
  3504. if (event.timestamp - this.pinchTime < 10000000) {
  3505. return;
  3506. }
  3507. this.pinchTime = event.timestamp;
  3508. this.waterFlowScale = event.scale;
  3509. this.imageScale = event.scale;
  3510. // 根据缩放比例设置WaterFlow透明度
  3511. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  3512. this.waterFlowOpacity *= 3;
  3513. if (!this.columnChanged) {
  3514. this.changeColumns(event.scale);
  3515. }
  3516. // 列数改变后的缩放比例调整:避免出现空白区域
  3517. if (this.columnChanged) {
  3518. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  3519. // 限制缩放范围,确保视觉效果自然
  3520. if (event.scale < 1) {
  3521. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  3522. } else {
  3523. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  3524. }
  3525. }
  3526. })
  3527. .onActionEnd((event: GestureEvent) => {
  3528. // 手势结束:执行归位动画并保存状态
  3529. // 执行归位动画:平滑过渡到正常状态
  3530. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  3531. this.waterFlowScale = 1;
  3532. this.waterFlowOpacity = 1;
  3533. })
  3534. // 持久化保存当前列数:下次启动时恢复
  3535. PreferencesUtil.putSync('lastColumns', this.columns);
  3536. })
  3537. )
  3538. //允许拖拽音乐和视频到List或Grid上自动导入视频
  3539. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3540. .onDrop((event?: DragEvent) => {
  3541. try {
  3542. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3543. if (dragData !== undefined) {
  3544. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3545. if (records.length > 0) {
  3546. for (let i = 0; i < records.length; i++) {
  3547. let types = records[i].getTypes();
  3548. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3549. const fileUriUds =
  3550. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3551. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3552. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3553. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3554. this.targetFile = fileUriUds.oriUri;
  3555. this.saveVideoDatas([this.targetFile])
  3556. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3557. }
  3558. }
  3559. }
  3560. } else {
  3561. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3562. }
  3563. } else {
  3564. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3565. }
  3566. } catch (error) {
  3567. const err = error as BusinessError;
  3568. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3569. }
  3570. })
  3571. }
  3572. }
  3573. .scrollBar(BarState.Off)
  3574. }
  3575. //瀑布流卡片布局
  3576. @Builder
  3577. private MusicWaterCardItem(item: VideoItem, index: number) {
  3578. Button({ type: ButtonType.Normal, stateEffect: false }) {
  3579. Stack() {
  3580. Column() {
  3581. Image(StrUtil.isEmpty(item.pixelMapPath) ? Utility.getMusisBg2(index) : item.pixelMapPath)
  3582. .backgroundImageSize(ImageSize.Auto)
  3583. .borderRadius({
  3584. topLeft: 12,
  3585. topRight : 12,
  3586. bottomLeft: 0,
  3587. bottomRight: 0
  3588. })
  3589. .draggable(false)// 禁止长按手势拖动
  3590. // .autoResize(true) // 重采样,可减少内存占用
  3591. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  3592. .width('100%')
  3593. .height('auto')
  3594. .objectFit(ImageFit.Auto)
  3595. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  3596. height: '99%' ,
  3597. dragBar: true,
  3598. onDisappear: () => {
  3599. this.longItemFilePath = '';
  3600. this.tempLyricContent = ''
  3601. },
  3602. showClose: true,
  3603. preferType: SheetType.CENTER ,
  3604. title: { title: '编辑标签' }
  3605. })
  3606. .draggable(false)
  3607. .opacity(this.opacityItem)// 绑定透明度
  3608. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3609. // .animation({ duration: 500, curve: Curve.Ease }))
  3610. .animation({
  3611. duration: 666,
  3612. curve: 'ease-in-out' // 可选动画曲线
  3613. })
  3614. .margin({
  3615. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3616. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3617. })
  3618. Column() {
  3619. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  3620. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  3621. .maxLines(1)
  3622. .fontWeight(FontWeight.Bold)
  3623. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  3624. .animation({
  3625. duration: 555,
  3626. curve: 'Linear',
  3627. })
  3628. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  3629. height: '95%',
  3630. dragBar: true,
  3631. showClose: true,
  3632. onDisappear: () => {
  3633. this.longItemFilePathDetail = '';
  3634. },
  3635. blurStyle:BlurStyle.Thin,
  3636. backgroundColor:Color.Transparent,
  3637. preferType: SheetType.CENTER ,
  3638. title: { title: '详情' }
  3639. })
  3640. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3641. $r('app.color.text_color'))
  3642. Column() {
  3643. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  3644. .fontSize(11)
  3645. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  3646. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3647. .fontColor($r('app.color.text_color'))
  3648. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  3649. .fontSize(11)
  3650. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  3651. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  3652. .fontColor($r('app.color.text_color'))
  3653. Row(){
  3654. Column(){
  3655. Text(item.md5Str?.includes('Lossless')?
  3656. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  3657. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  3658. .padding({ top: 3,right:6,left:6,bottom:3 })
  3659. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3660. $r('app.color.text_color'))
  3661. .fontWeight(500)
  3662. .borderRadius(12)
  3663. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  3664. .backgroundColor('#FFC107')
  3665. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  3666. }
  3667. .margin({ top: 2 ,right:6})
  3668. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  3669. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  3670. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  3671. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  3672. .maxLines(1)
  3673. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  3674. .margin({ top: 2})
  3675. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  3676. || item.type == CommonConstants.TYPE_IS_ALBUM
  3677. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3678. .fontWeight(FontWeight.Medium)
  3679. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3680. $r('app.color.text_color'))
  3681. }
  3682. }
  3683. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  3684. }
  3685. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  3686. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  3687. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  3688. .width('100%')
  3689. .justifyContent(FlexAlign.Center)
  3690. .margin({
  3691. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3692. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3693. })
  3694. }
  3695. .width('100%')
  3696. .borderRadius(12)
  3697. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?Utility.getMusisBg2(index):item.pixelMapPath)
  3698. .backgroundImageSize({ height: '100%', width: '100%' })
  3699. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  3700. .animation({ curve: Curve.Sharp, duration: 300 })
  3701. Checkbox({ name: 'checkbox' + index })
  3702. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  3703. .selectedColor(this.themeColor)
  3704. .shape(CheckBoxShape.CIRCLE)
  3705. .opacity(this.isMultiSelect ? 1 : 0)
  3706. .animation({
  3707. duration: 666,
  3708. curve: 'Smooth' // 可选动画曲线
  3709. })
  3710. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  3711. Visibility.None)
  3712. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  3713. .margin({ left: 20, top: 8, bottom: 8 })
  3714. .width(38)
  3715. .height(38)
  3716. }
  3717. }
  3718. .backgroundColor(Color.Transparent)
  3719. .width('100%')
  3720. .height('auto')
  3721. .padding({top:2})
  3722. .reuseId('card_item')
  3723. .onClick(() => {
  3724. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  3725. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  3726. this.handleFileSelection(item, !isChecked);
  3727. } else {
  3728. this.doPlay(item, index)
  3729. }
  3730. })
  3731. }
  3732. // Grid布局的开始
  3733. private dragRefOffSetX: number = 0;
  3734. private dragRefOffSetY: number = 0;
  3735. private FIX_VP_X: number = 180;
  3736. private FIX_VP_Y: number = 84;
  3737. isDraggable(index: number): boolean {
  3738. return index >= 0;
  3739. }
  3740. getRowEnd(item: number) {
  3741. if (item.toString() === '0') {
  3742. return 1;
  3743. } else {
  3744. return 0;
  3745. }
  3746. }
  3747. isInLeft(index: number) {
  3748. return index % 2 == 0;
  3749. }
  3750. down(index: number): void {
  3751. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  3752. return;
  3753. }
  3754. this.offsetY -= this.FIX_VP_Y;
  3755. this.dragRefOffSetY += this.FIX_VP_Y;
  3756. this.itemMove(index, index + 1);
  3757. }
  3758. up(index: number): void {
  3759. if (!this.isDraggable(index - 2)) {
  3760. return;
  3761. }
  3762. this.offsetY += this.FIX_VP_Y;
  3763. this.dragRefOffSetY -= this.FIX_VP_Y;
  3764. this.itemMove(index, index - 1);
  3765. }
  3766. left(index: number): void {
  3767. if (this.isInLeft(index)) {
  3768. return;
  3769. }
  3770. if (!this.isDraggable(index - 1)) {
  3771. return;
  3772. }
  3773. this.offsetX += this.FIX_VP_X;
  3774. this.dragRefOffSetX -= this.FIX_VP_X;
  3775. this.itemMove(index, index - 1)
  3776. }
  3777. right(index: number): void {
  3778. if (!this.isInLeft(index)) {
  3779. return;
  3780. }
  3781. if (!this.isDraggable(index + 1)) {
  3782. return;
  3783. }
  3784. this.offsetX -= this.FIX_VP_X;
  3785. this.dragRefOffSetX += this.FIX_VP_X;
  3786. this.itemMove(index, index + 1)
  3787. }
  3788. private scroller: Scroller = new Scroller();
  3789. private waterScroller: Scroller = new Scroller();
  3790. @State startIndex: number = 0
  3791. @State endIndex: number = 0
  3792. @State scaleValue: number = 1
  3793. @State pinchValue: number = 1
  3794. layoutOptionsForHeader: GridLayoutOptions = {
  3795. regularSize: [1, 1], // 只支持[1, 1]
  3796. irregularIndexes: [0], // 索引为0的GridItem占用一行
  3797. };
  3798. @Builder
  3799. getGridView() {
  3800. Grid(this.scroller, this.layoutOptionsForHeader) {
  3801. GridItem() {
  3802. if (this.isShowCoverHeader()) {
  3803. this.coverHeader()
  3804. } else {
  3805. this.listViewTitle()
  3806. }
  3807. }
  3808. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  3809. GridItem() {
  3810. Stack({ alignContent: Alignment.Center }) {
  3811. this.MusicItemGrid(item, index)
  3812. }
  3813. }
  3814. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  3815. {
  3816. preview: MenuPreviewMode.IMAGE,
  3817. previewAnimationOptions: { scale: [0.8, 1.0] },
  3818. })
  3819. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  3820. {
  3821. preview: MenuPreviewMode.IMAGE,
  3822. previewAnimationOptions: { scale: [0.8, 1.0] },
  3823. })
  3824. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  3825. TransitionEffect.scale({ x: 0, y: 0 })))
  3826. .clickEffect({ level: ClickEffectLevel.LIGHT })
  3827. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  3828. .zIndex(this.dragItem === index ? 1 : 0)
  3829. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  3830. }, (item: VideoItem) => item.filePath)
  3831. }
  3832. .width(this.isShowHeader ? '100%' : '94%')
  3833. .height('100%')
  3834. .editMode(true)
  3835. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  3836. .animation({ duration: 500, curve: Curve.Ease }))
  3837. .margin(
  3838. this.isHiCar()?{bottom:this.bottomBarHeight+98}:
  3839. {
  3840. bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? this.topBarHeight+30 : this.topBarHeight+90)
  3841. : (this.isShowCoverHeader() ? this.topBarHeight+45 : this.topBarHeight+128)
  3842. })
  3843. .reuseId('grid_item')
  3844. .layoutWeight(1)
  3845. .scrollBar(BarState.Off)
  3846. .supportAnimation(true)
  3847. .cachedCount(this.twoFingerType==1?5:this.twoFingerType==2?4:3)
  3848. .columnsTemplate(
  3849. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  3850. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  3851. )
  3852. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  3853. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  3854. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  3855. .gesture(PinchGesture({ fingers: 2 })
  3856. .onActionEnd((event: GestureEvent) => {
  3857. this.setGridTwoFingers()
  3858. })
  3859. .onActionUpdate(e => {
  3860. this.scaleValue = this.pinchValue * e.scale
  3861. })
  3862. .onActionStart(e => {
  3863. }))
  3864. .enableScrollInteraction(true)
  3865. .onScrollIndex((start: number, end: number) => {
  3866. this.startIndex = start
  3867. this.endIndex = end
  3868. })
  3869. .onScrollFrameBegin((offset: number) => {
  3870. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  3871. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  3872. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  3873. if (this.isScrollHide) {
  3874. this.setBarHeightHide2(offset)
  3875. } else {
  3876. this.setBarHeightNormal()
  3877. }
  3878. } else {
  3879. this.setBarHeightHide(offset)
  3880. }
  3881. return { offsetRemain: offset };
  3882. })
  3883. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3884. .onDrop((event?: DragEvent) => {
  3885. try {
  3886. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3887. if (dragData !== undefined) {
  3888. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3889. if (records.length > 0) {
  3890. for (let i = 0; i < records.length; i++) {
  3891. let types = records[i].getTypes();
  3892. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3893. const fileUriUds =
  3894. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3895. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3896. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3897. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3898. this.targetFile = fileUriUds.oriUri;
  3899. this.saveVideoDatas([this.targetFile])
  3900. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3901. }
  3902. }
  3903. }
  3904. } else {
  3905. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3906. }
  3907. } else {
  3908. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3909. }
  3910. } catch (error) {
  3911. const err = error as BusinessError;
  3912. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3913. }
  3914. })
  3915. }
  3916. @State targetFile: string = '';
  3917. setGridTwoFingers() {
  3918. this.pinchValue = this.scaleValue;
  3919. Logger.info('this.pinchValue = ' + this.pinchValue);
  3920. if (this.pinchValue >= 1) {
  3921. this.twoFingerType++
  3922. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  3923. if(this.twoFingerType >= 4){
  3924. this.twoFingerType = 4//切换成瀑布流
  3925. this.columns = 4
  3926. }
  3927. } else {
  3928. this.twoFingerType--
  3929. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  3930. if (this.twoFingerType < 1) {
  3931. this.twoFingerType = 3
  3932. this.isGridMusic = false
  3933. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  3934. }
  3935. }
  3936. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  3937. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  3938. this.pinchValue = 1;
  3939. this.scaleValue = 1;
  3940. }
  3941. @State longItemFilePath: string = ''
  3942. @State tempLyricContent: string = ''
  3943. @Builder
  3944. private MusicItemGrid(item: VideoItem, index: number) {
  3945. Button({ type: ButtonType.Normal, stateEffect: false }) {
  3946. Stack() {
  3947. Column() {
  3948. Image(StrUtil.isEmpty(item.pixelMapPath) ? Utility.getMusisBg2(index) : item.pixelMapPath)
  3949. .height(this.getGridHeight())
  3950. .width(this.getGridWight())
  3951. .draggable(false)
  3952. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  3953. .autoResize(true) // 重采样,可减少内存占用
  3954. .alt($r('app.media.ic_avatar2'))
  3955. .clip(true)
  3956. .borderRadius({
  3957. topLeft: 12,
  3958. topRight: 12,
  3959. bottomLeft: 0,
  3960. bottomRight: 0
  3961. })
  3962. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  3963. height: '99%' ,
  3964. dragBar: true,
  3965. onDisappear: () => {
  3966. this.longItemFilePath = '';
  3967. this.tempLyricContent = ''
  3968. },
  3969. showClose: true,
  3970. preferType: SheetType.CENTER ,
  3971. title: { title: '编辑标签' }
  3972. })
  3973. .draggable(false)
  3974. .opacity(this.opacityItem)// 绑定透明度
  3975. .animation({
  3976. duration: 666,
  3977. curve: 'ease-in-out' // 可选动画曲线
  3978. })
  3979. .margin({
  3980. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  3981. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  3982. })
  3983. Column() {
  3984. Text(this.isShowFileName&&item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  3985. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  3986. .maxLines(1)
  3987. .fontWeight(FontWeight.Bold)
  3988. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  3989. .animation({
  3990. duration: 555,
  3991. curve: 'Linear',
  3992. })
  3993. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  3994. height: '95%',
  3995. dragBar: true,
  3996. showClose: true,
  3997. onDisappear: () => {
  3998. this.longItemFilePathDetail = '';
  3999. },
  4000. blurStyle:BlurStyle.Thin,
  4001. backgroundColor:Color.Transparent,
  4002. preferType: SheetType.CENTER ,
  4003. title: { title: '详情' }
  4004. })
  4005. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4006. $r('app.color.text_color'))
  4007. Column() {
  4008. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  4009. .fontSize(11)
  4010. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  4011. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4012. .fontColor($r('app.color.text_color'))
  4013. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  4014. .fontSize(11)
  4015. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  4016. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4017. .fontColor($r('app.color.text_color'))
  4018. Row(){
  4019. Column(){
  4020. Text(item.md5Str?.includes('Lossless')?
  4021. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4022. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  4023. .padding({ top: 3,right:6,left:6,bottom:3 })
  4024. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4025. $r('app.color.text_color'))
  4026. .fontWeight(500)
  4027. .borderRadius(12)
  4028. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4029. .backgroundColor('#FFC107')
  4030. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  4031. }
  4032. .margin({ top: 2 ,right:6})
  4033. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  4034. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  4035. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  4036. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  4037. .maxLines(1)
  4038. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4039. .margin({ top: 2})
  4040. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  4041. || item.type == CommonConstants.TYPE_IS_ALBUM
  4042. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4043. .fontWeight(FontWeight.Medium)
  4044. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4045. $r('app.color.text_color'))
  4046. }
  4047. }
  4048. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  4049. }
  4050. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  4051. .width(this.getGridWight())
  4052. .justifyContent(FlexAlign.Center)
  4053. .margin({
  4054. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4055. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4056. })
  4057. }
  4058. .width(this.getGridWight())
  4059. .borderRadius(12)
  4060. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?Utility.getMusisBg2(index):item.pixelMapPath)
  4061. .backgroundImageSize({ height: '100%', width: '100%' })
  4062. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  4063. .animation({ curve: Curve.Sharp, duration: 300 })
  4064. Checkbox({ name: 'checkbox' + index })
  4065. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  4066. .selectedColor(this.themeColor)
  4067. .shape(CheckBoxShape.CIRCLE)
  4068. .opacity(this.isMultiSelect ? 1 : 0)
  4069. .animation({
  4070. duration: 666,
  4071. curve: 'Smooth' // 可选动画曲线
  4072. })
  4073. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  4074. Visibility.None)
  4075. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  4076. .margin({ left: 20, top: 8, bottom: 8 })
  4077. .width(38)
  4078. .height(38)
  4079. }
  4080. }
  4081. .backgroundColor(Color.Transparent)
  4082. .width('100%')
  4083. .padding({ top: 15 })
  4084. .height(this.getGridAllHeight())
  4085. .onClick(() => {
  4086. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  4087. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4088. this.handleFileSelection(item, !isChecked);
  4089. } else {
  4090. this.doPlay(item, index)
  4091. }
  4092. })
  4093. }
  4094. getGridAllHeight() {
  4095. let heightG = 222
  4096. switch (this.twoFingerType) {
  4097. case 1:
  4098. heightG = 143
  4099. break;
  4100. case 2:
  4101. heightG = 178
  4102. break;
  4103. case 3:
  4104. heightG = 222
  4105. break;
  4106. }
  4107. return heightG
  4108. }
  4109. getGridHeight() {
  4110. let heightG = 150
  4111. switch (this.twoFingerType) {
  4112. case 1:
  4113. heightG = 80
  4114. break;
  4115. case 2:
  4116. heightG = 110
  4117. break;
  4118. case 3:
  4119. heightG = 150
  4120. break;
  4121. }
  4122. return heightG
  4123. }
  4124. getGridWight() {
  4125. let wightG = 158
  4126. switch (this.twoFingerType) {
  4127. case 1:
  4128. wightG = 80
  4129. break;
  4130. case 2:
  4131. wightG = 110
  4132. break;
  4133. case 3:
  4134. wightG = 158
  4135. break;
  4136. }
  4137. return wightG
  4138. }
  4139. @State isShowDetail:boolean = false
  4140. @State longItemFilePathDetail:string =''
  4141. @Builder
  4142. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  4143. if(
  4144. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4145. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4146. item.name === LocalMusic.STR_HISTORY_MUSIC)
  4147. ){
  4148. //如果是专辑和艺术家的首页,不能长按
  4149. //如果是我的收藏 最近播放等也不能长按
  4150. }else{
  4151. Scroll() {
  4152. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  4153. Menu() {
  4154. MenuItem({
  4155. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  4156. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  4157. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  4158. })
  4159. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4160. .onClick(() => {
  4161. if (item) {
  4162. this.doFav(item)
  4163. }
  4164. this.longItemFilePath = ''
  4165. })
  4166. MenuItem({
  4167. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  4168. content: '下一首播放'
  4169. })
  4170. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4171. .onClick(() => {
  4172. this.addToNextPlay(item);
  4173. this.longItemFilePath = ''
  4174. })
  4175. MenuItem({
  4176. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  4177. content: '添加到歌单'
  4178. })
  4179. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4180. .onClick(async () => {
  4181. this.longItemFilePath = ''
  4182. await this.showAddToPlaylistDialog(item)
  4183. })
  4184. MenuItem({
  4185. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  4186. content: '编辑标签'
  4187. })
  4188. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  4189. height: '99%',
  4190. dragBar: true,
  4191. showClose: true,
  4192. preferType: SheetType.CENTER ,
  4193. title: { title: '编辑标签' }
  4194. })
  4195. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4196. .onClick(async() => {
  4197. this.setEditStrEmpty()
  4198. this.tempLyricContent = await this.getLyricContent(item);
  4199. if(this.isGridMusic||this.twoFingerType==4){
  4200. this.longItemFilePath = item.filePath
  4201. }else{
  4202. this.isShowEdit = !this.isShowEdit;
  4203. }
  4204. })
  4205. MenuItem({
  4206. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  4207. content: $r('app.string.select_all')
  4208. })
  4209. .onClick(() => {
  4210. this.isMultiSelect = !this.isMultiSelect
  4211. this.longItemFilePath = ''
  4212. this.selectedFiles.push(item)
  4213. })
  4214. MenuItem({
  4215. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  4216. content: $r('app.string.rename')
  4217. })
  4218. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  4219. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4220. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  4221. .onClick(() => {
  4222. this.showReNameDialog(item, index + '', filePath)
  4223. this.longItemFilePath = ''
  4224. })
  4225. MenuItem({
  4226. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  4227. content: $r('app.string.delete')
  4228. })
  4229. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  4230. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4231. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  4232. .onClick(() => {
  4233. this.selectedFiles.push(item)
  4234. this.showWarnIsDelete()
  4235. this.longItemFilePath = ''
  4236. })
  4237. MenuItem({
  4238. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  4239. content: $r('app.string.detail')
  4240. })
  4241. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  4242. height:'95%',
  4243. dragBar: true,
  4244. showClose: true,
  4245. blurStyle:BlurStyle.Thin,
  4246. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  4247. backgroundColor:Color.Transparent,
  4248. title: { title: '详情信息' }
  4249. })
  4250. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4251. .onClick(() => {
  4252. if(this.isGridMusic||this.twoFingerType==4){
  4253. this.longItemFilePathDetail = item.filePath
  4254. }else{
  4255. this.isShowDetail = !this.isShowDetail
  4256. }
  4257. })
  4258. MenuItem({
  4259. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  4260. content: $r('app.string.share')
  4261. })
  4262. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4263. .onClick(() => {
  4264. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  4265. this.longItemFilePath = ''
  4266. })
  4267. }
  4268. .font({ size: 15, weight: FontWeight.Normal })
  4269. }
  4270. .width(180)
  4271. }
  4272. .height('auto')
  4273. }
  4274. }
  4275. private listMaxScrollOffsetY: number = 0
  4276. @State selectedIndex: number = -1
  4277. setlistTwoFingers() {
  4278. this.pinchValue = this.scaleValue;
  4279. Logger.info('this.pinchValue = ' + this.pinchValue);
  4280. if (this.pinchValue >= 1) {
  4281. this.twoFingerType++
  4282. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  4283. if (this.twoFingerType > 3) {
  4284. this.twoFingerType = 1
  4285. this.isGridMusic = true
  4286. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4287. }
  4288. } else {
  4289. this.twoFingerType--
  4290. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  4291. if (this.twoFingerType < 1) {
  4292. this.twoFingerType = 4
  4293. this.columns = 1
  4294. }
  4295. }
  4296. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  4297. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4298. this.pinchValue = 1;
  4299. this.scaleValue = 1;
  4300. }
  4301. @Builder
  4302. getList(){
  4303. Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
  4304. this.getListView()
  4305. }
  4306. .pullDownRatio(this.ratioL)
  4307. .pullToRefresh(true)
  4308. .refreshOffset(0)
  4309. .onOffsetChange((offset: number) => {
  4310. // 越接近最大距离,下拉跟手系数越小。
  4311. this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
  4312. })
  4313. .onStateChange((refreshStatus: RefreshStatus) => {
  4314. console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
  4315. })
  4316. .onRefreshing(async () => {
  4317. if(this.modeType==0){
  4318. this.getHistoryList(false)
  4319. this.asyncCurrentPathOnlyFile()
  4320. }else if(this.modeType == 1){
  4321. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  4322. }else if(this.modeType == 2){
  4323. workerInstance.postMessage({ code: 3, data: this.context });
  4324. }else if(this.modeType == 3){
  4325. workerInstance.postMessage({ code: 4, data: this.context });
  4326. }
  4327. console.log('onRefreshing test');
  4328. })
  4329. }
  4330. // 扫描当前目录下的文件,不扫描子目录
  4331. asyncCurrentPathOnlyFile(){
  4332. if(this.modeType==0){
  4333. const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
  4334. this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
  4335. taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
  4336. if(this.modeType==0){
  4337. this.getSortedFiles(this.currentPath)
  4338. }
  4339. setTimeout(() => {
  4340. this.isRefreshing = false;
  4341. }, 100)
  4342. }).catch((e:object)=>{
  4343. console.info("task1 catch e: " + e);
  4344. })
  4345. }
  4346. }
  4347. @Builder
  4348. getListView() {
  4349. List({ scroller: this.listScroller }) {
  4350. ListItemGroup({ header: this.coverHeader() }) {
  4351. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  4352. ListItem() {
  4353. Column() {
  4354. if (item.type === CommonConstants.TYPE_IS_DIR
  4355. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  4356. this.DirItem(item, index)
  4357. } else if (item.type === CommonConstants.TYPE_IS_CSJAD) { //如果是穿山甲广告
  4358. } else {
  4359. this.MusicItem(item, index)
  4360. }
  4361. }
  4362. .shadow(this.scaleItem === index ? {
  4363. radius: 70,
  4364. color: '#15000000',
  4365. offsetX: 0,
  4366. offsetY: 0
  4367. } :
  4368. {
  4369. radius: 0,
  4370. color: '#15000000',
  4371. offsetX: 0,
  4372. offsetY: 0
  4373. })
  4374. .animation({ curve: Curve.Sharp, duration: 300 })
  4375. }
  4376. // .transition(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }))
  4377. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  4378. .animation({ duration: 500 }),
  4379. TransitionEffect.scale({ x: 0, y: 0 })))
  4380. .clickEffect({ level: ClickEffectLevel.LIGHT })
  4381. .swipeAction((
  4382. (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
  4383. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  4384. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
  4385. start:null,edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
  4386. .onClick(() => {
  4387. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  4388. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4389. this.handleFileSelection(item, !isChecked);
  4390. } else {
  4391. this.doPlay(item, index)
  4392. }
  4393. })
  4394. //拖动List关键代码开始
  4395. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  4396. .zIndex(this.dragItem === index ? 1 : 0)
  4397. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  4398. .gesture(
  4399. GestureGroup(GestureMode.Sequence,
  4400. LongPressGesture({ repeat: true })
  4401. .onAction((event?: GestureEvent) => {
  4402. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  4403. this.scaleItem = index
  4404. })
  4405. })
  4406. .onActionEnd(() => {
  4407. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  4408. this.scaleItem = -1
  4409. })
  4410. }),
  4411. PanGesture({ fingers: 1, direction: null, distance: 0 })
  4412. .onActionStart(() => {
  4413. this.dragItem = index // 记录当前拖动项索引
  4414. this.dragRefOffset = 0 // 重置偏移基准
  4415. })
  4416. .onActionUpdate((event: GestureEvent) => {
  4417. this.offsetY = event.offsetY - this.dragRefOffset;
  4418. this.neighborItem = -1;
  4419. let indexA = this.videoLocalList.indexOf(item);
  4420. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  4421. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  4422. let value: number = 0;
  4423. if (this.offsetY < 0) {
  4424. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  4425. this.neighborItem = indexA - 1;
  4426. this.neighborScale = 1 - value / 20;
  4427. } else if (this.offsetY > 0) {
  4428. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  4429. this.neighborItem = indexA + 1;
  4430. this.neighborScale = 1 - value / 20;
  4431. }
  4432. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  4433. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4434. this.offsetY -= this.ITEM_INTV;
  4435. this.dragRefOffset += this.ITEM_INTV;
  4436. this.itemMove(indexA, indexA + 1);
  4437. });
  4438. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  4439. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4440. this.offsetY += this.ITEM_INTV;
  4441. this.dragRefOffset -= this.ITEM_INTV;
  4442. this.itemMove(indexA, indexA - 1);
  4443. });
  4444. }
  4445. let curListOffset = this.listScroller.currentOffset()
  4446. // 获取手指信息
  4447. let fingerInfo = event.fingerList[0]
  4448. let clickPercentY =
  4449. (fingerInfo.globalY - Number(this.listArea.globalPosition.y)) / Number(this.listArea.height)
  4450. if (clickPercentY > 0.8 && !this.listScroller.isAtEnd()) {
  4451. let scrollVelocity = clickPercentY > 0.9 ? 4 : 2
  4452. if (this.listMaxScrollOffsetY - curListOffset.yOffset > scrollVelocity + 5) {
  4453. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset += scrollVelocity })
  4454. }
  4455. } else if (clickPercentY < 0.2 && curListOffset.yOffset >= 0) {
  4456. let scrollVelocity = clickPercentY < 0.1 ? 4 : 2
  4457. if (curListOffset.yOffset > scrollVelocity + 5) {
  4458. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset -= scrollVelocity })
  4459. }
  4460. }
  4461. })
  4462. .onActionEnd((event: GestureEvent) => {
  4463. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4464. this.dragItem = -1
  4465. this.neighborItem = -1
  4466. })
  4467. animateTo({
  4468. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  4469. }, () => {
  4470. this.scaleItem = -1
  4471. })
  4472. })
  4473. )
  4474. .onCancel(() => {
  4475. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  4476. this.dragItem = -1
  4477. this.neighborItem = -1
  4478. })
  4479. animateTo({
  4480. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  4481. }, () => {
  4482. this.scaleItem = -1
  4483. })
  4484. })
  4485. ) //拖动List关键代码结束
  4486. }, (item: VideoItem) => item.filePath)
  4487. }
  4488. }
  4489. .scrollBar(BarState.Off)
  4490. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  4491. .gesture(PinchGesture({ fingers: 2 })
  4492. .onActionEnd((event: GestureEvent) => {
  4493. this.setlistTwoFingers()
  4494. })
  4495. .onActionUpdate(e => {
  4496. this.scaleValue = this.pinchValue * e.scale
  4497. })
  4498. .onActionStart(e => {
  4499. }))
  4500. // .divider({ strokeWidth: 1, color: this.isDarkMode? '#333333':'#ffe9f0f0' })
  4501. .margin(
  4502. this.isHiCar()&&(this.windowWidth>1800&&this.windowHeight>=1200)?{bottom:this.bottomBarHeight+98}:
  4503. {
  4504. bottom: this.isCoverOpacity() ? (this.isShowCoverHeader() ? this.topBarHeight+25 : this.topBarHeight+80)
  4505. : (this.isShowCoverHeader() ? this.topBarHeight+35 : this.isHiCarSmall()?this.topBarHeight+90:this.topBarHeight+165)
  4506. })
  4507. .cachedCount(6)
  4508. .reuseId('list_item')
  4509. .borderRadius(20)
  4510. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  4511. TransitionEffect.scale({ x: 0, y: 0 })))
  4512. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4513. // .animation({ duration: 500, curve: Curve.Ease }))
  4514. .layoutWeight(1)
  4515. .onScrollIndex((start) => {
  4516. this.selectedIndex = start
  4517. })
  4518. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  4519. .lanes(
  4520. new BreakpointType<number>({
  4521. sm: 1,
  4522. md: 2,
  4523. lg: 2,
  4524. xl: 3,
  4525. xxl: 4
  4526. }).getValue(this.currentBreakpoint),
  4527. new BreakpointType<number>({
  4528. sm: 0,
  4529. md: 12,
  4530. lg: 12,
  4531. xl: 16,
  4532. xxl: 20
  4533. }).getValue(this.currentBreakpoint)
  4534. )
  4535. .onAreaChange((oldValue: Area, newValue: Area) => {
  4536. this.listArea = newValue
  4537. if (this.twoFingerType == 3) {
  4538. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  4539. } else if (this.twoFingerType == 2) {
  4540. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  4541. } else if (this.twoFingerType == 1) {
  4542. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  4543. }
  4544. })
  4545. .onScrollFrameBegin((offset: number) => {
  4546. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  4547. // if (this.isPhoneLan()) {
  4548. // this.setBarHeightHide(offset)
  4549. // } else
  4550. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  4551. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  4552. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  4553. if (this.isScrollHide) {
  4554. this.setBarHeightHide2(offset)
  4555. } else {
  4556. this.setBarHeightNormal()
  4557. }
  4558. } else {
  4559. this.setBarHeightHide(offset)
  4560. }
  4561. return { offsetRemain: offset };
  4562. })
  4563. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  4564. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  4565. .onDrop((event?: DragEvent) => {
  4566. try {
  4567. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  4568. if (dragData !== undefined) {
  4569. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  4570. if (records.length > 0) {
  4571. for (let i = 0; i < records.length; i++) {
  4572. let types = records[i].getTypes();
  4573. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  4574. const fileUriUds =
  4575. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  4576. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  4577. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  4578. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  4579. this.targetFile = fileUriUds.oriUri;
  4580. this.saveVideoDatas([this.targetFile])
  4581. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  4582. }
  4583. }
  4584. }
  4585. } else {
  4586. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  4587. }
  4588. } else {
  4589. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  4590. }
  4591. } catch (error) {
  4592. const err = error as BusinessError;
  4593. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  4594. }
  4595. })
  4596. }
  4597. setBarHeightNormal() {
  4598. this.hideDone = false;
  4599. this.getUIContext().animateTo({
  4600. duration: 300
  4601. }, () => {
  4602. this.bottomBarHeight = 55 + 0;
  4603. this.topBarHeight = 50 + 0;
  4604. this.barOpacity = 1;
  4605. this.barBottomOpacity = 1
  4606. this.currentYOffset = 0;
  4607. this.isHiding = false;
  4608. });
  4609. }
  4610. setBarHeightHide(offset: number) {
  4611. if (offset > 0 && !this.hideDone) {
  4612. this.currentYOffset += offset;
  4613. if (this.currentYOffset <= 100) {
  4614. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  4615. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  4616. this.barOpacity = 1 - this.currentYOffset / 100;
  4617. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  4618. } else {
  4619. this.topBarHeight = 0;
  4620. this.bottomBarHeight = 0;
  4621. this.barBottomOpacity = 0
  4622. this.barOpacity = 0;
  4623. this.hideDone = true;
  4624. }
  4625. this.isHiding = true;
  4626. }
  4627. if (offset < 0 && this.isHiding) {
  4628. this.hideDone = false;
  4629. this.getUIContext().animateTo({
  4630. duration: 300
  4631. }, () => {
  4632. this.bottomBarHeight = 55 + 0;
  4633. this.topBarHeight = 50 + 0;
  4634. this.barOpacity = 1;
  4635. this.barBottomOpacity = 1
  4636. this.currentYOffset = 0;
  4637. this.isHiding = false;
  4638. });
  4639. }
  4640. }
  4641. //这个方法没隐藏bottomBar,只隐藏topbar
  4642. setBarHeightHide2(offset: number) {
  4643. if (offset > 0 && !this.hideDone) {
  4644. this.currentYOffset += offset;
  4645. if (this.currentYOffset <= 100) {
  4646. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  4647. this.barOpacity = 1 - this.currentYOffset / 100;
  4648. } else {
  4649. this.topBarHeight = 0;
  4650. this.barOpacity = 0;
  4651. this.hideDone = true;
  4652. }
  4653. this.isHiding = true;
  4654. }
  4655. if (offset < 0 && this.isHiding) {
  4656. this.hideDone = false;
  4657. this.getUIContext().animateTo({
  4658. duration: 300
  4659. }, () => {
  4660. this.topBarHeight = 50 + 0;
  4661. this.barOpacity = 1;
  4662. this.currentYOffset = 0;
  4663. this.isHiding = false;
  4664. });
  4665. }
  4666. }
  4667. private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  4668. Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
  4669. switch (item.type) {
  4670. case CommonConstants.TYPE_IS_DIR:
  4671. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  4672. let offsetB = 0
  4673. if(this.twoFingerType==4){
  4674. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  4675. let cur = this.waterScroller.currentOffset()
  4676. if (cur && typeof cur.yOffset === 'number') {
  4677. offsetB = cur.yOffset
  4678. }
  4679. }
  4680. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  4681. }else
  4682. if (this.isGridMusic) {
  4683. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  4684. let cur = this.scroller.currentOffset()
  4685. if (cur && typeof cur.yOffset === 'number') {
  4686. offsetB = cur.yOffset
  4687. }
  4688. }
  4689. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  4690. } else {
  4691. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  4692. let cur = this.listScroller.currentOffset()
  4693. if (cur && typeof cur.yOffset === 'number') {
  4694. offsetB = cur.yOffset
  4695. }
  4696. }
  4697. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  4698. }
  4699. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  4700. this.showVerifyDialog()
  4701. this.currentTitleName = '私密音频'
  4702. this.currentTitleCover = $r('app.media.ic_avatar5')
  4703. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  4704. this.titleBarModel.setTitleName('最近播放')
  4705. this.currentTitleCover = $r('app.media.ic_avatar2')
  4706. this.currentTitleName = '最近播放'
  4707. //加载动画效果
  4708. this.updateListData(this.historyList, true)
  4709. // this.videoLocalList = this.historyList
  4710. if (ArrayUtil.isEmpty(this.historyList)) {
  4711. ToastUtil.showToast('最近播放记录空空如也')
  4712. } else {
  4713. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  4714. }
  4715. this.isHistory = true
  4716. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4717. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  4718. this.titleBarModel.setTitleName('我的收藏')
  4719. this.currentTitleName = '我的收藏'
  4720. this.currentTitleCover = $r('app.media.ic_avatar1')
  4721. //加载动画效果
  4722. this.updateListData(this.favList)
  4723. if (ArrayUtil.isEmpty(this.favList)) {
  4724. ToastUtil.showToast('无音乐收藏记录')
  4725. } else {
  4726. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  4727. }
  4728. this.isFavMusic = true
  4729. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4730. } else {
  4731. this.currentTitleName = item.name
  4732. this.currentPath = item.filePath
  4733. this.currentTitleCover = $r('app.media.ic_avatar5')
  4734. this.getSortedFiles(this.currentPath)
  4735. }
  4736. //进入歌单的时候的滚动位置在顶部
  4737. if(this.twoFingerType==4){
  4738. setTimeout(() => {
  4739. this.waterScroller.scrollEdge(Edge.Top)
  4740. this.scroller.scrollEdge(Edge.Top)
  4741. }, 380)
  4742. }else{
  4743. if (this.isGridMusic) {
  4744. this.scroller.scrollEdge(Edge.Top)
  4745. }else{
  4746. this.listScroller.scrollEdge(Edge.Top)
  4747. }
  4748. }
  4749. break;
  4750. case CommonConstants.TYPE_IS_ARTIST:
  4751. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  4752. let offsetA = 0
  4753. if(this.twoFingerType==4){
  4754. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  4755. let cur = this.waterScroller.currentOffset()
  4756. if (cur && typeof cur.yOffset === 'number') {
  4757. offsetA = cur.yOffset
  4758. }
  4759. }
  4760. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  4761. }else
  4762. if (this.isGridMusic) {
  4763. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  4764. let cur = this.scroller.currentOffset()
  4765. if (cur && typeof cur.yOffset === 'number') {
  4766. offsetA = cur.yOffset
  4767. }
  4768. }
  4769. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  4770. } else {
  4771. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  4772. let cur = this.listScroller.currentOffset()
  4773. if (cur && typeof cur.yOffset === 'number') {
  4774. offsetA = cur.yOffset
  4775. }
  4776. }
  4777. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  4778. }
  4779. let mList = this.artistMap.get(item.name)
  4780. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  4781. Utility.doSortListAscending(mList)
  4782. this.isCanBack = true
  4783. this.titleBarModel.setTitleName(item.name)
  4784. this.currentTitleName = '艺术家:' + item.name
  4785. if (item.pixelMapPath) {
  4786. this.currentTitleCover = item.pixelMapPath
  4787. }
  4788. this.updateListData(mList)
  4789. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4790. }
  4791. //进入歌单的时候的滚动位置在顶部
  4792. if(this.twoFingerType==4){
  4793. setTimeout(() => {
  4794. this.waterScroller.scrollEdge(Edge.Top)
  4795. this.scroller.scrollEdge(Edge.Top)
  4796. }, 380)
  4797. }else{
  4798. if (this.isGridMusic) {
  4799. this.scroller.scrollEdge(Edge.Top)
  4800. }else{
  4801. this.listScroller.scrollEdge(Edge.Top)
  4802. }
  4803. }
  4804. break;
  4805. case CommonConstants.TYPE_IS_ALBUM:
  4806. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  4807. let offset = 0
  4808. if(this.twoFingerType==4){
  4809. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  4810. let cur = this.waterScroller.currentOffset()
  4811. if (cur && typeof cur.yOffset === 'number') {
  4812. offset = cur.yOffset
  4813. }
  4814. }
  4815. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  4816. }else
  4817. if (this.isGridMusic) {
  4818. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  4819. let cur = this.scroller.currentOffset()
  4820. if (cur && typeof cur.yOffset === 'number') {
  4821. offset = cur.yOffset
  4822. }
  4823. }
  4824. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  4825. } else {
  4826. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  4827. let cur = this.listScroller.currentOffset()
  4828. if (cur && typeof cur.yOffset === 'number') {
  4829. offset = cur.yOffset
  4830. }
  4831. }
  4832. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  4833. }
  4834. let albumList = this.albumMap.get(item.name)
  4835. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  4836. Utility.doSortListAscending(albumList)
  4837. this.isCanBack = true
  4838. this.titleBarModel.setTitleName(item.name)
  4839. this.currentTitleName = '专辑:' + item.name
  4840. if (item.pixelMapPath) {
  4841. this.currentTitleCover = item.pixelMapPath
  4842. }
  4843. this.updateListData(albumList)
  4844. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  4845. this.mScrollMap.set(item.name, this.selectedIndex)
  4846. }
  4847. //进入歌单的时候的滚动位置在顶部
  4848. if(this.twoFingerType==4){
  4849. setTimeout(() => {
  4850. this.waterScroller.scrollEdge(Edge.Top)
  4851. this.scroller.scrollEdge(Edge.Top)
  4852. }, 380)
  4853. }else{
  4854. if (this.isGridMusic) {
  4855. this.scroller.scrollEdge(Edge.Top)
  4856. }else{
  4857. this.listScroller.scrollEdge(Edge.Top)
  4858. }
  4859. }
  4860. break;
  4861. case CommonConstants.TYPE_IS_CSJAD:
  4862. return
  4863. break;
  4864. case CommonConstants.TYPE_LOCAL:
  4865. if(item&&item.filePath.toLowerCase().endsWith('.cue')){
  4866. const cueinfo:CueInfo = await parseCueFile(item.filePath)
  4867. const cueTracks:CueTrack[] = cueinfo.tracks
  4868. console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
  4869. if(ArrayUtil.isNotEmpty(cueTracks)){
  4870. this.showCueDialog(cueTracks,cueinfo)
  4871. }
  4872. // this.showCueSheet = !this.showCueSheet
  4873. return
  4874. }
  4875. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  4876. this.stop();
  4877. }
  4878. if (isOpen) {
  4879. this.currentSong = item
  4880. if (index !== undefined) {
  4881. this.curIndex = index
  4882. }
  4883. this.songList = []
  4884. this.songList.push(item)
  4885. this.sonDataSource.pushArrayData(this.songList)
  4886. }else if(isFromSonPlayList){ //点击来自右下角的播放列表
  4887. this.currentSong = item
  4888. if (index !== undefined) {
  4889. this.curIndex = index
  4890. }
  4891. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  4892. Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  4893. }else {
  4894. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  4895. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  4896. this.songList = globalVideoList
  4897. this.sonDataSource.pushArrayData(this.songList)
  4898. this.currentSong = globalVideoList[this.curIndex]
  4899. }
  4900. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  4901. this.videoUrl = this.currentSong.filePath
  4902. this.name = this.currentSong.name
  4903. this.cover = this.currentSong.pixelMapPath
  4904. this.artist = this.currentSong.artist
  4905. LogUtil.info('this.currentSong.duration =' + this.currentSong.duration)
  4906. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  4907. this.startPlayOrResumePlay()
  4908. break;
  4909. }
  4910. }
  4911. private cueComponentId: number = 0
  4912. //显示cue分轨列表对话框
  4913. showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
  4914. this.getUIContext().getPromptAction().openCustomDialog({
  4915. builder: () => {
  4916. this.cueComptentBuilder(cueTracks,cueinfo)
  4917. },
  4918. isModal:true,
  4919. showInSubWindow:false,
  4920. maskColor: Color.Transparent,
  4921. dialogTransition: // 设置弹窗内容显示的过渡效果
  4922. TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  4923. .animation({ duration: 600, curve: Curve.Smooth }),
  4924. maskTransition: // 设置蒙层显示的过渡效果
  4925. TransitionEffect.opacity(0.5)
  4926. .animation({ duration: 600, curve: Curve.Smooth })
  4927. }).then((dialogId: number) => {
  4928. this.cueComponentId = dialogId
  4929. })
  4930. .catch((error: BusinessError) => {
  4931. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  4932. })
  4933. }
  4934. @Builder
  4935. cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
  4936. CueComptent({
  4937. title:cueinfo.title,
  4938. cueTracks:cueTracks,
  4939. isLongNameRoLL:this.isLongNameRoLL,
  4940. onCancel:()=>{
  4941. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
  4942. },
  4943. onDoItemClick:(item: CueTrack, index: number)=>{
  4944. //获取cueinfo对应的filePath
  4945. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  4946. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
  4947. this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
  4948. console.info('onecold cueinfo.filePath=', cueinfo.filePath)
  4949. console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
  4950. if (this.currentSong){
  4951. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  4952. this.stop();//播放之前先停止之前播放。
  4953. }
  4954. this.songList = globalVideoList
  4955. this.sonDataSource.pushArrayData(this.songList)
  4956. this.videoUrl = this.currentSong.filePath
  4957. this.name = item.title||this.currentSong.name
  4958. this.cover = this.currentSong.pixelMapPath
  4959. this.artist = item.performer||this.currentSong.artist
  4960. this.currentSong.name = this.name
  4961. this.currentSong.artist = this.artist
  4962. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  4963. this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
  4964. }
  4965. }
  4966. })
  4967. }
  4968. @Builder
  4969. PlayController() {
  4970. Column() {
  4971. Line().width('100%').height(1).backgroundColor($r('app.color.index_background'))
  4972. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  4973. Row() {
  4974. if(this.isHiCar()){
  4975. this.playConRigth()
  4976. Column(){
  4977. this.centerName()
  4978. }.layoutWeight(1)
  4979. .onClick(()=>{
  4980. this.showPlayerView()
  4981. })
  4982. this.playConLeft(false)
  4983. }else{
  4984. this.playConLeft()
  4985. this.playConRigth()
  4986. }
  4987. }
  4988. .width('100%')
  4989. .height(this.bottomBarHeight)
  4990. .justifyContent(FlexAlign.Center)
  4991. .hitTestBehavior(HitTestMode.Transparent)
  4992. .backgroundColor(this.isCustomizeBg ? Color.Transparent : $r('app.color.bottom_control_background'))
  4993. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  4994. // modalTransition: ModalTransition.DEFAULT,
  4995. transition: AnimationHelper.transitionInDown(666),
  4996. backgroundColor: 'rgba(0, 0, 0, 0.9)',
  4997. })
  4998. .padding({
  4999. left: 16,
  5000. right: 16
  5001. })
  5002. Line()
  5003. .width('100%')
  5004. .height(25)
  5005. .backgroundColor($r('app.color.bottom_control_background'))// .visibility(this.isPhoneLan()?Visibility.None:this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
  5006. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  5007. }
  5008. .clickEffect({ level: ClickEffectLevel.HEAVY })
  5009. }
  5010. @State isFrontWhite: boolean = false
  5011. @Builder
  5012. centerName() {
  5013. Column() {
  5014. Text(this.currentSong?.name)
  5015. .fontSize(16)
  5016. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  5017. .maxLines(1)
  5018. .fontColor($r('app.color.text_color'))
  5019. .fontWeight(500);
  5020. Row() {
  5021. Text(this.currentSong?.artist)
  5022. .margin({ top: 2 })
  5023. .fontSize(13)
  5024. .textAlign(TextAlign.Start)
  5025. .maxLines(1)
  5026. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  5027. .fontColor($r('app.color.text_color'));
  5028. }
  5029. .visibility(this.currentSong?.artist? Visibility.Visible:Visibility.None)
  5030. }
  5031. .alignItems(HorizontalAlign.Center)
  5032. }
  5033. @Builder
  5034. playConLeft(isLeft: boolean = true) {
  5035. Row() {
  5036. RotatingCover({ songLabel: this.currentSong?.pixelMapPath });
  5037. Column() {
  5038. Text(this.currentSong?.name)
  5039. .fontSize(16)
  5040. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  5041. .maxLines(1)
  5042. .fontColor($r('app.color.text_color'))
  5043. .fontWeight(500);
  5044. Row() {
  5045. Text(this.currentSong?.artist)
  5046. .margin({ top: 2 })
  5047. .fontSize(13)
  5048. .textAlign(TextAlign.Start)
  5049. .maxLines(1)
  5050. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  5051. .fontColor($r('app.color.text_color'));
  5052. }
  5053. .visibility(this.currentSong?.artist? Visibility.Visible:Visibility.None)
  5054. }
  5055. .alignItems(isLeft?HorizontalAlign.Start:HorizontalAlign.End)
  5056. .margin({ right: isLeft?22:10 })
  5057. .visibility(isLeft? Visibility.Visible:Visibility.None)
  5058. }
  5059. .padding({ right: 18 })
  5060. .layoutWeight(isLeft?1:0)
  5061. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5062. .onClick(() => {
  5063. this.showPlayerView()
  5064. })
  5065. }
  5066. //打开播放页
  5067. showPlayerView() {
  5068. if (ArrayUtil.isNotEmpty(this.songList)) {
  5069. this.isShowPlay = true;
  5070. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  5071. this.initLyric(lyricPath);
  5072. this.startAutoHide();
  5073. } else {
  5074. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  5075. }
  5076. }
  5077. @Builder
  5078. playConRigth() {
  5079. Row() {
  5080. Image($r('app.media.hm_previous'))
  5081. .height(28)
  5082. .width(28)
  5083. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5084. .margin({ left: 8, right: 16 })
  5085. .fillColor(this.themeColor)
  5086. .displayPriority(2)
  5087. .onClick(() => {
  5088. if (ArrayUtil.isNotEmpty(this.songList)) {
  5089. this.playPrevious()
  5090. } else {
  5091. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5092. }
  5093. })
  5094. //播放进度条
  5095. Stack() {
  5096. Progress({
  5097. value: Math.floor(this.progressValue),
  5098. type: ProgressType.Ring,
  5099. })
  5100. .color(this.themeColor)// 进度条前景色为灰色
  5101. .backgroundColor($r('app.color.index_background'))
  5102. .height(40)
  5103. .aspectRatio(CommonConstants.ASPECT_RATIO)
  5104. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ? $r('app.media.hm_pause') : $r('app.media.hm_play2'))
  5105. .height(38)
  5106. .width(38)
  5107. .displayPriority(3)
  5108. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5109. .fillColor(this.themeColor)
  5110. .onClick(() => {
  5111. if (ArrayUtil.isNotEmpty(this.songList)) {
  5112. console.info('onecold playOrPause 4642')
  5113. this.playOrPause()
  5114. } else {
  5115. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5116. }
  5117. })
  5118. }
  5119. Image($r('app.media.hm_next'))
  5120. .height(28)
  5121. .width(28)
  5122. .margin({
  5123. right: 16,
  5124. left: 16
  5125. })
  5126. .fillColor(this.themeColor)
  5127. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5128. .displayPriority(2)
  5129. .onClick(() => {
  5130. if (ArrayUtil.isNotEmpty(this.songList)) {
  5131. this.playNext()
  5132. } else {
  5133. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5134. }
  5135. })
  5136. Image($r('app.media.hm_playlist'))
  5137. .height(28)
  5138. .width(28)
  5139. .displayPriority(1)
  5140. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  5141. .fillColor(this.themeColor)
  5142. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  5143. height: '95%',
  5144. dragBar: true,
  5145. showClose: true,
  5146. blurStyle: BlurStyle.Thin,
  5147. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  5148. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  5149. title: {
  5150. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  5151. + `(${this.songList.length}首)`
  5152. }
  5153. })
  5154. .onClick(() => {
  5155. if (ArrayUtil.isNotEmpty(this.songList)) {
  5156. this.isShowSheet = !this.isShowSheet;
  5157. this.isFrontWhite = false
  5158. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  5159. this.scrollIndex()
  5160. } else {
  5161. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  5162. }
  5163. })
  5164. }
  5165. }
  5166. scrollIndex(){
  5167. try {
  5168. setTimeout(() => {
  5169. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  5170. if(this.curIndex>60){
  5171. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  5172. }else{
  5173. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  5174. }
  5175. })
  5176. }, 123)
  5177. }catch (error) {
  5178. console.error(`onecold scrollIndex出错: ${error}`);
  5179. }
  5180. }
  5181. //播放列表布局
  5182. @Builder
  5183. PlayListSheet() {
  5184. Column() {
  5185. this.PlayList()
  5186. }
  5187. .width('100%')
  5188. .height('100%')
  5189. }
  5190. @State titleStr: string = ''
  5191. @State ablumStr: string = ''
  5192. @State artistStr: string = ''
  5193. @State lyricConStr: string = ''
  5194. @State currentEditItem: string = ''
  5195. @State yearStr: string = ''
  5196. @State trackStr: string = ''
  5197. @State genreStr: string = ''
  5198. @State imagePathStr: string = ''
  5199. @State albumArtistStr: string = ''
  5200. @State composerStr: string = ''
  5201. @State lyricistStr: string = ''
  5202. @State commentStr: string = ''
  5203. @State discStr: string = ''
  5204. doUpdateData() {
  5205. setTimeout(() => {
  5206. if (this.modeType === 0) {
  5207. this.deleteCache(this.currentPath)
  5208. this.getSortedFiles(this.currentPath)
  5209. }
  5210. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  5211. workerInstance.postMessage({ code: 3, data: this.context });
  5212. workerInstance.postMessage({ code: 4, data: this.context });
  5213. }, 999)
  5214. }
  5215. //编辑信息
  5216. async doEdit(item: VideoItem) {
  5217. if (!item) {
  5218. return
  5219. }
  5220. if (StrUtil.isEmpty(this.titleStr)) {
  5221. ToastUtil.showToast('标题不能为空')
  5222. return
  5223. }
  5224. //用户更改了封面,那就内嵌下封面
  5225. if(StrUtil.isNotEmpty(this.imagePathStr)){
  5226. const resultCover:boolean = await changeMusicCover(this.context,
  5227. item.filePath,this.imagePathStr,true);
  5228. this.imagePathStr = ''
  5229. if(resultCover){
  5230. ToastUtil.showToast('内嵌封面成功')
  5231. }
  5232. }
  5233. const metadata:FFMpegTags = {
  5234. title: this.titleStr,
  5235. artist: this.artistStr,
  5236. album: this.ablumStr,
  5237. TYER:this.yearStr,
  5238. genre:this.genreStr,
  5239. track:this.trackStr,
  5240. album_artist:this.albumArtistStr,
  5241. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  5242. COMPOSER:this.composerStr,
  5243. lyricist:this.lyricistStr,
  5244. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  5245. comment:this.commentStr,
  5246. disc:this.discStr,
  5247. };
  5248. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  5249. const result:boolean = await repairAudioMetadata(
  5250. item.filePath,
  5251. this.lyricConStr,
  5252. metadata,
  5253. true
  5254. );
  5255. if (result) {
  5256. this.table.updateMediaInfo(item.filePath, this.titleStr, this.artistStr, this.ablumStr,this.lyricConStr,
  5257. this.yearStr,this.genreStr,this.trackStr,this.albumArtistStr,this.composerStr, this.lyricistStr,this.commentStr,this.discStr,
  5258. (success: boolean, error?: string) => {
  5259. // this.isShowEdit = false
  5260. if (success) {
  5261. console.log(" onecold 编辑信息成功,数据库已同步");
  5262. ToastUtil.showToast('内嵌音乐标签成功')
  5263. this.isShowMoreView = false
  5264. this.name = this.titleStr
  5265. if (item.filePath == this.currentSong?.filePath) {
  5266. this.currentSong.name = this.titleStr
  5267. this.artist = this.artistStr
  5268. this.currentSong.artist = this.artistStr
  5269. this.currentSong.album = this.ablumStr
  5270. this.currentSong.year = this.yearStr
  5271. this.currentSong.genre = this.genreStr
  5272. this.currentSong.track = this.trackStr
  5273. this.currentSong.lyricContent = this.lyricConStr
  5274. this.initLyric(item.filePath)
  5275. this.currentSong.ALBUMARTIST = this.albumArtistStr
  5276. this.currentSong.COMPOSER = this.composerStr
  5277. this.currentSong.LYRICIST = this.lyricistStr
  5278. this.currentSong.COMMENT = this.commentStr
  5279. }
  5280. this.doUpdateData()
  5281. } else {
  5282. // ToastUtil.showToast('保存失败' + error?.toString())
  5283. console.error(" onecold 编辑信息数据库失败原因: " + error);
  5284. }
  5285. });
  5286. console.log(' onecold 元数据标签更新成功,');
  5287. } else {
  5288. ToastUtil.showToast('内嵌音乐标签失败')
  5289. console.log('onecold 内嵌音乐标签失败');
  5290. }
  5291. this.longItemFilePath = ''
  5292. this.tempLyricContent = ''
  5293. this.isShowEdit = false
  5294. }
  5295. updateLyricToDB() {
  5296. }
  5297. @Builder
  5298. editSheet(item: VideoItem) {
  5299. Scroll() {
  5300. Column() {
  5301. this.editDetail(item)
  5302. }
  5303. }
  5304. .width('100%')
  5305. .height('100%')
  5306. }
  5307. @Builder
  5308. editDetail(item: VideoItem) {
  5309. Column() {
  5310. if (item) {
  5311. Row() {
  5312. Stack() {
  5313. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  5314. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  5315. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  5316. item.pixelMapPath)
  5317. .fillColor(this.themeColor)
  5318. .height(88)
  5319. .width(88)
  5320. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  5321. .borderRadius(12)
  5322. .clip(true)
  5323. .opacity(this.opacityItem)// 绑定透明度
  5324. .margin({ left: 25 })
  5325. }
  5326. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  5327. .onClick(async () => {
  5328. const imagePath:string | undefined = await this.goSelectImage(item);
  5329. if (imagePath) {
  5330. //用户更改过图片
  5331. this.imagePathStr = imagePath
  5332. }
  5333. })
  5334. .width('28%')
  5335. Row() {
  5336. Column() {
  5337. Text(item.name)
  5338. .fontSize(17)
  5339. .maxLines(1)
  5340. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  5341. .animation({
  5342. duration: 555,
  5343. curve: 'Linear',
  5344. })
  5345. .fontColor(this.themeColor)
  5346. .margin({ left: 8 })
  5347. Row() {
  5348. Text(item.artist)
  5349. .fontSize(14)
  5350. .maxLines(1)
  5351. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  5352. .padding({ top: 8 })
  5353. .fontColor(this.themeColor)
  5354. .margin({ left: 8 })
  5355. }
  5356. }
  5357. .height('100%')
  5358. .width(100)
  5359. .layoutWeight(1)
  5360. .justifyContent(FlexAlign.Center)
  5361. .alignItems(HorizontalAlign.Start)
  5362. Column() {
  5363. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5364. Row(){
  5365. SymbolGlyph($r('sys.symbol.picture'))
  5366. .fontSize(18)
  5367. .fontColor([Color.White])
  5368. Text('获取封面')
  5369. .margin({ left: 4 })
  5370. .fontSize(11)
  5371. .fontColor(Color.White)
  5372. .fontWeight(480)
  5373. .textAlign(TextAlign.Center)
  5374. }
  5375. .justifyContent(FlexAlign.Center)
  5376. }
  5377. .height(38)
  5378. .width(100)
  5379. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5380. .backgroundColor(this.themeColor)
  5381. .stateEffect(true)
  5382. .margin({ right: 35 })
  5383. .onClick(async () => {
  5384. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  5385. this.showTipsDialog();
  5386. return; // Return empty string when no API is configured
  5387. }
  5388. const imagePath:string | undefined = await this.doSearchCover(item);
  5389. console.info('onecold imagePath = '+imagePath)
  5390. if (StrUtil.isNotEmpty(imagePath)) {
  5391. //用户更改过图片
  5392. this.imagePathStr = imagePath
  5393. ToastUtil.showToast('获取封面成功')
  5394. }else{
  5395. ToastUtil.showToast('获取封面失败,请重试')
  5396. }
  5397. })
  5398. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5399. Row(){
  5400. SymbolGlyph($r('sys.symbol.input_mode'))
  5401. .fontSize(18)
  5402. .fontColor([Color.White])
  5403. Text('获取歌词')
  5404. .margin({ left: 4 })
  5405. .fontSize(11)
  5406. .fontColor(Color.White)
  5407. .fontWeight(480)
  5408. .textAlign(TextAlign.Center)
  5409. }
  5410. .justifyContent(FlexAlign.Center)
  5411. }
  5412. .height(38)
  5413. .width(100)
  5414. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5415. .backgroundColor(this.themeColor)
  5416. .stateEffect(true)
  5417. .margin({ top: 9, right: 35 })
  5418. .onClick(async () => {
  5419. //判断有没有设置api
  5420. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  5421. if (StrUtil.isEmpty(apiUrl)) {
  5422. this.isLyricSetting = false
  5423. this.showTipsDialog()
  5424. return
  5425. }
  5426. let artist = item.artist
  5427. let title = item.name
  5428. if(!artist)
  5429. artist = ''
  5430. if(!title)
  5431. title = ''
  5432. let res: string | undefined = await getApiLyric(apiUrl,title, artist, false);
  5433. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  5434. this.lyricConStr = res;
  5435. ToastUtil.showToast('获取歌词成功')
  5436. }else{
  5437. ToastUtil.showToast('获取歌词失败,请重试')
  5438. }
  5439. })
  5440. }
  5441. .justifyContent(FlexAlign.Start)
  5442. }
  5443. .height('100%')
  5444. .justifyContent(FlexAlign.Start)
  5445. .layoutWeight(1)
  5446. }
  5447. .width('100%')
  5448. .height(98)
  5449. Row() {
  5450. Text('标题:')
  5451. .fontSize(14)
  5452. .fontColor($r('app.color.text_color'))
  5453. .margin({ left: 22 })
  5454. TextInput({ text: item.name })
  5455. .height(40)
  5456. .maxLines(1)
  5457. .fontSize(14)
  5458. .layoutWeight(1)
  5459. .fontColor($r('app.color.text_color'))
  5460. .margin({ right: 20, left: 10 })
  5461. .onChange((val: string) => {
  5462. this.titleStr = val
  5463. })
  5464. }
  5465. .width('100%')
  5466. .margin({ top: 10, bottom: 10 })
  5467. .justifyContent(FlexAlign.Start)
  5468. Row() {
  5469. Text('艺术家:')
  5470. .fontSize(14)
  5471. .fontColor($r('app.color.text_color'))
  5472. .margin({ left: 22 })
  5473. TextInput({ text: item.artist })
  5474. .height(40)
  5475. .maxLines(1)
  5476. .fontSize(14)
  5477. .layoutWeight(1)
  5478. .fontColor($r('app.color.text_color'))
  5479. .margin({ right: 20, left: 10 })
  5480. .onChange((val: string) => {
  5481. this.artistStr = val
  5482. })
  5483. }
  5484. .width('100%')
  5485. .margin({ top: 10, bottom: 10 })
  5486. .justifyContent(FlexAlign.Start)
  5487. Row() {
  5488. Text('专辑名:')
  5489. .fontSize(14)
  5490. .fontColor($r('app.color.text_color'))
  5491. .margin({ left: 22 })
  5492. TextInput({ text: item.album })
  5493. .height(40)
  5494. .maxLines(1)
  5495. .fontSize(14)
  5496. .layoutWeight(1)
  5497. .fontColor($r('app.color.text_color'))
  5498. .margin({ right: 20, left: 10 })
  5499. .onChange((val: string) => {
  5500. this.ablumStr = val
  5501. })
  5502. }
  5503. .width('100%')
  5504. .margin({ top: 10, bottom: 10 })
  5505. .justifyContent(FlexAlign.Start)
  5506. Row() {
  5507. Column(){
  5508. Column(){
  5509. Text('歌词:')
  5510. .fontSize(14)
  5511. .fontColor($r('app.color.text_color'))
  5512. .margin({ top:9,left: 22 })
  5513. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5514. SymbolGlyph($r('sys.symbol.trash_fill'))
  5515. .fontSize(25)
  5516. .alignSelf(ItemAlign.Center)
  5517. .margin({ left: 22,top:25})
  5518. }
  5519. .backgroundColor(Color.Transparent)
  5520. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  5521. Visibility.None:Visibility.Visible)
  5522. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5523. .onClick(()=>{
  5524. this.lyricConStr = ''
  5525. this.lyricContent = ''
  5526. this.tempLyricContent = ''
  5527. })
  5528. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5529. SymbolGlyph($r('sys.symbol.plus'))
  5530. .fontSize(25)
  5531. .alignSelf(ItemAlign.Center)
  5532. .margin({ left: 22,top:25})
  5533. }
  5534. .backgroundColor(Color.Transparent)
  5535. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5536. .onClick( ()=>{
  5537. this.callFilePickerSelectFileForLyric()
  5538. })
  5539. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5540. SymbolGlyph($r('sys.symbol.traditional_square'))
  5541. .fontSize(25)
  5542. .alignSelf(ItemAlign.Center)
  5543. .margin({ left: 22,top:25})
  5544. }
  5545. .backgroundColor(Color.Transparent)
  5546. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  5547. Visibility.None:Visibility.Visible)
  5548. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5549. .onClick( ()=>{
  5550. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  5551. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  5552. })
  5553. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5554. Image($r('app.media.jianti'))
  5555. .height(25)
  5556. .fillColor($r('app.color.text_color'))
  5557. .alignSelf(ItemAlign.Center)
  5558. .margin({ left: 22,top:25})
  5559. }
  5560. .backgroundColor(Color.Transparent)
  5561. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  5562. Visibility.None:Visibility.Visible)
  5563. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5564. .onClick( ()=>{
  5565. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  5566. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  5567. })
  5568. }
  5569. .layoutWeight(1)
  5570. }
  5571. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  5572. this.tempLyricContent })
  5573. .type(TextAreaType.NORMAL)
  5574. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  5575. .fontSize(14)
  5576. .layoutWeight(1)
  5577. .fontColor($r('app.color.text_color'))
  5578. .margin({ right: 20, left: 10 })
  5579. .onChange((val: string) => {
  5580. this.lyricConStr = val
  5581. })
  5582. }
  5583. .width('100%')
  5584. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  5585. .margin({ top: 10, bottom: 10 })
  5586. .justifyContent(FlexAlign.Start)
  5587. Row() {
  5588. Text('年份:')
  5589. .fontSize(14)
  5590. .fontColor($r('app.color.text_color'))
  5591. .margin({ left: 22 })
  5592. TextInput({ text: item.year })
  5593. .height(40)
  5594. .maxLines(1)
  5595. .fontSize(14)
  5596. .type(InputType.Number)
  5597. .layoutWeight(1)
  5598. .fontColor($r('app.color.text_color'))
  5599. .margin({ right: 20, left: 10 })
  5600. .onChange((val: string) => {
  5601. this.yearStr = val
  5602. })
  5603. }
  5604. .width('100%')
  5605. .margin({ top: 10, bottom: 10 })
  5606. .justifyContent(FlexAlign.Start)
  5607. Row() {
  5608. Text('音轨号:')
  5609. .fontSize(14)
  5610. .fontColor($r('app.color.text_color'))
  5611. .margin({ left: 22 })
  5612. TextInput({ text:item.track=='未知'?'': item.track })
  5613. .height(40)
  5614. .maxLines(1)
  5615. .fontSize(14)
  5616. .type(InputType.Number)
  5617. .layoutWeight(1)
  5618. .fontColor($r('app.color.text_color'))
  5619. .margin({ right: 20, left: 10 })
  5620. .onChange((val: string) => {
  5621. this.trackStr = val
  5622. })
  5623. }
  5624. .width('100%')
  5625. .margin({ top: 10, bottom: 10 })
  5626. .justifyContent(FlexAlign.Start)
  5627. Row() {
  5628. Text('碟号:')
  5629. .fontSize(14)
  5630. .fontColor($r('app.color.text_color'))
  5631. .margin({ left: 22 })
  5632. TextInput({ text:item.disc })
  5633. .height(40)
  5634. .maxLines(1)
  5635. .fontSize(14)
  5636. .type(InputType.Number)
  5637. .layoutWeight(1)
  5638. .fontColor($r('app.color.text_color'))
  5639. .margin({ right: 20, left: 10 })
  5640. .onChange((val: string) => {
  5641. this.discStr = val
  5642. })
  5643. }
  5644. .width('100%')
  5645. .margin({ top: 10, bottom: 10 })
  5646. .justifyContent(FlexAlign.Start)
  5647. Row() {
  5648. Text('风格:')
  5649. .fontSize(14)
  5650. .fontColor($r('app.color.text_color'))
  5651. .margin({ left: 22 })
  5652. TextInput({ text: item.genre })
  5653. .height(40)
  5654. .maxLines(1)
  5655. .fontSize(14)
  5656. .layoutWeight(1)
  5657. .fontColor($r('app.color.text_color'))
  5658. .margin({ right: 20, left: 10 })
  5659. .onChange((val: string) => {
  5660. this.genreStr = val
  5661. })
  5662. }
  5663. .width('100%')
  5664. .margin({ top: 10, bottom: 10 })
  5665. .justifyContent(FlexAlign.Start)
  5666. Row() {
  5667. Text('专辑艺术家:')
  5668. .fontSize(14)
  5669. .fontColor($r('app.color.text_color'))
  5670. .margin({ left: 22 })
  5671. TextInput({ text: item.ALBUMARTIST })
  5672. .height(40)
  5673. .maxLines(1)
  5674. .fontSize(14)
  5675. .layoutWeight(1)
  5676. .fontColor($r('app.color.text_color'))
  5677. .margin({ right: 20, left: 10 })
  5678. .onChange((val: string) => {
  5679. this.albumArtistStr = val
  5680. })
  5681. }
  5682. .width('100%')
  5683. .margin({ top: 10, bottom: 10 })
  5684. .justifyContent(FlexAlign.Start)
  5685. Row() {
  5686. Text('作曲:')
  5687. .fontSize(14)
  5688. .fontColor($r('app.color.text_color'))
  5689. .margin({ left: 22 })
  5690. TextInput({ text: item.COMPOSER })
  5691. .height(40)
  5692. .maxLines(1)
  5693. .fontSize(14)
  5694. .layoutWeight(1)
  5695. .fontColor($r('app.color.text_color'))
  5696. .margin({ right: 20, left: 10 })
  5697. .onChange((val: string) => {
  5698. this.composerStr = val
  5699. })
  5700. }
  5701. .width('100%')
  5702. .margin({ top: 10, bottom: 10 })
  5703. .justifyContent(FlexAlign.Start)
  5704. Row() {
  5705. Text('作词:')
  5706. .fontSize(14)
  5707. .fontColor($r('app.color.text_color'))
  5708. .margin({ left: 22 })
  5709. TextInput({ text: item.LYRICIST })
  5710. .height(40)
  5711. .maxLines(1)
  5712. .fontSize(14)
  5713. .layoutWeight(1)
  5714. .fontColor($r('app.color.text_color'))
  5715. .margin({ right: 20, left: 10 })
  5716. .onChange((val: string) => {
  5717. this.lyricistStr = val
  5718. })
  5719. }
  5720. .width('100%')
  5721. .margin({ top: 10, bottom: 10 })
  5722. .justifyContent(FlexAlign.Start)
  5723. Row() {
  5724. Text('注释:')
  5725. .fontSize(14)
  5726. .fontColor($r('app.color.text_color'))
  5727. .margin({ left: 22 })
  5728. TextInput({ text: item.COMMENT })
  5729. .height(40)
  5730. .maxLines(1)
  5731. .fontSize(14)
  5732. .layoutWeight(1)
  5733. .fontColor($r('app.color.text_color'))
  5734. .margin({ right: 20, left: 10 })
  5735. .onChange((val: string) => {
  5736. this.commentStr = val
  5737. })
  5738. }
  5739. .width('100%')
  5740. .margin({ top: 10, bottom: 10 })
  5741. .justifyContent(FlexAlign.Start)
  5742. Row() {
  5743. Button('保存')
  5744. .fontColor(Color.White)
  5745. .layoutWeight(1)
  5746. .height(50)
  5747. .width(100)
  5748. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5749. .backgroundColor(this.themeColor)
  5750. .stateEffect(true)
  5751. .margin({ right: 20, bottom: 20 })
  5752. .onClick(async () => {
  5753. this.doEdit(item)
  5754. })
  5755. Button('取消')
  5756. .fontColor(Color.White)
  5757. .layoutWeight(1)
  5758. .height(50)
  5759. .width(100)
  5760. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  5761. .backgroundColor(this.themeColor)
  5762. .stateEffect(true)
  5763. .margin({ left: 20, bottom: 20 })
  5764. .onClick(async () => {
  5765. if(this.isGridMusic){
  5766. this.longItemFilePath =''
  5767. }else{
  5768. this.isShowEdit = false
  5769. }
  5770. this.setEditStrEmpty()
  5771. if(this.isShowPlay){
  5772. this.isShowEdit = false
  5773. }
  5774. })
  5775. }
  5776. .margin({
  5777. left: 38,
  5778. right: 38,
  5779. top: 10,
  5780. bottom: 10
  5781. })
  5782. .width(250)
  5783. .height(60)
  5784. }
  5785. }
  5786. .margin({ bottom: 20 })
  5787. }
  5788. setEditStrEmpty(){
  5789. this.imagePathStr = ''
  5790. this.lyricConStr = ''
  5791. this.artistStr = ''
  5792. this.titleStr = ''
  5793. this.ablumStr = ''
  5794. this.genreStr = ''
  5795. this.yearStr = ''
  5796. this.trackStr = ''
  5797. this.albumArtistStr = ''
  5798. this.composerStr = ''
  5799. this.lyricistStr = ''
  5800. this.commentStr = ''
  5801. this.discStr = ''
  5802. }
  5803. @Builder
  5804. detailSheet(item:VideoItem) {
  5805. Scroll() {
  5806. Column() {
  5807. this.songDetail(item)
  5808. }
  5809. }
  5810. .width('100%')
  5811. .height('100%')
  5812. }
  5813. @Builder
  5814. songDetail(currentItem:VideoItem) {
  5815. Column() {
  5816. if (currentItem) {
  5817. Row() {
  5818. Stack() {
  5819. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.music_red') :
  5820. currentItem.pixelMapPath)
  5821. .fillColor(this.themeColor)
  5822. .height(80)
  5823. .width(80)
  5824. .borderRadius(10)
  5825. .opacity(this.opacityItem)// 绑定透明度
  5826. .margin({ left: 22 })
  5827. }
  5828. Column() {
  5829. Column() {
  5830. Text(currentItem.name)
  5831. .fontSize(16)
  5832. .maxLines(1)
  5833. .animation({
  5834. duration: 555,
  5835. curve: 'Linear',
  5836. })
  5837. .fontColor($r('app.color.text_color'))
  5838. .margin({ left: 15 })
  5839. }
  5840. .height('100%')
  5841. .width('100%')
  5842. .justifyContent(FlexAlign.Center)
  5843. .alignItems(HorizontalAlign.Start)
  5844. }
  5845. .height('100%')
  5846. }
  5847. .width('100%')
  5848. .height(90)
  5849. .justifyContent(FlexAlign.SpaceBetween)
  5850. Row() {
  5851. Text('艺术家:')
  5852. .fontSize(14)
  5853. .fontColor($r('app.color.text_color'))
  5854. .margin({ left: 22 })
  5855. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  5856. .fontSize(14)
  5857. .fontColor($r('app.color.text_color'))
  5858. .margin({ left: 10 })
  5859. .layoutWeight(1)
  5860. }
  5861. .width('100%')
  5862. .margin({ top: 10, bottom: 10 })
  5863. .justifyContent(FlexAlign.Start)
  5864. Row() {
  5865. Text('专辑名:')
  5866. .fontSize(14)
  5867. .fontColor($r('app.color.text_color'))
  5868. .margin({ left: 22 })
  5869. Text(currentItem?.album ?currentItem.album : '未知专辑')
  5870. .fontSize(14)
  5871. .margin({ left: 10 })
  5872. .fontColor($r('app.color.text_color'))
  5873. .layoutWeight(1)
  5874. }
  5875. .width('100%')
  5876. .margin({ top: 10, bottom: 10 })
  5877. .justifyContent(FlexAlign.Start)
  5878. Row() {
  5879. Text('时长:')
  5880. .fontSize(14)
  5881. .fontColor($r('app.color.text_color'))
  5882. .margin({ left: 22 })
  5883. Text(StrUtil.isEmpty(currentItem.duration)?
  5884. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  5885. .fontSize(14)
  5886. .margin({ left: 10 })
  5887. .fontColor($r('app.color.text_color'))
  5888. .layoutWeight(1)
  5889. }
  5890. .width('100%')
  5891. .margin({ top: 10, bottom: 10 })
  5892. .justifyContent(FlexAlign.Start)
  5893. Row() {
  5894. Text('采样率:')
  5895. .fontSize(14)
  5896. .fontColor($r('app.color.text_color'))
  5897. .margin({ left: 22 })
  5898. Text(Utility.convertToKHz(currentItem.sampleRate))
  5899. .fontSize(14)
  5900. .margin({ left: 10 })
  5901. .fontColor($r('app.color.text_color'))
  5902. .layoutWeight(1)
  5903. }
  5904. .width('100%')
  5905. .margin({ top: 10, bottom: 10 })
  5906. .justifyContent(FlexAlign.Start)
  5907. Row() {
  5908. Text('比特率:')
  5909. .fontSize(14)
  5910. .fontColor($r('app.color.text_color'))
  5911. .margin({ left: 22 })
  5912. Text(currentItem.bit_rate)
  5913. .fontSize(14)
  5914. .margin({ left: 10 })
  5915. .fontColor($r('app.color.text_color'))
  5916. .layoutWeight(1)
  5917. }
  5918. .width('100%')
  5919. .margin({ top: 10, bottom: 10 })
  5920. .justifyContent(FlexAlign.Start)
  5921. Row() {
  5922. Text('位深:')
  5923. .fontSize(14)
  5924. .fontColor($r('app.color.text_color'))
  5925. .margin({ left: 22 })
  5926. Text(`${currentItem.bits_per_raw_sample} bits`)
  5927. .fontSize(14)
  5928. .margin({ left: 10 })
  5929. .fontColor($r('app.color.text_color'))
  5930. .layoutWeight(1)
  5931. }
  5932. .width('100%')
  5933. .margin({ top: 10, bottom: 10 })
  5934. .justifyContent(FlexAlign.Start)
  5935. Row() {
  5936. Text('声道:')
  5937. .fontSize(14)
  5938. .fontColor($r('app.color.text_color'))
  5939. .margin({ left: 22 })
  5940. Text(`${currentItem.channels}`)
  5941. .fontSize(14)
  5942. .margin({ left: 10 })
  5943. .fontColor($r('app.color.text_color'))
  5944. .layoutWeight(1)
  5945. }
  5946. .width('100%')
  5947. .margin({ top: 10, bottom: 10 })
  5948. .justifyContent(FlexAlign.Start)
  5949. Row() {
  5950. Text('声道布局:')
  5951. .fontSize(14)
  5952. .fontColor($r('app.color.text_color'))
  5953. .margin({ left: 22 })
  5954. Text(`${currentItem.channel_layout}`)
  5955. .fontSize(14)
  5956. .margin({ left: 10 })
  5957. .fontColor($r('app.color.text_color'))
  5958. .layoutWeight(1)
  5959. }
  5960. .width('100%')
  5961. .margin({ top: 10, bottom: 10 })
  5962. .justifyContent(FlexAlign.Start)
  5963. Row() {
  5964. Text('起始播放点:')
  5965. .fontSize(14)
  5966. .fontColor($r('app.color.text_color'))
  5967. .margin({ left: 22 })
  5968. Text(`${currentItem.start_time}`)
  5969. .fontSize(14)
  5970. .margin({ left: 10 })
  5971. .fontColor($r('app.color.text_color'))
  5972. .layoutWeight(1)
  5973. }
  5974. .width('100%')
  5975. .margin({ top: 10, bottom: 10 })
  5976. .justifyContent(FlexAlign.Start)
  5977. Row() {
  5978. Text('风格:')
  5979. .fontSize(14)
  5980. .fontColor($r('app.color.text_color'))
  5981. .margin({ left: 22 })
  5982. Text(currentItem.genre)
  5983. .fontSize(14)
  5984. .margin({ left: 10 })
  5985. .fontColor($r('app.color.text_color'))
  5986. .layoutWeight(1)
  5987. }
  5988. .width('100%')
  5989. .margin({ top: 10, bottom: 10 })
  5990. .justifyContent(FlexAlign.Start)
  5991. Row() {
  5992. Text('发行时间:')
  5993. .fontSize(14)
  5994. .fontColor($r('app.color.text_color'))
  5995. .margin({ left: 22 })
  5996. Text(currentItem.year)
  5997. .fontSize(14)
  5998. .margin({ left: 10 })
  5999. .fontColor($r('app.color.text_color'))
  6000. .layoutWeight(1)
  6001. }
  6002. .width('100%')
  6003. .margin({ top: 10, bottom: 10 })
  6004. .justifyContent(FlexAlign.Start)
  6005. Row() {
  6006. Text('质量评分:')
  6007. .fontSize(14)
  6008. .fontColor($r('app.color.text_color'))
  6009. .margin({ left: 22 })
  6010. Text(currentItem.probe_score+"")
  6011. .fontSize(14)
  6012. .margin({ left: 10 })
  6013. .fontColor($r('app.color.text_color'))
  6014. .layoutWeight(1)
  6015. }
  6016. .width('100%')
  6017. .margin({ top: 10, bottom: 10 })
  6018. .justifyContent(FlexAlign.Start)
  6019. Row() {
  6020. Text('音轨号:')
  6021. .fontSize(14)
  6022. .fontColor($r('app.color.text_color'))
  6023. .margin({ left: 22 })
  6024. Text(currentItem.track)
  6025. .fontSize(14)
  6026. .margin({ left: 10 })
  6027. .fontColor($r('app.color.text_color'))
  6028. .layoutWeight(1)
  6029. }
  6030. .width('100%')
  6031. .margin({ top: 10, bottom: 10 })
  6032. .justifyContent(FlexAlign.Start)
  6033. Row() {
  6034. Text('碟号:')
  6035. .fontSize(14)
  6036. .fontColor($r('app.color.text_color'))
  6037. .margin({ left: 22 })
  6038. Text(currentItem.disc)
  6039. .fontSize(14)
  6040. .margin({ left: 10 })
  6041. .fontColor($r('app.color.text_color'))
  6042. .layoutWeight(1)
  6043. }
  6044. .width('100%')
  6045. .margin({ top: 10, bottom: 10 })
  6046. .justifyContent(FlexAlign.Start)
  6047. Row() {
  6048. Text('专辑艺术家:')
  6049. .fontSize(14)
  6050. .fontColor($r('app.color.text_color'))
  6051. .margin({ left: 22 })
  6052. Text(currentItem.ALBUMARTIST)
  6053. .fontSize(14)
  6054. .margin({ left: 10 })
  6055. .fontColor($r('app.color.text_color'))
  6056. .layoutWeight(1)
  6057. }
  6058. .width('100%')
  6059. .margin({ top: 10, bottom: 10 })
  6060. .justifyContent(FlexAlign.Start)
  6061. Row() {
  6062. Text('作曲家:')
  6063. .fontSize(14)
  6064. .fontColor($r('app.color.text_color'))
  6065. .margin({ left: 22 })
  6066. Text(currentItem.COMPOSER)
  6067. .fontSize(14)
  6068. .margin({ left: 10 })
  6069. .fontColor($r('app.color.text_color'))
  6070. .layoutWeight(1)
  6071. }
  6072. .width('100%')
  6073. .margin({ top: 10, bottom: 10 })
  6074. .justifyContent(FlexAlign.Start)
  6075. Row() {
  6076. Text('作词家:')
  6077. .fontSize(14)
  6078. .fontColor($r('app.color.text_color'))
  6079. .margin({ left: 22 })
  6080. Text(currentItem.LYRICIST)
  6081. .fontSize(14)
  6082. .margin({ left: 10 })
  6083. .fontColor($r('app.color.text_color'))
  6084. .layoutWeight(1)
  6085. }
  6086. .width('100%')
  6087. .margin({ top: 10, bottom: 10 })
  6088. .justifyContent(FlexAlign.Start)
  6089. Row() {
  6090. Text('注释:')
  6091. .fontSize(14)
  6092. .fontColor($r('app.color.text_color'))
  6093. .margin({ left: 22 })
  6094. Text(currentItem.COMMENT)
  6095. .fontSize(14)
  6096. .margin({ left: 10 })
  6097. .fontColor($r('app.color.text_color'))
  6098. .layoutWeight(1)
  6099. }
  6100. .width('100%')
  6101. .margin({ top: 10, bottom: 10 })
  6102. .justifyContent(FlexAlign.Start)
  6103. Row() {
  6104. Text('格式:')
  6105. .fontSize(14)
  6106. .fontColor($r('app.color.text_color'))
  6107. .margin({ left: 22 })
  6108. Text(Utility.formatMimeType(currentItem.mimeType))
  6109. .fontSize(14)
  6110. .margin({ left: 10 })
  6111. .fontColor($r('app.color.text_color'))
  6112. .layoutWeight(1)
  6113. }
  6114. .width('100%')
  6115. .margin({ top: 10, bottom: 10 })
  6116. .justifyContent(FlexAlign.Start)
  6117. Row() {
  6118. Text('播放次数:')
  6119. .fontSize(14)
  6120. .fontColor($r('app.color.text_color'))
  6121. .margin({ left: 22 })
  6122. Text(currentItem.playCount?.toString())
  6123. .fontSize(14)
  6124. .margin({ left: 10 })
  6125. .fontColor($r('app.color.text_color'))
  6126. .layoutWeight(1)
  6127. }
  6128. .width('100%')
  6129. .margin({ top: 10, bottom: 10 })
  6130. .justifyContent(FlexAlign.Start)
  6131. Row() {
  6132. Text('流数量:')
  6133. .fontSize(14)
  6134. .fontColor($r('app.color.text_color'))
  6135. .margin({ left: 22 })
  6136. Text(currentItem.nb_streams?.toString())
  6137. .fontSize(14)
  6138. .margin({ left: 10 })
  6139. .fontColor($r('app.color.text_color'))
  6140. .layoutWeight(1)
  6141. }
  6142. .width('100%')
  6143. .margin({ top: 10, bottom: 10 })
  6144. .justifyContent(FlexAlign.Start)
  6145. Row() {
  6146. Text('文件大小:')
  6147. .fontSize(14)
  6148. .fontColor($r('app.color.text_color'))
  6149. .margin({ left: 22 })
  6150. Text(currentItem.size)
  6151. .fontSize(14)
  6152. .margin({ left: 10 })
  6153. .fontColor($r('app.color.text_color'))
  6154. .layoutWeight(1)
  6155. }
  6156. .width('100%')
  6157. .margin({ top: 10, bottom: 10 })
  6158. .justifyContent(FlexAlign.Start)
  6159. Row() {
  6160. Text('文件名:')
  6161. .fontSize(14)
  6162. .fontColor($r('app.color.text_color'))
  6163. .margin({ left: 22 })
  6164. Text(currentItem.fileName)
  6165. .fontSize(14)
  6166. .margin({ left: 10 })
  6167. .fontColor($r('app.color.text_color'))
  6168. .layoutWeight(1)
  6169. }
  6170. .width('100%')
  6171. .margin({ top: 10, bottom: 10 })
  6172. .justifyContent(FlexAlign.Start)
  6173. Row() {
  6174. Text('修改时间:')
  6175. .fontSize(14)
  6176. .fontColor($r('app.color.text_color'))
  6177. .margin({ left: 22 })
  6178. Text(currentItem.cTime)
  6179. .fontSize(14)
  6180. .margin({ left: 10 })
  6181. .fontColor($r('app.color.text_color'))
  6182. .layoutWeight(1)
  6183. }
  6184. .width('100%')
  6185. .margin({ top: 10, bottom: 10 })
  6186. .justifyContent(FlexAlign.Start)
  6187. Row() {
  6188. Text('存放目录:')
  6189. .fontSize(14)
  6190. .fontColor($r('app.color.text_color'))
  6191. .margin({ left: 22 })
  6192. Text(currentItem.filePath)
  6193. .fontSize(12)
  6194. .margin({ left: 10 })
  6195. .fontColor($r('app.color.text_color'))
  6196. .layoutWeight(1)
  6197. }
  6198. .margin({ top: 10, bottom: 10 })
  6199. .width('100%')
  6200. .justifyContent(FlexAlign.Start)
  6201. Row() {
  6202. Text('内嵌歌词:')
  6203. .fontSize(14)
  6204. .fontColor($r('app.color.text_color'))
  6205. .margin({ left: 22 })
  6206. Text(currentItem.lyricContent)
  6207. .fontSize(12)
  6208. .copyOption(CopyOptions.InApp)
  6209. .margin({ left: 10 })
  6210. .fontColor($r('app.color.text_color'))
  6211. .layoutWeight(1)
  6212. }
  6213. .margin({ top: 10, bottom: 10 })
  6214. .width('100%')
  6215. .justifyContent(FlexAlign.Start)
  6216. }
  6217. }
  6218. .margin({ bottom: 20 })
  6219. }
  6220. //定时关闭布局
  6221. @Builder
  6222. TimeCloseSheet() {
  6223. Scroll() {
  6224. Column() {
  6225. this.TimeClose()
  6226. }
  6227. }
  6228. .width('100%')
  6229. .height('100%')
  6230. }
  6231. //倒计时关闭音乐,退出App功能实现。
  6232. @State selectedMinutes: number = 0 // 0表示未开启
  6233. @State remainingSeconds: number = 0
  6234. // 预设时间选项
  6235. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  6236. private formatTime(seconds: number): string {
  6237. const mins = Math.floor(seconds / 60)
  6238. const secs = seconds % 60
  6239. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  6240. }
  6241. // 开始倒计时
  6242. private handleTimeSelect(minutes: number) {
  6243. if (minutes === this.selectedMinutes) {
  6244. this.stopCountdown();
  6245. this.selectedMinutes = 0;
  6246. return;
  6247. }
  6248. this.selectedMinutes = minutes;
  6249. this.remainingSeconds = minutes * 60;
  6250. this.startCountdown(); // 新增调用
  6251. }
  6252. @Builder
  6253. TimeClose() {
  6254. Column() {
  6255. // 倒计时显示区域
  6256. Text(this.selectedMinutes > 0 ?
  6257. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  6258. "定时关闭未开启")
  6259. .fontSize(17)
  6260. .fontColor($r('app.color.text_color'))
  6261. .margin({ top: 2, bottom: 8 });
  6262. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  6263. ForEach(this.presetTimes, (minutes: number, index: number) => {
  6264. // 单行时间选项容器
  6265. Row() {
  6266. // 文字描述区域
  6267. Text(this.getDisplayText(minutes))
  6268. .fontSize(15)
  6269. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  6270. $r('app.color.text_color'))// 选中态颜色变化
  6271. .textAlign(TextAlign.Start)
  6272. .layoutWeight(1); // 占据剩余空间
  6273. // 复选框样式的选择器
  6274. Row() {
  6275. if (minutes === this.selectedMinutes) {
  6276. // 选中状态 - 带勾号的圆形复选框
  6277. Row() {
  6278. // 使用系统内置的勾号图标
  6279. Image($r('sys.media.ohos_ic_public_ok'))
  6280. .width(14)
  6281. .height(14)
  6282. .fillColor(Color.White)
  6283. }
  6284. .width(24)
  6285. .height(24)
  6286. .borderRadius(12)
  6287. .backgroundColor(this.themeColor)
  6288. .justifyContent(FlexAlign.Center)
  6289. .alignItems(VerticalAlign.Center)
  6290. } else {
  6291. // 未选中状态的圆形边框
  6292. Row()
  6293. .width(24)
  6294. .height(24)
  6295. .borderRadius(12)
  6296. .border({
  6297. width: 2,
  6298. color: $r('app.color.text_color'),
  6299. style: BorderStyle.Solid
  6300. })
  6301. .backgroundColor(Color.Transparent)
  6302. }
  6303. }
  6304. .width(24)
  6305. .height(24)
  6306. .margin({ left: 20 })
  6307. .justifyContent(FlexAlign.Center)
  6308. .alignItems(VerticalAlign.Center)
  6309. }
  6310. .width('100%')
  6311. .padding({
  6312. top: 18,
  6313. bottom: 18,
  6314. left: 18,
  6315. right: 18
  6316. })
  6317. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  6318. $r('app.color.bottom_control_background')) // 选中背景高亮
  6319. .borderRadius(12)
  6320. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  6321. .margin({ bottom: 18 })
  6322. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  6323. });
  6324. }
  6325. .width('100%')
  6326. .padding(16)
  6327. }
  6328. }
  6329. // 获取显示文本
  6330. private getDisplayText(minutes: number): string {
  6331. if (minutes === -1) {
  6332. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  6333. }
  6334. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  6335. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  6336. }
  6337. // 处理选择事件
  6338. private handleSelect(minutes: number): void {
  6339. if (minutes === -1) { // 自定义
  6340. // 弹出自定义时间对话框
  6341. DialogHelper.showTextInputDialog({
  6342. title: '自定义时间',
  6343. maskColor: Color.Transparent,
  6344. inputType: InputType.Number,
  6345. text: '',
  6346. onChange: (text) => {
  6347. console.error("onChange: " + text);
  6348. },
  6349. onAction: (action, dialogId, content) => {
  6350. if (action == DialogAction.TWO) {
  6351. const customMinutes = Number(content);
  6352. if (customMinutes > 0) {
  6353. this.handleTimeSelect(customMinutes); // 设置自定义时间
  6354. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  6355. }
  6356. }
  6357. }
  6358. });
  6359. } else {
  6360. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  6361. }
  6362. }
  6363. // 添加定时器引用
  6364. private timerId: number = -1;
  6365. // 启动/重置倒计时
  6366. private startCountdown() {
  6367. // 清除旧定时器
  6368. if (this.timerId !== -1) {
  6369. clearInterval(this.timerId);
  6370. }
  6371. // 创建新定时器
  6372. if (this.selectedMinutes > 0) {
  6373. this.timerId = setInterval(() => {
  6374. if (this.remainingSeconds === 15) {
  6375. this.showConfirmationDialog();
  6376. }
  6377. if (this.remainingSeconds > 0) {
  6378. this.remainingSeconds -= 1;
  6379. } else {
  6380. this.stopCountdown();
  6381. this.handleTimeout();
  6382. }
  6383. }, 1000);
  6384. }
  6385. }
  6386. // 15倒计时后再次提示显示确认是否关闭App对话框
  6387. private showConfirmationDialog() {
  6388. DialogHelper.showAlertDialog({
  6389. backgroundColor: $r('app.color.btn_green'),
  6390. title: '确认关闭',
  6391. maskColor: Color.Transparent,
  6392. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  6393. borderStyle: BorderStyle.Dashed,
  6394. primaryButton: '暂不关闭',
  6395. secondaryButton: '确定',
  6396. onAction: (action) => {
  6397. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  6398. this.stopCountdown();
  6399. this.selectedMinutes = 0
  6400. } else if (action == DialogAction.TWO) {
  6401. }
  6402. }
  6403. })
  6404. }
  6405. // 停止倒计时
  6406. private stopCountdown() {
  6407. if (this.timerId !== -1) {
  6408. clearInterval(this.timerId);
  6409. this.timerId = -1;
  6410. }
  6411. }
  6412. // 超时处理
  6413. private handleTimeout() {
  6414. // 执行播放器关闭逻辑
  6415. this.selectedMinutes = 0;
  6416. ToastUtil.showToast(" 定时关闭已完成");
  6417. this.stop(); // 假设存在的播放器实例
  6418. //退出APP
  6419. const mContext = getContext(this) as common.UIAbilityContext
  6420. mContext.terminateSelf();
  6421. AvSessionController.getInstance(true).unregisterSessionListener()
  6422. }
  6423. //倒计时关闭音乐,退出App功能实现结束。
  6424. //播放列表的拖动List 重新排序
  6425. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  6426. //左滑操作 移动文件 重命名 删除等操作
  6427. @Builder
  6428. sonButton(item: VideoItem, index: number, filePath: string) {
  6429. Row() {
  6430. //加入下一首播放
  6431. Button() {
  6432. Image($r('app.media.next_to_play'))
  6433. .fillColor(Color.White)
  6434. .width(20)
  6435. }
  6436. .width(40)
  6437. .height(40)
  6438. .type(ButtonType.Circle)
  6439. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  6440. .backgroundColor(this.themeColor)
  6441. .margin(5)
  6442. .onClick(() => {
  6443. this.addToNextPlay(item);
  6444. })
  6445. Button() {
  6446. Image($r('app.media.close'))
  6447. .fillColor(Color.White)
  6448. .width(20)
  6449. }
  6450. .width(40)
  6451. .height(40)
  6452. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  6453. .type(ButtonType.Circle)
  6454. .backgroundColor(this.themeColor)
  6455. .margin(5)
  6456. .onClick(() => {
  6457. this.songList.splice(Number(index), 1)
  6458. this.sonDataSource.pushArrayData(this.songList)
  6459. })
  6460. Button() {
  6461. Image($r('app.media.share2'))
  6462. .fillColor(Color.White)
  6463. .width(20)
  6464. }
  6465. .width(40)
  6466. .height(40)
  6467. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  6468. .type(ButtonType.Circle)
  6469. .backgroundColor(this.themeColor)
  6470. .margin(5)
  6471. .onClick(() => {
  6472. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  6473. })
  6474. }
  6475. }
  6476. itemMoveSon(index: number, newIndex: number): void {
  6477. if (newIndex < 0 || newIndex >= this.songList.length) {
  6478. return;
  6479. }
  6480. let tmp = this.songList.splice(index, 1);
  6481. this.songList.splice(newIndex, 0, tmp[0]);
  6482. this.sonDataSource.pushArrayData(this.songList)
  6483. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  6484. }
  6485. @Builder
  6486. PlayList() {
  6487. List({ scroller: this.playListScroller }) {
  6488. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  6489. ListItem() {
  6490. this.MusicItemSon(item, index)
  6491. }
  6492. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  6493. .animation({
  6494. duration: 666,
  6495. curve: 'ease-in-out' // 可选动画曲线
  6496. })
  6497. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
  6498. TransitionEffect.scale({ x: 0, y: 0 })))
  6499. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  6500. //拖动List关键代码开始
  6501. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  6502. .zIndex(this.dragItem === index ? 1 : 0)
  6503. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  6504. .gesture(
  6505. GestureGroup(GestureMode.Sequence,
  6506. LongPressGesture({ repeat: true })
  6507. .onAction((event?: GestureEvent) => {
  6508. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  6509. this.scaleItem = index
  6510. })
  6511. })
  6512. .onActionEnd(() => {
  6513. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  6514. this.scaleItem = -1
  6515. })
  6516. }),
  6517. PanGesture({ fingers: 1, direction: null, distance: 0 })
  6518. .onActionStart(() => {
  6519. this.dragItem = index // 记录当前拖动项索引
  6520. this.dragRefOffset = 0 // 重置偏移基准
  6521. })
  6522. .onActionUpdate((event: GestureEvent) => {
  6523. this.offsetY = event.offsetY - this.dragRefOffset;
  6524. this.neighborItem = -1;
  6525. let indexA = this.songList.indexOf(item);
  6526. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  6527. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  6528. let value: number = 0;
  6529. if (this.offsetY < 0) {
  6530. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  6531. this.neighborItem = indexA - 1;
  6532. this.neighborScale = 1 - value / 20;
  6533. } else if (this.offsetY > 0) {
  6534. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  6535. this.neighborItem = indexA + 1;
  6536. this.neighborScale = 1 - value / 20;
  6537. }
  6538. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  6539. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6540. this.offsetY -= this.ITEM_INTV;
  6541. this.dragRefOffset += this.ITEM_INTV;
  6542. this.itemMoveSon(indexA, indexA + 1);
  6543. });
  6544. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  6545. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6546. this.offsetY += this.ITEM_INTV;
  6547. this.dragRefOffset -= this.ITEM_INTV;
  6548. this.itemMoveSon(indexA, indexA - 1);
  6549. });
  6550. }
  6551. })
  6552. .onActionEnd((event: GestureEvent) => {
  6553. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6554. this.dragItem = -1
  6555. this.neighborItem = -1
  6556. })
  6557. animateTo({
  6558. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  6559. }, () => {
  6560. this.scaleItem = -1
  6561. })
  6562. })
  6563. )
  6564. .onCancel(() => {
  6565. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  6566. this.dragItem = -1
  6567. this.neighborItem = -1
  6568. })
  6569. animateTo({
  6570. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  6571. }, () => {
  6572. this.scaleItem = -1
  6573. })
  6574. })
  6575. ) //拖动List关键代码结束
  6576. .onClick(() => {
  6577. this.doPlay(item, index, true)
  6578. })
  6579. }, (item: VideoItem) => item.filePath)
  6580. }
  6581. .width('100%')
  6582. .height('100%')
  6583. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  6584. // .animation({ duration: 500, curve: Curve.Ease }))
  6585. .cachedCount(10)
  6586. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  6587. .gesture(PinchGesture({ fingers: 2 })
  6588. .onActionEnd((event: GestureEvent) => {
  6589. this.setSonListTwoFingers()
  6590. })
  6591. .onActionUpdate(e => {
  6592. this.scaleValue = this.pinchValue * e.scale
  6593. })
  6594. .onActionStart(e => {
  6595. }))
  6596. .padding({
  6597. bottom: 0
  6598. })
  6599. }
  6600. setSonListTwoFingers() {
  6601. this.pinchValue = this.scaleValue;
  6602. Logger.info('this.pinchValue = ' + this.pinchValue);
  6603. if (this.pinchValue >= 1) {
  6604. this.sonTwoFingerType++
  6605. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  6606. if (this.sonTwoFingerType > 3) {
  6607. this.sonTwoFingerType = 1
  6608. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6609. }
  6610. } else {
  6611. this.sonTwoFingerType--
  6612. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  6613. if (this.sonTwoFingerType < 1) {
  6614. this.sonTwoFingerType = 1
  6615. }
  6616. }
  6617. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  6618. this.pinchValue = 1;
  6619. this.scaleValue = 1;
  6620. }
  6621. @State sonTwoFingerType:number = 3
  6622. @Builder
  6623. private MusicItemSon(item: VideoItem, index?: number) {
  6624. Button({ type: ButtonType.Normal, stateEffect: true }) {
  6625. Row() {
  6626. Stack() {
  6627. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  6628. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  6629. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  6630. .alt($r('app.media.music_red'))
  6631. .fillColor(this.themeColor)
  6632. .borderRadius('100%')
  6633. .clip(true)
  6634. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  6635. .draggable(false)// 禁止长按手势拖动
  6636. .autoResize(true) // 重采样,可减少内存占用
  6637. .margin({ left: 20 })
  6638. }
  6639. .width('15%')
  6640. Column() {
  6641. Column() {
  6642. Text(this.isShowFileName?item.fileName :item.name)
  6643. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  6644. .fontColor(this.curIndex === index ? this.themeColor :
  6645. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  6646. .maxLines(1)
  6647. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  6648. Row() {
  6649. Column(){
  6650. Text(item.md5Str?.includes('Lossless')?
  6651. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  6652. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  6653. .padding({ top: 3,right:6,left:6,bottom:3 })
  6654. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6655. $r('app.color.text_color'))
  6656. .fontWeight(500)
  6657. .borderRadius(12)
  6658. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  6659. .backgroundColor('#FFC107')
  6660. }
  6661. .padding({ top: 8 })
  6662. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  6663. item.artist + ' ' + item?.duration)
  6664. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  6665. .padding({ top: 8 })
  6666. .maxLines(1)
  6667. .fontColor(this.curIndex === index ? this.themeColor :
  6668. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  6669. .margin({ left: this.sonTwoFingerType == 3 ? 5 : 3 })
  6670. Blank()
  6671. Text(item.size)
  6672. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  6673. .padding({ top: 8 })
  6674. .maxLines(1)
  6675. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  6676. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  6677. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  6678. .margin({ left: 10 })
  6679. }
  6680. }
  6681. .height('100%')
  6682. .width('100%')
  6683. .justifyContent(FlexAlign.Center)
  6684. .alignItems(HorizontalAlign.Start)
  6685. }
  6686. .height('100%')
  6687. .width('65%')
  6688. Column() {
  6689. ImageAnimator()
  6690. .images(this.imagesF)// 动画数组
  6691. .duration(1000)// 持续
  6692. .state(this.animationState)// 动画状态
  6693. .fillMode(FillMode.Forwards)
  6694. .width(18)
  6695. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  6696. Visibility.None)
  6697. .height(18)
  6698. .iterations(-1) // 播放次数
  6699. }
  6700. .width('20%')
  6701. }
  6702. }
  6703. .backgroundColor(Color.Transparent)
  6704. .width('100%')
  6705. .reuseId('son_item')
  6706. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  6707. .shadow(this.scaleItem === index ? {
  6708. radius: 70,
  6709. color: '#15000000',
  6710. offsetX: 0,
  6711. offsetY: 0
  6712. } :
  6713. {
  6714. radius: 0,
  6715. color: '#15000000',
  6716. offsetX: 0,
  6717. offsetY: 0
  6718. })
  6719. .animation({ curve: Curve.Sharp, duration: 300 })
  6720. }
  6721. @Builder
  6722. MusicPlayBuilder() {
  6723. Column() {
  6724. this.IjkMusicPlayerView()
  6725. }
  6726. .height('100%')
  6727. .width('100%')
  6728. .onDisAppear(() => {
  6729. this.translateY = 0;
  6730. })
  6731. .translate({ y: this.translateY })
  6732. .gesture(
  6733. PanGesture(this.panOption)
  6734. .onActionUpdate((event?: GestureEvent) => {
  6735. if (event) {
  6736. // 只允许向下滑动,向上滑动时限制为0
  6737. this.translateY = Math.max(0, event.offsetY);
  6738. }
  6739. })
  6740. .onActionEnd((event?: GestureEvent) => {
  6741. // 使用更低的阈值和滑动速度判断
  6742. const minDistance = 100; // 最小滑动距离 100vp
  6743. const minVelocity = 500; // 最小滑动速度
  6744. // 获取滑动速度(如果可用)
  6745. const velocity = event?.velocityY || 0;
  6746. // 判断是否应该关闭:距离足够 或者 速度足够快
  6747. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  6748. if (shouldClose) {
  6749. // 添加关闭动画
  6750. this.getUIContext().animateTo({
  6751. duration: 300,
  6752. curve: Curve.Smooth
  6753. }, () => {
  6754. this.isShowPlay = false;
  6755. this.translateY = 0;
  6756. })
  6757. } else {
  6758. // 回弹动画
  6759. this.getUIContext().animateTo({
  6760. duration: 300,
  6761. curve: Curve.Smooth
  6762. }, () => {
  6763. this.translateY = 0;
  6764. })
  6765. }
  6766. })
  6767. )
  6768. }
  6769. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  6770. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  6771. HeightBreakpoint.HEIGHT_LG;
  6772. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  6773. @State topBarHeight: number = 50
  6774. @State barOpacity: number = 1
  6775. @State barBottomOpacity: number = 1
  6776. private hideDone: boolean = false;
  6777. @State currentYOffset: number = 0;
  6778. @State bottomBarHeight: number = 60;
  6779. private isHiding: boolean = false;
  6780. //是否是Pura X外屏,或者小屏幕
  6781. isPuraWP() {
  6782. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  6783. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  6784. }
  6785. //是否是Pura X外屏,或者小屏幕,手机横屏
  6786. /**
  6787. * 是否是Pura X外屏,或者小屏幕,手机横屏
  6788. * @returns
  6789. */
  6790. isCoverOpacity() {
  6791. if (this.isPuraWP()) {
  6792. return true
  6793. }
  6794. if (this.isPhoneLan()) {
  6795. return true
  6796. }
  6797. if (deviceInfo.marketName.includes('Pura X')
  6798. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  6799. return true
  6800. }
  6801. return false
  6802. }
  6803. //是不是手机横屏
  6804. isPhoneLan() {
  6805. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  6806. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  6807. LogUtil.info('hicar isPhoneLan width= ' + this.windowWidth);
  6808. LogUtil.info('hicar isPhoneLan height= ' + this.windowHeight);
  6809. LogUtil.info(`twocold hicarWindow size: ${this.windowWidth}x${this.windowHeight}, this.isHiCarStatus: ${this.isHiCarStatus}`);
  6810. LogUtil.info(`twocold hicar Window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall: ${this.isHiCarSmall()}`);
  6811. if (this.isHiCarKuanBianPing()) {
  6812. return true
  6813. }
  6814. if (this.isHiCar()) {
  6815. return false
  6816. }
  6817. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  6818. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  6819. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  6820. return true
  6821. }
  6822. return false
  6823. }
  6824. //是不是1920x720的hicar的屏幕分辨率
  6825. isHiCarKuanBianPing(){
  6826. if(!this.isHiCar()){
  6827. return false
  6828. }
  6829. const hiCarAspectRatios: HiCarAspectRatio[] = [
  6830. { ratio: 1920 / 720, name: "1920x720" },
  6831. ];
  6832. const currentRatio: number = this.windowWidth / this.windowHeight;
  6833. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  6834. LogUtil.info('twocold isHiCarKuanBianPing currentRatio = ' + currentRatio)
  6835. for (const hiCarRatio of hiCarAspectRatios) {
  6836. LogUtil.info('twocold isHiCarKuanBianPing hiCarRatio= ' + hiCarRatio.ratio)
  6837. LogUtil.info('twocold isHiCarKuanBianPing Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  6838. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  6839. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  6840. //宽扁平的尺寸设置列表展示
  6841. this.twoFingerType ==3
  6842. this.isGridMusic = false
  6843. return true;
  6844. }
  6845. }
  6846. return false;
  6847. }
  6848. //是不是hicar的屏幕分辨率
  6849. isHiCarSmall() {
  6850. if(!this.isHiCar()){
  6851. return false
  6852. }
  6853. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  6854. {
  6855. this.columns = 6
  6856. return false
  6857. }
  6858. const hiCarAspectRatios: HiCarAspectRatio[] = [
  6859. { ratio: 800 / 480, name: "800x480" },
  6860. { ratio: 1280 / 720, name: "1280x720" },
  6861. { ratio: 1920 / 1080, name: "1920x1080" },
  6862. ];
  6863. const currentRatio: number = this.windowWidth / this.windowHeight;
  6864. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  6865. LogUtil.info('twocold isHiCarSmall currentRatio = ' + currentRatio)
  6866. for (const hiCarRatio of hiCarAspectRatios) {
  6867. LogUtil.info('twocold isHiCarSmall hiCarRatio= ' + hiCarRatio.ratio)
  6868. LogUtil.info('twocold isHiCarSmall Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  6869. LogUtil.info('twocold isHiCarSmall isHiCarStatus= ' + this.isHiCarStatus);
  6870. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  6871. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  6872. //宽扁平的尺寸设置列表展示
  6873. return true;
  6874. }
  6875. }
  6876. return false;
  6877. }
  6878. isHiCar() {
  6879. return this.isHiCarStatus&&this.curDisplayIsHiCar;
  6880. }
  6881. //是不是正常的手机竖屏
  6882. isPhonePortrait() {
  6883. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  6884. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  6885. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  6886. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  6887. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  6888. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  6889. return true
  6890. }
  6891. return false
  6892. }
  6893. @State showSpeedDialog: boolean = false
  6894. @State longPressSpeed: number = 3 //长按默认倍数
  6895. @Builder
  6896. SpeedDialog() {
  6897. Stack() {
  6898. Column() {
  6899. Text('已切换至' + this.longPressSpeed + '倍速播放')
  6900. .fontColor(Color.White)
  6901. .visibility(Visibility.Hidden)
  6902. }
  6903. .backgroundColor(Color.Black)
  6904. .borderRadius(20)
  6905. .padding({
  6906. top: 10,
  6907. right: 20,
  6908. left: 15,
  6909. bottom: 20
  6910. })
  6911. .opacity(0.6)
  6912. Text('已切换至' + this.longPressSpeed + '倍速播放')
  6913. .fontColor(Color.White)
  6914. }
  6915. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  6916. .zIndex(5)
  6917. .margin({ top: 80 })
  6918. }
  6919. @Builder
  6920. IjkMusicPlayerView() {
  6921. Column() {
  6922. Column() {
  6923. Column() {
  6924. //播放标题
  6925. Column() {
  6926. this.PlayTitle()
  6927. }
  6928. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  6929. .width('100%')
  6930. .margin({ top: 0 })
  6931. .height(PlayConstants.HEIGHT)
  6932. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  6933. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  6934. if (this.showSpeedDialog) {
  6935. this.SpeedDialog()
  6936. }
  6937. Stack() {
  6938. //手势拖动快进
  6939. Column()
  6940. .width(CommonConstants.FULL_PERCENT)
  6941. .height('100%')
  6942. .gesture(
  6943. GestureGroup(GestureMode.Parallel,
  6944. // 长按屏幕倍数播放
  6945. LongPressGesture({ repeat: true })
  6946. .onAction(() => {
  6947. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  6948. this.showSpeedDialog = true;
  6949. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  6950. }
  6951. })
  6952. .onActionEnd(() => {
  6953. this.showSpeedDialog = false;
  6954. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  6955. }),
  6956. //双击屏幕暂停或者播放
  6957. TapGesture({ count: 2 })
  6958. .onAction((event: GestureEvent) => {
  6959. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  6960. ToastUtil.showToast('已暂停')
  6961. }
  6962. console.info('onecold playOrPause 6693')
  6963. this.playOrPause()
  6964. })
  6965. )
  6966. )
  6967. }
  6968. .height('65%')
  6969. Swiper() {
  6970. this.CoverInfo()
  6971. this.PlayerLyrics()
  6972. }
  6973. .onChange((index: number) => {
  6974. this.currentSwiperIndex = index
  6975. })
  6976. .indicator(false)
  6977. // .indicator(this.currentBreakpoint === BreakpointTypeEnum.SM ?
  6978. // new DotIndicator()
  6979. // .top(this.isCoverOpacity()?0:10)
  6980. //
  6981. // .selectedColor($r('app.color.select_swiper'))
  6982. // .color($r('app.color.slider_track')):false
  6983. // )
  6984. .displayCount(new BreakpointType({
  6985. sm: 1,
  6986. md: 2,
  6987. lg: 2,
  6988. xl: 2,
  6989. xxl: 2
  6990. }).getValue(this.currentBreakpoint))
  6991. .clip(false)
  6992. .loop(false)
  6993. .autoPlay(false)
  6994. // .interval(8000)
  6995. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  6996. .height('100%')
  6997. .hitTestBehavior(HitTestMode.Transparent)
  6998. Image($r('app.media.icon_replay'))
  6999. .objectFit(ImageFit.Auto)
  7000. .width('120px')
  7001. .height('120px')
  7002. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  7003. .border({ width: 0 })
  7004. .visibility(Visibility.None)
  7005. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  7006. .onClick(() => {
  7007. console.info('onecold startPlayOrResumePlay 6744')
  7008. this.startPlayOrResumePlay();
  7009. })
  7010. }
  7011. .width(CommonConstants.FULL_PERCENT)
  7012. .height(CommonConstants.FULL_PERCENT)
  7013. .justifyContent(FlexAlign.End)
  7014. }
  7015. .justifyContent(FlexAlign.End)
  7016. .margin({ bottom: 8 })
  7017. }
  7018. .backgroundImage(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  7019. // .backgroundImage(this.isPuraWP() && this.currentSwiperIndex === 0 ?
  7020. // (StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover) : this.imageLabelBg)
  7021. .backgroundImageSize(this.isPuraWP() ? { width: '100%' } : { height: '150%', width: '100%' })
  7022. // .backgroundImagePosition(Alignment.Center)
  7023. .animation({
  7024. duration: 666,
  7025. curve: 'ease-in-out' // 可选动画曲线
  7026. })
  7027. .backgroundBlurStyle(this.isPuraWP() && this.currentSwiperIndex === 0 ? BlurStyle.NONE :
  7028. BlurStyle.BACKGROUND_ULTRA_THICK)
  7029. .hitTestBehavior(HitTestMode.Transparent)
  7030. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  7031. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  7032. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  7033. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  7034. .onClick(() => {
  7035. // this.startAutoHide()
  7036. if(this.isHiCar())
  7037. return
  7038. if(this.is_auto_hide_progress){
  7039. this.is_auto_hide_progress = false
  7040. }
  7041. this.startAutoHide()
  7042. })
  7043. }
  7044. @State progressValue: number = 0;
  7045. @State currentTime: string = "00:00";
  7046. @State totalTime: string = "00:00";
  7047. @State loadingVisible: Visibility = Visibility.None;
  7048. @State replayVisible: Visibility = Visibility.None;
  7049. @State slideEnable: boolean = false;
  7050. @State aspRatio: number = 0.5;
  7051. @State mContext: object | undefined = undefined;
  7052. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  7053. @State mFirst: boolean = true;
  7054. @State mDestroyPage: boolean = false;
  7055. @State playSpeed: number = 1;
  7056. @State oldSeconds: number = 0;
  7057. @State isSeekTo: boolean = false;
  7058. @State isCurrentTime: boolean = false;
  7059. @State videoWidth: string = '100%';
  7060. @State videoHeight: string = '100%';
  7061. @State initAspectRatio: number = 1;
  7062. @State videoAspectRatio: number = this.initAspectRatio;
  7063. private videoUrl: string = '';
  7064. private last: number = 0;
  7065. @State videoParentAspectRatio: number = this.initAspectRatio;
  7066. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  7067. @State CONTROL_PlayStatus: number = PlayStatus.INIT;
  7068. @State PROGRESS_MAX_VALUE: number = 100;
  7069. @State updateProgressTimer: number = 0;
  7070. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  7071. @State name: string = '';
  7072. // @State loop: boolean = false;
  7073. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  7074. @State multiple: string = '1.0X';
  7075. xcomponentController: XComponentController = new XComponentController()
  7076. private panOptionBright: PanGestureOptions =
  7077. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  7078. private panOptionVolume: PanGestureOptions =
  7079. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  7080. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  7081. //手势的音量控制和亮度控制
  7082. private positionX: number = PlayConstants.POSITION_X;
  7083. private positionY: number = PlayConstants.POSITION_Y;
  7084. private windowClass: window.Window = globalThis.windowClass
  7085. @State volume: number = 0.5;
  7086. @State volumeSmall: boolean = false
  7087. @State autoParseMusicName: boolean = true
  7088. @State isShowFileName: boolean = false
  7089. @State isLongNameRoLL: boolean = true//长歌名滚动
  7090. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  7091. @State bright: number = PlayConstants.BRIGHT;
  7092. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  7093. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  7094. @State screenWidth: number = 0
  7095. @State screenHeight: number = 0
  7096. @State statusBarHeight: number = 0
  7097. @State isYesFull: boolean = false
  7098. private seekValue: number = 0
  7099. @State isVideoLock: boolean = false; // Whether the video playback is locked
  7100. eventHub = getContext().eventHub;
  7101. //投播组件
  7102. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  7103. private castController: avSession.AVCastController | undefined = undefined;
  7104. @State isCastPlaying: boolean = false;
  7105. @State currentTime2: number = 0;
  7106. @State currentStringTime: string = '00:00';
  7107. @State duration: number = 0;
  7108. @State isReady: boolean = false;
  7109. @State durationTime: number = 0;
  7110. @State durationStringTime: string = '00:00';
  7111. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  7112. // @State isPlaying: boolean = false;
  7113. private castSeek: boolean = false;
  7114. private castItem: avSession.AVQueueItem | undefined = undefined;
  7115. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  7116. @State imageLabel: PixelMap | Resource = CommonConstants.musicBgList[0];
  7117. @State imageLabelBg: PixelMap | Resource = CommonConstants.musicBgList[0];
  7118. @State rotateAngle2: number = -9
  7119. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  7120. @State cover: string | undefined = '';
  7121. @State artist: string | undefined = ''
  7122. // 1.初始化controller
  7123. private lyricController: LyricController = new LyricController()
  7124. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  7125. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  7126. private parser = new LyricParser()
  7127. @State randomColor: string = 'rgb(0,0,0)'
  7128. @State randomShakenX: number = 0
  7129. @State randomShakenY: number = 0
  7130. @State lyricTextSize: number = 24
  7131. @State lyricContent: string = ''
  7132. @State isDebug: boolean = false
  7133. @State isHightLightCenter: boolean = true
  7134. /**
  7135. * 初始化歌词加载与展示逻辑
  7136. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  7137. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  7138. * @param isApi2 是否使用API2获取歌词(可选)
  7139. *
  7140. * 主要流程:
  7141. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  7142. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  7143. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  7144. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  7145. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  7146. * 6. 解析失败或读取失败时,清空歌词显示。
  7147. *
  7148. * 注意事项:
  7149. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  7150. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  7151. * - 歌词内容解析后通过lyricController驱动UI渲染。
  7152. */
  7153. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  7154. if (StrUtil.isEmpty(lyricPath)) {
  7155. return
  7156. }
  7157. this.initPipLyricSetting()
  7158. this.lyricControllerSingle
  7159. .setTextSize(15)
  7160. .setCacheSize(4)
  7161. .setTextColor("#FFFFFF")
  7162. .setHighlightColor("#FFFFFF")
  7163. .setHighlightScale(1.2)
  7164. .setEmptyHint("")
  7165. .setAlignMode('center')
  7166. .setAnimationDuration(500)
  7167. .setSingleLine(true)
  7168. this.lyricContent = ''
  7169. this.lyricController
  7170. .setTextSize(this.currentLyricSize)
  7171. .setCacheSize(4)
  7172. .setTextColor("#DDDDDD")
  7173. .setHighlightColor("#FFFFFF")
  7174. .setEmptyHint("")
  7175. .setAnimationDuration(1000)
  7176. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  7177. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  7178. this.setBlurDegree(this.blurDegree, false)
  7179. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  7180. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  7181. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  7182. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  7183. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  7184. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  7185. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  7186. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  7187. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  7188. this.lyricController.setTextWeight(this.lyricTextWeight)
  7189. this.showSingleLyric = false
  7190. this.timeOffset = 0
  7191. this.lyricController.setLyric(null)
  7192. this.lyricControllerSingle.setLyric(null)
  7193. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  7194. console.log("onecold lyricPath =" + lyricPath)
  7195. let neiqianLrc = ''
  7196. let lyContent = this.currentSong?.lyricContent
  7197. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  7198. neiqianLrc = lyContent
  7199. }
  7200. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast&&!isLocal&&!isLocal) {
  7201. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  7202. //赋值给this.lyricContent,播控中心才可以显示歌词
  7203. this.lyricContent = neiqianLrc
  7204. // 将文件内容按行分割成字符串数组
  7205. let lines = neiqianLrc.split('\n').map(line => line.trim());
  7206. // 3.解析歌词
  7207. let lyric = this.parser.parse(lines);
  7208. // 4.设置歌词
  7209. this.lyricController.setLyric(lyric);
  7210. this.lyricControllerXF.setLyric(lyric)
  7211. this.lyricControllerSingle.setLyric(lyric)
  7212. return
  7213. }
  7214. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  7215. && !Utility.isVideoByExtension(this.videoUrl))) {
  7216. if (this.currentSong !== undefined) {
  7217. // ToastUtil.showShort('正在为你搜索在线歌词!')
  7218. //判断是不是赞助会员,是会员的话才开启歌词功能
  7219. // if (!this.isDebug) {
  7220. // if (!Utility.isNoble()) {
  7221. // LogUtil.debug("onecold 不是赞助会员")
  7222. // return
  7223. // }
  7224. // if(!Utility.isPassInstallTime(33)){
  7225. // LogUtil.debug("onecold not pass time")
  7226. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  7227. // return
  7228. // }
  7229. // }
  7230. let artist = this.currentSong?.artist
  7231. if (artist === undefined) {
  7232. artist = ''
  7233. }
  7234. if (isApi2 === undefined) {
  7235. isApi2 = false
  7236. }
  7237. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  7238. // LogUtil.debug("onecold res =" + res)
  7239. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  7240. if (StrUtil.isNotEmpty(res)) {
  7241. this.lyricContent = res
  7242. let lines = res.split('\n').map(line => line.trim());
  7243. // 3.解析歌词
  7244. let lyric = this.parser.parse(lines);
  7245. // 4.设置歌词
  7246. this.lyricController.setLyric(lyric);
  7247. this.lyricControllerXF.setLyric(lyric)
  7248. this.lyricControllerSingle.setLyric(lyric)
  7249. this.showSingleLyric = true
  7250. // 4.保存歌词文件lyric到本地
  7251. //2025年8月28日歌词不再加密下载
  7252. this.saveDataToFile(res, lyricPath, false)
  7253. } else {
  7254. this.lyricController.setLyric(null)
  7255. this.lyricControllerXF.setLyric(null)
  7256. this.lyricControllerSingle.setLyric(null)
  7257. if (isOnLineAndToast) {
  7258. ToastUtil.showShort('未获取到歌词!')
  7259. }
  7260. }
  7261. } else {
  7262. this.lyricController.setLyric(null)
  7263. this.lyricControllerXF.setLyric(null)
  7264. this.lyricControllerSingle.setLyric(null)
  7265. if (isOnLineAndToast) {
  7266. ToastUtil.showShort('未获取到歌词!')
  7267. }
  7268. }
  7269. })
  7270. } else {
  7271. this.lyricController.setLyric(null)
  7272. this.lyricControllerXF.setLyric(null)
  7273. this.lyricControllerSingle.setLyric(null)
  7274. if (isOnLineAndToast) {
  7275. ToastUtil.showShort('未获取到歌词!')
  7276. }
  7277. }
  7278. return
  7279. }
  7280. try {
  7281. let isJiaMi = false;
  7282. let realLyricPath = lyricPath
  7283. if (FileUtil.accessSync(jiaMilyricPath)) {
  7284. isJiaMi = true
  7285. realLyricPath = jiaMilyricPath
  7286. console.info("onecold 找到加密本地歌词 ");
  7287. } else {
  7288. isJiaMi = false
  7289. realLyricPath = lyricPath
  7290. console.info("onecold 找到本地歌词 ");
  7291. }
  7292. // 3.读取文件内容并指定编码为 UTF-8
  7293. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  7294. const stat = await fileIo.stat(file.fd);
  7295. const arrayBuffer = new ArrayBuffer(stat.size);
  7296. fs.read(file.fd, arrayBuffer)
  7297. .then((readLen: number) => {
  7298. console.info("read file data succeed");
  7299. // let buf = buffer.from(arrayBuffer, 0, readLen);
  7300. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  7301. // 检查 buf 是否为空
  7302. if (buf.length === 0) {
  7303. throw new Error("Buffer is empty after reading the file");
  7304. }
  7305. try {
  7306. // 检测文件编码
  7307. // let detectedEncoding = chardet.detect(buf);
  7308. // console.info("onecoldT Detected encoding: " + detectedEncoding);
  7309. let detectedEncoding = this.detect(arrayBuffer)
  7310. console.info("onecoldT Detected encoding: " + detectedEncoding);
  7311. // 使用检测到的编码解码,解决中文乱码问题
  7312. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  7313. console.info("onecoldT Detected textDecoder: " + textDecoder);
  7314. let fileContent = textDecoder.decode(buf);
  7315. console.info(`onecoldT The content of file1: ${fileContent}`);
  7316. //解密
  7317. if (isJiaMi) {
  7318. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  7319. }
  7320. console.info(`onecold The content of file2: ${fileContent}`);
  7321. this.lyricContent = fileContent
  7322. if(isLocal){//编辑标签选择本地歌词需要赋值给this.lyricConStr
  7323. this.lyricConStr = fileContent
  7324. }
  7325. // 将文件内容按行分割成字符串数组
  7326. let lines = fileContent.split('\n').map(line => line.trim());
  7327. console.info(`onecold The content of file: ${fileContent}`);
  7328. // 3.解析歌词
  7329. let lyric = this.parser.parse(lines);
  7330. // 4.设置歌词
  7331. this.lyricController.setLyric(lyric);
  7332. this.lyricControllerXF.setLyric(lyric)
  7333. this.lyricControllerSingle.setLyric(lyric)
  7334. this.showSingleLyric = true
  7335. console.info(`The content of file: ${fileContent}`);
  7336. } catch (chardetError) {
  7337. console.error("chardet.detect failed with error: " + chardetError.message);
  7338. this.lyricController.setLyric(null);
  7339. this.lyricControllerXF.setLyric(null)
  7340. this.lyricControllerSingle.setLyric(null)
  7341. }
  7342. })
  7343. .catch((err: BusinessError) => {
  7344. this.lyricController.setLyric(null)
  7345. this.lyricControllerXF.setLyric(null)
  7346. this.lyricControllerSingle.setLyric(null)
  7347. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  7348. })
  7349. .catch((err: Error) => {
  7350. this.lyricController.setLyric(null)
  7351. this.lyricControllerXF.setLyric(null)
  7352. this.lyricControllerSingle.setLyric(null)
  7353. console.error("read file 2 data failed with error message: " + err.message);
  7354. })
  7355. .finally(() => {
  7356. fs.closeSync(file);
  7357. });
  7358. } catch (error) {
  7359. this.lyricController.setLyric(null)
  7360. this.lyricControllerSingle.setLyric(null)
  7361. this.lyricControllerXF.setLyric(null)
  7362. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  7363. }
  7364. }
  7365. detect(data: ArrayBuffer): string {
  7366. //创建检测对象
  7367. let detector: UniversalDetector = new UniversalDetector();
  7368. // 传入检测数据并实时判断编码格式
  7369. detector.handleData(data, 0, data.byteLength);
  7370. // 标记检测数据 读取结束
  7371. detector.dataEnd();
  7372. // 获取检测结果
  7373. let detected: string = detector.getDetectedCharset();
  7374. // 释放资源
  7375. detector.reset();
  7376. return detected;
  7377. }
  7378. //初始化悬浮歌词的自定义设置
  7379. initPipLyricSetting() {
  7380. this.lyricControllerXF
  7381. .setTextSize(this.currentLyricSize)
  7382. .setCacheSize(4)
  7383. .setTextColor("#DDDDDD")
  7384. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  7385. .setEmptyHint("")
  7386. .setAnimationDuration(1000)
  7387. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  7388. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  7389. this.setBlurDegree(this.blurDegreePip, true)
  7390. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  7391. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  7392. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  7393. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  7394. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  7395. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  7396. this.lyricControllerXF.setHightLightCenter(true)
  7397. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  7398. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  7399. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  7400. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  7401. if (this.pipBgIndex === 0) {
  7402. if (this.cover) {
  7403. this.pipBg = this.cover
  7404. } else {
  7405. this.pipBg = this.imageColor
  7406. }
  7407. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  7408. }
  7409. }
  7410. //根据item返回歌词内容
  7411. async getLyricContent(item: VideoItem): Promise<string> {
  7412. let neiqianLrc = ''
  7413. let lyContent = item?.lyricContent
  7414. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  7415. neiqianLrc = lyContent
  7416. return neiqianLrc
  7417. }
  7418. try {
  7419. //取数据库里面的歌词lyContent
  7420. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  7421. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  7422. console.log("onecold Lyrics:", lyricContent);
  7423. neiqianLrc = lyricContent
  7424. return neiqianLrc
  7425. }
  7426. } catch (error) {
  7427. console.error("Error fetching lyrics:", error);
  7428. }
  7429. try {
  7430. let filePath = item.filePath;
  7431. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  7432. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  7433. let isJiaMi = false;
  7434. let realLyricPath = lyricPath;
  7435. if (FileUtil.accessSync(jiaMilyricPath)) {
  7436. isJiaMi = true;
  7437. realLyricPath = jiaMilyricPath;
  7438. console.info("onecold 找到加密本地歌词");
  7439. } else {
  7440. console.info("onecold 找到本地歌词");
  7441. }
  7442. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  7443. const stat = await fileIo.stat(file.fd);
  7444. const arrayBuffer = new ArrayBuffer(stat.size);
  7445. const readLen = await fs.read(file.fd, arrayBuffer);
  7446. console.info("read file data succeed");
  7447. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  7448. if (buf.length === 0) {
  7449. throw new Error("Buffer is empty after reading the file");
  7450. }
  7451. // let detectedEncoding = chardet.detect(buf);
  7452. let detectedEncoding = this.detect(arrayBuffer)
  7453. console.info("Detected encoding: " + detectedEncoding);
  7454. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  7455. let fileContent = textDecoder.decode(buf);
  7456. console.info(`onecold The content of file1: ${fileContent}`);
  7457. if (isJiaMi) {
  7458. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  7459. }
  7460. console.info(`onecold The content of file2: ${fileContent}`);
  7461. fs.closeSync(file);
  7462. return fileContent;
  7463. } catch (error) {
  7464. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  7465. return '';
  7466. }
  7467. }
  7468. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  7469. if (StrUtil.isEmpty(filePath)) {
  7470. return
  7471. }
  7472. try {
  7473. //将content进行加密
  7474. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  7475. let lyricContent = ''
  7476. if (isJiaMi) {
  7477. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  7478. } else {
  7479. lyricContent = content
  7480. }
  7481. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  7482. // 清空文件内容
  7483. await fileIo.truncate(file.fd, 0);
  7484. await fileIo.write(file.fd, lyricContent);
  7485. await fileIo.close(file);
  7486. console.log('onecold lyric file Data saved successfully.');
  7487. } catch (error) {
  7488. console.error('onecold lyric file Failed to save data:', error);
  7489. }
  7490. }
  7491. /**
  7492. * Get largest proportion color of an image.
  7493. */
  7494. getImageColor() {
  7495. if (!this.context) {
  7496. return;
  7497. }
  7498. let bg = Utility.getMusisBg()
  7499. this.imageLabel = bg
  7500. ColorConversion.setSysBarLightBackground(true);
  7501. this.context.resourceManager.getMediaContent(bg)
  7502. .then((value: Uint8Array) => {
  7503. let buffer = value.buffer as ArrayBuffer;
  7504. image.createImageSource(buffer).createPixelMap().then((pixelMap) => {
  7505. effectKit.createColorPicker(pixelMap, (error, colorPicker) => {
  7506. if (error) {
  7507. Logger.error('Failed to create color picker.');
  7508. } else {
  7509. let color = colorPicker.getLargestProportionColor();
  7510. let colorArr = ColorConversion.dealColor(color.red, color.green, color.blue);
  7511. this.imageColor = `rgba(${colorArr[0]}, ${colorArr[1]}, ${colorArr[2]}, 1)`;
  7512. }
  7513. })
  7514. let headFilter = effectKit.createEffect(pixelMap);
  7515. if (headFilter !== null) {
  7516. headFilter.blur(15);
  7517. headFilter.getEffectPixelMap().then((value) => {
  7518. this.imageLabelBg = value;
  7519. })
  7520. }
  7521. })
  7522. .catch((error: BusinessError) => {
  7523. Logger.error(`${error.code} + ${error.message}`)
  7524. })
  7525. })
  7526. .catch((error: BusinessError) => {
  7527. Logger.error(`${error.code} + ${error.message}`)
  7528. })
  7529. }
  7530. setImageColor(cover: string) {
  7531. if (!this.context) {
  7532. return;
  7533. }
  7534. if (cover === undefined) {
  7535. return;
  7536. }
  7537. imagePathToPixelMap(cover).then((value) => {
  7538. let headFilter = effectKit.createEffect(value);
  7539. if (headFilter !== null) {
  7540. headFilter.blur(15);
  7541. headFilter.getEffectPixelMap().then((value) => {
  7542. this.imageLabelBg = value;
  7543. })
  7544. }
  7545. }).catch((error: BusinessError) => {
  7546. Logger.error(`${error.code} + ${error.message}`)
  7547. })
  7548. }
  7549. setImageColor2(cover: string) {
  7550. if (!this.context) {
  7551. return;
  7552. }
  7553. if (cover === undefined) {
  7554. return;
  7555. }
  7556. LogUtils.getInstance().LOGI("setImageColor2--> cover ==" + cover);
  7557. ImageUtils.getImageDealData(getContext(this), cover, this.videoUrl).then((data) => {
  7558. this.imageColor = data.imageColor;
  7559. if (data.blurPixelMap) {
  7560. this.imageLabelBg = data.blurPixelMap;
  7561. }
  7562. })
  7563. }
  7564. // 定义开始旋转的方法
  7565. // 定时器用于一百毫秒执行一次旋转角度
  7566. @State timer: number = 0
  7567. @State rotateAngle: number = 0
  7568. //封面旋转动画
  7569. animationRoFun() {
  7570. if (this.isPlaying && !this.isCoverRectangle) {
  7571. this.timer = setInterval(() => {
  7572. this.rotateAngle += 1
  7573. }, 100)
  7574. this.startRotation()
  7575. } else {
  7576. clearInterval(this.timer)
  7577. this.stopRotation()
  7578. }
  7579. }
  7580. // 定义开始旋转的方法
  7581. startRotation() {
  7582. if (this.isPlaying) {
  7583. animateTo({
  7584. duration: 777,
  7585. iterations: 1,
  7586. curve: Curve.Linear
  7587. }, () => {
  7588. this.rotateAngle2 = -9
  7589. })
  7590. }
  7591. }
  7592. // 回调,暂停和播放按钮回调,下一首和上一首
  7593. playChange() {
  7594. // if(this.isCoverRectangle){
  7595. // return
  7596. // }
  7597. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  7598. this.setIsPlaying(true)
  7599. this.animationState = AnimationStatus.Running
  7600. } else {
  7601. this.setIsPlaying(false)
  7602. this.animationState = AnimationStatus.Paused
  7603. }
  7604. }
  7605. // 定义停止旋转的方法
  7606. stopRotation() {
  7607. if (this.isCoverRectangle) {
  7608. this.rotateAngle = 0
  7609. } else {
  7610. //唱针以左上角为点选择逆时针40度
  7611. animateTo({
  7612. duration: 1000,
  7613. curve: Curve.Linear,
  7614. iterations: 1,
  7615. }, () => {
  7616. this.rotateAngle2 = -45;
  7617. });
  7618. }
  7619. }
  7620. @Builder
  7621. private LyricsTopItem() {
  7622. Row() {
  7623. Stack() {
  7624. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  7625. .height(62)
  7626. .width(62)
  7627. .alt(this.imageLabel)
  7628. .borderRadius(8)
  7629. .clickEffect({ level: ClickEffectLevel.HEAVY })
  7630. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  7631. .shadow({
  7632. radius: 22,
  7633. type: ShadowType.BLUR,
  7634. color: 'on_primary'
  7635. })
  7636. }
  7637. .width('18%')
  7638. Column() {
  7639. Column() {
  7640. Text(this.name)
  7641. .fontSize(16)
  7642. .maxLines(1)
  7643. .fontWeight(FontWeight.Bolder)
  7644. .fontColor(this.currentLyricColor)
  7645. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  7646. Row() {
  7647. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  7648. .fontSize(13)
  7649. .fontWeight(FontWeight.Bold)
  7650. .padding({ top: 8 })
  7651. .fontColor(this.currentLyricColor)
  7652. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  7653. Blank()
  7654. }
  7655. }
  7656. .height('100%')
  7657. .width('100%')
  7658. .justifyContent(FlexAlign.Center)
  7659. .alignItems(HorizontalAlign.Start)
  7660. }
  7661. .height('100%')
  7662. .width('65%')
  7663. Column() {
  7664. Image($r('app.media.lyric'))
  7665. .width(28)
  7666. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7667. .margin({ right: 30 })
  7668. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7669. .onClick(() => {
  7670. this.isLyricSetting = !this.isLyricSetting;
  7671. })
  7672. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  7673. height: '95%',
  7674. dragBar: true,
  7675. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  7676. showClose: true,
  7677. blurStyle: BlurStyle.Thin,
  7678. backgroundColor: Color.Transparent,
  7679. // title: { title: $r('app.string.lyric_setting') }
  7680. })
  7681. }
  7682. .width('18%')
  7683. }
  7684. .width('82%')
  7685. .height(58)
  7686. .justifyContent(FlexAlign.SpaceBetween)
  7687. }
  7688. //歌词显示
  7689. @Builder
  7690. PlayerLyrics() {
  7691. Column() {
  7692. Column() {
  7693. this.LyricsTopItem()
  7694. }
  7695. .height(this.isPuraWP() ? 15 : 58)
  7696. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  7697. Visibility.None : Visibility.Visible)
  7698. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  7699. .width("100%")
  7700. Column() {
  7701. LyricView2({
  7702. controller: this.lyricController,
  7703. enableSeek: true,
  7704. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  7705. seekLineColor: "#80ffffff", // 滑动定位线颜色
  7706. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  7707. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  7708. if (!this.isPlaying) {
  7709. console.info('onecold startPlayOrResumePlay 7527')
  7710. this.startPlayOrResumePlay()
  7711. }
  7712. else {
  7713. this.isSeekTo = true;
  7714. this.mDestroyPage = false;
  7715. this.showLoadIng();
  7716. this.seekTo(position + "");
  7717. this.isSeekTo = false;
  7718. }
  7719. return true
  7720. }
  7721. })
  7722. .width("100%")
  7723. .layoutWeight(1)
  7724. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  7725. if (this.isPhoneLan()) {
  7726. Column() {
  7727. this.playProgressView()
  7728. // this.playCenterView()
  7729. }
  7730. .margin({ bottom: 30, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  7731. }
  7732. }
  7733. .position({
  7734. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  7735. (this.isPuraWP() ? 58 : 99)
  7736. })
  7737. .justifyContent(FlexAlign.Center)
  7738. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  7739. }
  7740. }
  7741. @Builder
  7742. SingleLyricView() {
  7743. Column() {
  7744. Column() {
  7745. LyricView2({
  7746. controller: this.lyricControllerSingle,
  7747. enableSeek: false,
  7748. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  7749. seekLineColor: "#80ffffff", // 滑动定位线颜色
  7750. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  7751. })
  7752. }
  7753. .height(66)
  7754. .margin({ bottom: 20 })
  7755. }
  7756. }
  7757. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  7758. @Builder
  7759. BottomControl() {
  7760. Column() {
  7761. this.TopPlayProgressView()
  7762. //播放 暂停,下一首,上一首
  7763. this.playCenterView()
  7764. //播放进度条
  7765. this.BottomView()
  7766. }
  7767. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  7768. }
  7769. //播放控制上一首 下一首 暂停和播放
  7770. @Builder
  7771. playCenterView(){
  7772. Row() {
  7773. Row({ space: 20 }) {
  7774. Button({type:ButtonType.Circle,stateEffect:true}){
  7775. //更多功能
  7776. Image($r('app.media.menu'))
  7777. .width(24)
  7778. .clickEffect({level:ClickEffectLevel.MIDDLE})
  7779. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  7780. height: this.isCoverOpacity() ? '95%' : '93%',
  7781. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  7782. dragBar: true,
  7783. showClose: true,
  7784. blurStyle: BlurStyle.Thin,
  7785. backgroundColor: Color.Transparent,
  7786. })
  7787. }
  7788. .margin({ left: 5 })
  7789. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  7790. .backgroundColor(Color.Transparent)
  7791. .onClick(() => {
  7792. this.isShowMoreView = !this.isShowMoreView;
  7793. })
  7794. Button({type:ButtonType.Circle,stateEffect:true}){
  7795. Image($r('app.media.ic_previous'))
  7796. .width(33)
  7797. .clickEffect({level:ClickEffectLevel.HEAVY})
  7798. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7799. }
  7800. .onClick(async () => {
  7801. this.playPrevious()
  7802. })
  7803. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  7804. .backgroundColor(Color.Transparent)
  7805. .margin({ left: 5 })
  7806. }
  7807. Button({type:ButtonType.Circle,stateEffect:true}){
  7808. Column() {
  7809. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  7810. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  7811. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  7812. .width(this.isPhoneLan()?45:55)
  7813. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  7814. .fillColor(Color.White)
  7815. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7816. .onClick(async () => {
  7817. console.info('onecold playOrPause 7651')
  7818. this.playOrPause()
  7819. })
  7820. }
  7821. }
  7822. .backgroundColor(Color.Transparent)
  7823. .layoutWeight(1)
  7824. // .margin({ left: 38, right: 38 })
  7825. Row({ space: 20 }) {
  7826. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7827. Image($r('app.media.ic_next'))
  7828. .width(33)
  7829. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  7830. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7831. .onClick(() => {
  7832. this.playNext();
  7833. })
  7834. }
  7835. .backgroundColor(Color.Transparent)
  7836. .margin({ right: 5 })
  7837. .width(33)
  7838. if(this.isPhoneLan()){
  7839. this.fullButton()
  7840. }else{
  7841. Button({type:ButtonType.Circle,stateEffect:true}){
  7842. //添加或取消收藏
  7843. SymbolGlyph(Utility.getIsFav(this.favList,this.currentSong)?
  7844. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'))
  7845. .fontSize(23)
  7846. .fontColor([Color.White])
  7847. .alignSelf(ItemAlign.Center)
  7848. // .width(24)
  7849. .clickEffect({level:ClickEffectLevel.MIDDLE})
  7850. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7851. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  7852. .onClick(async () => {
  7853. if(this.currentSong){
  7854. this.doFav(this.currentSong)
  7855. }
  7856. })
  7857. }
  7858. .backgroundColor(Color.Transparent)
  7859. .width(24)
  7860. }
  7861. }
  7862. // .margin({ left: 5 })
  7863. }
  7864. .width('95%')
  7865. .margin({ bottom:this.isCoverOpacity()?0:20 })
  7866. .justifyContent(FlexAlign.SpaceEvenly)
  7867. }
  7868. @Builder
  7869. TopPlayProgressView(){
  7870. Row() {
  7871. Column(){
  7872. Row(){
  7873. Stack(){
  7874. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  7875. .fontColor([Color.White])
  7876. .fontSize(21)
  7877. .effectStrategy(1)
  7878. Text(this.fastForwardSeconds)
  7879. .fontColor(Color.White)
  7880. .fontSize(10)
  7881. .fontWeight(FontWeight.Bold)
  7882. }
  7883. .margin({left:12,bottom:6})
  7884. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  7885. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7886. .onClick(()=>{
  7887. this.backForward()
  7888. })
  7889. Slider({
  7890. value: this.progressValue,
  7891. min: 0,
  7892. max: this.PROGRESS_MAX_VALUE,
  7893. step: 1,
  7894. style: SliderStyle.InSet
  7895. })
  7896. .height(20)
  7897. .blockColor('rgba(255,255,255,1)')
  7898. .trackColor('rgba(255,255,255,0.3)')
  7899. .selectedColor(Color.White)
  7900. .trackThickness(4)
  7901. .layoutWeight(1)
  7902. .showSteps(false)
  7903. .showTips(true)
  7904. .alignSelf(ItemAlign.Center)
  7905. .enabled(this.slideEnable)
  7906. .onChange((value: number, mode: SliderChangeMode) => {
  7907. // if (mode == 2) {
  7908. this.isSeekTo = true;
  7909. this.mDestroyPage = false;
  7910. this.showLoadIng();
  7911. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  7912. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  7913. this.seekTo(seekValue + "");
  7914. // this.setProgress()
  7915. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  7916. this.isSeekTo = false;
  7917. // }
  7918. })
  7919. Stack(){
  7920. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  7921. .fontColor([Color.White])
  7922. .fontSize(21)
  7923. .effectStrategy(1)
  7924. Text(this.fastForwardSeconds)
  7925. .fontColor(Color.White)
  7926. .fontSize(10)
  7927. .fontWeight(FontWeight.Bold)
  7928. }
  7929. .margin({right:10,bottom:6})
  7930. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  7931. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7932. .onClick(()=>{
  7933. this.fastForward()
  7934. })
  7935. }
  7936. .padding({ right: 7,left:22 })
  7937. Row(){
  7938. Text(this.currentTime)
  7939. .fontSize(10)
  7940. .fontColor(Color.White)
  7941. Blank()
  7942. .layoutWeight(1)
  7943. Text(this.totalTime)
  7944. .fontSize(10)
  7945. .fontColor(Color.White)
  7946. }
  7947. .justifyContent(FlexAlign.Start)
  7948. .padding({ right: 18,left:36 })
  7949. }
  7950. }
  7951. //x5的竖屏模式需要99%
  7952. .width(this.isLandscape?'80%':'93%')
  7953. .justifyContent(FlexAlign.Center)
  7954. .margin({bottom:6})
  7955. .animation({
  7956. duration: 666,
  7957. curve: 'ease-in-out' // 可选动画曲线
  7958. })
  7959. }
  7960. //播放进度条
  7961. @Builder
  7962. BottomView(){
  7963. Row() {
  7964. Button({type:ButtonType.Circle,stateEffect:true}){
  7965. Column() {
  7966. if (this.playType === 0) {
  7967. Image($r('app.media.loop'))
  7968. .width(27)
  7969. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7970. } else if (this.playType === 1) {
  7971. Image($r('app.media.single'))
  7972. .width(27)
  7973. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7974. } else if (this.playType === 2) {
  7975. Image($r('app.media.normal_play'))
  7976. .width(27)
  7977. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7978. } else if (this.playType === 3) {
  7979. Image($r('app.media.random'))
  7980. .width(27)
  7981. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7982. }
  7983. }
  7984. }
  7985. .layoutWeight(1)
  7986. .margin({ left: 5 })
  7987. .backgroundColor(Color.Transparent)
  7988. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  7989. .onClick(async () => {
  7990. this.setLoopMode()
  7991. })
  7992. this.fullButton()
  7993. Button({type:ButtonType.Circle,stateEffect:true}){
  7994. Column() {
  7995. Image($r('app.media.lyric'))
  7996. .width(26)
  7997. .aspectRatio(CommonConstants.ASPECT_RATIO)
  7998. }
  7999. }
  8000. .layoutWeight(1)
  8001. .backgroundColor(Color.Transparent)
  8002. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8003. .onClick(async () => {
  8004. this.isLyricSetting = !this.isLyricSetting;
  8005. })
  8006. //播放列表
  8007. Button({type:ButtonType.Circle,stateEffect:true}){
  8008. Image($r('app.media.hm_playlist'))
  8009. .width(24)
  8010. .fillColor(Color.White)
  8011. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8012. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  8013. height: '95%',
  8014. dragBar: true,
  8015. showClose: true,
  8016. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8017. blurStyle: BlurStyle.Thin,
  8018. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  8019. title: {
  8020. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  8021. + `(${this.songList.length}首)`
  8022. }
  8023. })
  8024. }
  8025. .layoutWeight(1)
  8026. .backgroundColor(Color.Transparent)
  8027. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8028. .onClick(() => {
  8029. this.isShowSheetView = !this.isShowSheetView;
  8030. if(this.isPlayListBgGrass){
  8031. this.isFrontWhite = true
  8032. }else{
  8033. this.isFrontWhite = false
  8034. }
  8035. this.scrollIndex()
  8036. })
  8037. }
  8038. .width(this.isLandscape?'88%':'95%')
  8039. .justifyContent(FlexAlign.SpaceAround)
  8040. .height(30)
  8041. .margin({top:3})
  8042. .animation({
  8043. duration: 666,
  8044. curve: 'ease-in-out' // 可选动画曲线
  8045. })
  8046. }
  8047. @Builder
  8048. fullButton(){
  8049. Button({type:ButtonType.Circle,stateEffect:true}){
  8050. Column() {
  8051. Image($r('app.media.full_4'))
  8052. .width(25)
  8053. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8054. }
  8055. }
  8056. .layoutWeight(1)
  8057. .backgroundColor(Color.Transparent)
  8058. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  8059. .onClick(async () => {
  8060. if (this.isLandscape) {
  8061. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  8062. } else {
  8063. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  8064. }
  8065. })
  8066. }
  8067. //旧版本播放进度条
  8068. @Builder
  8069. playProgressView() {
  8070. Row() {
  8071. Button({ type: ButtonType.Circle, stateEffect: true }) {
  8072. Column() {
  8073. if (this.playType === 0) {
  8074. Image($r('app.media.loop'))
  8075. .width($r('app.float.control_image_width'))
  8076. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8077. } else if (this.playType === 1) {
  8078. Image($r('app.media.single'))
  8079. .width($r('app.float.control_image_width'))
  8080. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8081. } else if (this.playType === 2) {
  8082. Image($r('app.media.normal_play'))
  8083. .width($r('app.float.control_image_width'))
  8084. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8085. } else if (this.playType === 3) {
  8086. Image($r('app.media.random'))
  8087. .width($r('app.float.control_image_width'))
  8088. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8089. }
  8090. }
  8091. }
  8092. .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  8093. .animation({
  8094. duration: 666,
  8095. curve: 'ease-in-out' // 可选动画曲线
  8096. })
  8097. .backgroundColor(Color.Transparent)
  8098. .margin({ right: 10 })
  8099. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8100. .onClick(async () => {
  8101. this.setLoopMode()
  8102. })
  8103. Text(this.currentTime)
  8104. .fontSize($r('app.float.slider_font_size'))
  8105. .fontColor(Color.White)
  8106. .margin(3)
  8107. Slider({
  8108. value: this.progressValue,
  8109. min: 0,
  8110. max: this.PROGRESS_MAX_VALUE,
  8111. step: 1,
  8112. style: SliderStyle.OutSet
  8113. })
  8114. .width('600px')
  8115. .blockColor('rgba(255,255,255,1)')
  8116. .trackColor('rgba(255,255,255,0.3)')
  8117. .selectedColor(Color.White)
  8118. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  8119. .layoutWeight(1)
  8120. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  8121. .showSteps(false)
  8122. .showTips(true)
  8123. .enabled(this.slideEnable)
  8124. .onChange((value: number, mode: SliderChangeMode) => {
  8125. // if (mode == 2) {
  8126. this.isSeekTo = true;
  8127. this.mDestroyPage = false;
  8128. this.showLoadIng();
  8129. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  8130. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  8131. this.seekTo(seekValue + "");
  8132. // this.setProgress()
  8133. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  8134. this.isSeekTo = false;
  8135. // }
  8136. })
  8137. Text(this.totalTime)
  8138. .fontSize($r('app.float.slider_font_size'))
  8139. .fontColor(Color.White)
  8140. .margin(3)
  8141. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  8142. //播放列表
  8143. Button({ type: ButtonType.Circle, stateEffect: true }) {
  8144. Image($r('app.media.hm_playlist'))
  8145. .width($r('app.float.control_image_width'))
  8146. .fillColor(Color.White)
  8147. .aspectRatio(CommonConstants.ASPECT_RATIO)
  8148. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  8149. height: '95%',
  8150. dragBar: true,
  8151. showClose: true,
  8152. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  8153. blurStyle: BlurStyle.Thin,
  8154. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  8155. title: {
  8156. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  8157. + `(${this.songList.length}首)`
  8158. }
  8159. })
  8160. }
  8161. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  8162. .animation({
  8163. duration: 666,
  8164. curve: 'ease-in-out' // 可选动画曲线
  8165. })
  8166. .backgroundColor(Color.Transparent)
  8167. .margin({ right: 20, left: 10 })
  8168. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8169. .onClick(() => {
  8170. this.isShowSheetView = !this.isShowSheetView;
  8171. if (this.isPlayListBgGrass) {
  8172. this.isFrontWhite = true
  8173. } else {
  8174. this.isFrontWhite = false
  8175. }
  8176. this.scrollIndex()
  8177. })
  8178. }
  8179. //x5的竖屏模式需要99%
  8180. .width(this.isPhonePortrait() ? '93.4%'
  8181. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  8182. .height(this.isPhoneLan() ? 25 : 33)
  8183. .animation({
  8184. duration: 666,
  8185. curve: 'ease-in-out' // 可选动画曲线
  8186. })
  8187. }
  8188. isBigScreen() {
  8189. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  8190. return true
  8191. }
  8192. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8193. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  8194. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  8195. return false
  8196. } else {
  8197. return true
  8198. }
  8199. return false
  8200. }
  8201. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  8202. @State isCoverRectangle: boolean = false
  8203. @State isCoverTop: boolean = true
  8204. // 添加控制缩放的状态变量
  8205. @State scaleValueImage: number = 1
  8206. @Builder
  8207. CoverInfo() {
  8208. Column() {
  8209. //如果是方形,判断是不是封面在顶部,如果不是顶部,显示musicNameInfo, 如果是圆形显示musicNameInfo
  8210. if (this.isCoverRectangle) {
  8211. if (!this.isCoverTop) {
  8212. this.musicNameInfo(false)
  8213. }
  8214. } else {
  8215. this.musicNameInfo(false)
  8216. }
  8217. Stack() {
  8218. // 唱片旋转效果
  8219. Image($r('app.media.ic_music_disc'))
  8220. .width(245)
  8221. .height(245)
  8222. .margin({ right: 20, left: 20 ,top:this.isCoverRectangle||this.isLandscape?0:43})
  8223. .aspectRatio(1)
  8224. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  8225. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  8226. .borderRadius('100%')
  8227. .align(Alignment.Center)
  8228. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  8229. .rotate({
  8230. angle: this.rotateAngle,
  8231. centerX: "50%",
  8232. centerY: "50%",
  8233. })
  8234. .animation({
  8235. duration: 100,
  8236. curve: Curve.Linear
  8237. })
  8238. .shadow({
  8239. radius: 22,
  8240. type: ShadowType.BLUR,
  8241. color: 'on_primary'
  8242. })
  8243. Column() {
  8244. if (this.isCoverTop && !this.isCoverOpacity() && this.isCoverRectangle) {
  8245. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  8246. .height(this.isHiCar()?(px2vp(this.windowHeight)*0.46):'auto')
  8247. .width(this.isHiCar()?'auto':this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '88%')
  8248. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  8249. .alt(this.imageLabel)
  8250. .margin({ right: 8, left: 8, top: 8 })
  8251. .aspectRatio(1)
  8252. .opacity(this.opacityValueImage)
  8253. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  8254. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  8255. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  8256. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  8257. .align(Alignment.Center)//
  8258. .clip(true)
  8259. .rotate({
  8260. x: 0,
  8261. y: 0,
  8262. z: 1,
  8263. angle: this.rotateAngle
  8264. })
  8265. .shadow({
  8266. radius: 22,
  8267. type: ShadowType.BLUR,
  8268. color: 'on_primary'
  8269. })
  8270. .onClick(() => {
  8271. this.getImageColor()
  8272. })
  8273. this.musicNameInfo(false)
  8274. } else {
  8275. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  8276. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  8277. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 162))
  8278. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  8279. .alt(this.imageLabel)
  8280. .margin({ right: 20, left: 20,top:this.isCoverRectangle||this.isLandscape?0:43 })
  8281. .aspectRatio(1)
  8282. .opacity(this.opacityValueImage)
  8283. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  8284. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  8285. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  8286. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  8287. .align(Alignment.Center)//
  8288. .clip(true)
  8289. .shadow({
  8290. radius: 22,
  8291. type: ShadowType.BLUR,
  8292. color: 'on_primary'
  8293. })
  8294. .rotate({
  8295. x: 0,
  8296. y: 0,
  8297. z: 1,
  8298. angle: this.rotateAngle
  8299. })
  8300. .onClick(() => {
  8301. this.getImageColor()
  8302. })
  8303. if (this.isPhoneLan()) {
  8304. Text(this.name)
  8305. .fontSize(18)
  8306. .fontWeight(FontWeight.Bold)
  8307. .margin({ top: 13 })
  8308. .textOverflow({ overflow: TextOverflow.Ellipsis })
  8309. .maxLines(1)
  8310. .width('99%')
  8311. .textAlign(TextAlign.Center)
  8312. .fontColor(Color.White)
  8313. }
  8314. }
  8315. }
  8316. // 唱针以左上角为点选择逆时针40度
  8317. Image($r('app.media.ic_music_cover_hand'))
  8318. .height(130)
  8319. .margin({ bottom: 220, top: 0 })
  8320. .align(Alignment.Top)
  8321. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  8322. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  8323. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  8324. Column({ space: 8 }) {
  8325. Text(this.name)
  8326. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  8327. .fontWeight(FontWeight.Bold)
  8328. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  8329. .maxLines(1)
  8330. .width('48%')
  8331. .textAlign(TextAlign.Center)
  8332. .fontColor(Color.White)
  8333. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  8334. Text(this.artist)
  8335. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  8336. .fontColor(Color.White)
  8337. .fontWeight(FontWeight.Bold)
  8338. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  8339. }
  8340. .justifyContent(FlexAlign.Start)
  8341. .zIndex(1)
  8342. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  8343. }
  8344. .margin({
  8345. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  8346. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  8347. top: this.isCoverOpacity() ? 0 : 20
  8348. })
  8349. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  8350. this.SingleLyricView()
  8351. }
  8352. if (this.isPhoneLan()) {
  8353. Column() {
  8354. this.playCenterView()
  8355. // this.playProgressView()
  8356. }
  8357. .position({ left: 28, bottom: 38 })
  8358. } else {
  8359. this.BottomControl()
  8360. }
  8361. }
  8362. .width(CommonConstants.FULL_PERCENT)
  8363. .clip(true)
  8364. }
  8365. @Builder
  8366. private musicNameInfo(isHidden: boolean) {
  8367. Column({ space: 8 }) {
  8368. Text(this.name)
  8369. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22)
  8370. .fontWeight(FontWeight.Bold)
  8371. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  8372. .maxLines(1)
  8373. .width('99%')
  8374. .textAlign(TextAlign.Center)
  8375. .fontColor(Color.White)
  8376. Text(this.artist + ' ' + this.currentSong?.album)
  8377. .fontSize(this.isCoverOpacity() ? 12 : 15)
  8378. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  8379. .fontColor(Color.White)
  8380. .textAlign(TextAlign.Center)
  8381. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  8382. .width('99%')
  8383. .maxLines(1)
  8384. }
  8385. .margin({ top: this.isCoverOpacity() ? 20 : isHidden ? 40 : 20 })
  8386. .zIndex(1)
  8387. .scale({ x: this.scaleValueImage, y: this.scaleValueImage }) // 添加缩放效果
  8388. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  8389. }
  8390. @Builder
  8391. private PlayTitle() {
  8392. Row() {
  8393. Row() {
  8394. Image($r('app.media.ic_back_down'))
  8395. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  8396. .hitTestBehavior(HitTestMode.Transparent)
  8397. Text(this.name + ' ' + this.artist)
  8398. .fontColor(Color.White)
  8399. .fontSize($r('app.float.title_font_size'))
  8400. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  8401. .maxLines(1)
  8402. .visibility(Visibility.None)
  8403. .margin({ left: 2, right: 30 })
  8404. }
  8405. .layoutWeight(1)
  8406. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8407. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  8408. .onClick(() => {
  8409. this.isShowPlay = false;
  8410. })
  8411. Column() {
  8412. AVCastPicker({
  8413. normalColor: Color.White,
  8414. onStateChange: this.onStateVastChange
  8415. })
  8416. .width(24)
  8417. .height(24)
  8418. }
  8419. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  8420. }
  8421. .width(PlayConstants.ROW_WIDTH)
  8422. }
  8423. @Builder
  8424. lyricSettingSheet(isPip: boolean) {
  8425. Scroll() {
  8426. this.lyricSetting(isPip)
  8427. }
  8428. .width('100%')
  8429. .height('100%')
  8430. }
  8431. @Builder
  8432. lyricSetting(isPip: boolean) {
  8433. Column() {
  8434. // 时间调节模块
  8435. if (!isPip) {
  8436. this.BuildTimeControls()
  8437. }
  8438. // 字号控制模块
  8439. this.BuildFontControls(isPip)
  8440. }
  8441. }
  8442. // 歌词时间偏移状态
  8443. @State timeOffset: number = 0.0
  8444. @State currentLyricColor: string = '#FFFFFF'
  8445. @State currentLyricColorPip: string = '#FFFFFF'
  8446. @State currentHighLightLyricColor: string = '#FF4081'
  8447. @State currentHighLightLyricColorPip: string = '#FF4081'
  8448. // 歌词字号状态
  8449. @State currentLyricSize: number = 20
  8450. @State currentLyricSizePip: number = 20
  8451. // 高亮歌词放大倍数
  8452. @State currentHightLyricSize: number = 1.2
  8453. @State currentHightLyricSizePip: number = 1.2
  8454. @State currentLyricLineSpace: number = 10
  8455. @State currentLyricLineSpacePip: number = 10
  8456. @State currentLyricAlignMode: number = 1
  8457. @State currentLyricAlignModePip: number = 1
  8458. @State blurDegree: number = 2
  8459. @State blurDegreePip: number = 2
  8460. @State isShowSelectColor: boolean = false
  8461. @State isShowHLSelectColor: boolean = false
  8462. @State isShowPipBgSelectColor: boolean = false
  8463. @State pipLyWidth: number = 330
  8464. @State pipLyHeight: number = 120
  8465. // 构建颜色选择器
  8466. @Builder
  8467. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  8468. Row({ space: 10 }) {
  8469. HSBColorPicker({
  8470. color: '#FFFFFF',
  8471. radius: 8,
  8472. layout: HSBColorPickerLayout.COLUMN,
  8473. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  8474. '#fa7105'],
  8475. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  8476. this.changeLyricColor(value, isPip, isBGPip)
  8477. })
  8478. .height(250)
  8479. .layoutWeight(1)
  8480. .padding(25)
  8481. }
  8482. .width('66%')
  8483. }
  8484. @State isOpenPip: boolean = false
  8485. @State pipBgIndex: number = 0
  8486. // 构建字号控制器
  8487. @Builder
  8488. BuildFontControls(isPip: boolean) {
  8489. Column() {
  8490. if (isPip) {
  8491. Column() {
  8492. Row() {
  8493. Text('悬浮歌词')
  8494. .margin({ left: 18 })
  8495. .fontSize(15)
  8496. .fontColor(Color.White)
  8497. .fontWeight(480)
  8498. .layoutWeight(1)
  8499. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  8500. .selectedColor(this.themeColor)
  8501. .switchPointColor(Color.White)
  8502. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8503. .margin({ right: 18 })
  8504. .onChange((checked: boolean) => {
  8505. this.isOpenPip = checked;
  8506. if (this.isOpenPip) {
  8507. this.startPip()
  8508. } else {
  8509. this.stopPip()
  8510. }
  8511. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  8512. })
  8513. .width(50)
  8514. .height(30);
  8515. }
  8516. .height(55)
  8517. }
  8518. .backgroundColor(Color.Transparent)
  8519. .borderRadius(15)
  8520. .margin({
  8521. left: 30,
  8522. right: 30,
  8523. top: 0,
  8524. bottom: 20
  8525. })
  8526. .padding(0)
  8527. .border({
  8528. color: Color.White,
  8529. width: 1.8
  8530. })
  8531. }else{
  8532. Column() {
  8533. Row() {
  8534. Text('单行歌词')
  8535. .margin({ left: 18 })
  8536. .fontSize(15)
  8537. .fontColor(Color.White)
  8538. .fontWeight(480)
  8539. .layoutWeight(1)
  8540. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  8541. .selectedColor(this.themeColor)
  8542. .switchPointColor(Color.White)
  8543. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8544. .margin({ right: 18 })
  8545. .onChange((checked: boolean) => {
  8546. this.isShowSingleLineLyric = checked;
  8547. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  8548. })
  8549. .width(50)
  8550. .height(30);
  8551. }
  8552. .height(55)
  8553. }
  8554. .backgroundColor(Color.Transparent)
  8555. .borderRadius(15)
  8556. .margin({
  8557. left: 30,
  8558. right: 30,
  8559. top: 10,
  8560. bottom: 10
  8561. })
  8562. .padding(0)
  8563. .border({
  8564. color: Color.White,
  8565. width: 1.8
  8566. })
  8567. }
  8568. Row() {
  8569. Text(`歌词居中:`)
  8570. .fontSize(14)
  8571. .fontColor(Color.White)
  8572. .margin({ left: 2 })
  8573. Row() {
  8574. ForEach(['居中', '居左'], (size: string, index: number) => {
  8575. Button(size)
  8576. .width(60)
  8577. .height(28)
  8578. .fontSize(12)
  8579. .fontColor('#FFFFFF')
  8580. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  8581. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  8582. .border({
  8583. color: (!isPip && this.currentLyricAlignMode === index) ||
  8584. (isPip && this.currentLyricAlignModePip === index) ?
  8585. '#007DFF' : '#DDDDDD',
  8586. width: 1.8
  8587. })
  8588. .onClick(() => {
  8589. this.setLyricAlignMode(index, isPip)
  8590. })
  8591. .margin({ left: 10, right: 8 })
  8592. })
  8593. }
  8594. .width('76%')
  8595. Blank()
  8596. }
  8597. .margin({
  8598. top: 10,
  8599. bottom: 10,
  8600. right: 20,
  8601. left: 20
  8602. })
  8603. if (isPip) {
  8604. Row() {
  8605. Text(`悬浮背景:`)
  8606. .fontSize(14)
  8607. .fontColor(Color.White)
  8608. Select([
  8609. { value: CommonConstants.PIP_LYRIC_BG[0] },
  8610. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  8611. .font({ size: 13, weight: FontWeight.Medium })
  8612. .fontColor(Color.White)
  8613. .margin({ left: 10 })
  8614. .selected(this.pipBgIndex)
  8615. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  8616. .onSelect(async (_index: number, text?: string | undefined) => {
  8617. this.pipBgIndex = _index
  8618. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  8619. if (this.pipBgIndex === 0) {
  8620. if (this.cover) {
  8621. this.pipBg = this.cover
  8622. } else {
  8623. this.pipBg = this.imageColor
  8624. }
  8625. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  8626. } else {
  8627. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  8628. }
  8629. })
  8630. Column() {
  8631. }
  8632. .backgroundColor(this.pipBg)
  8633. .margin({ left: 10, right: 10 })
  8634. .borderRadius(20)
  8635. .height(28)
  8636. .width(28)
  8637. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8638. Row() {
  8639. SymbolGlyph($r('sys.symbol.paintbrush'))
  8640. .fontColor([Color.White])
  8641. .effectStrategy(1)
  8642. Text(`选择颜色`)
  8643. .fontSize(13)
  8644. .margin({ left: 10 })
  8645. .fontColor(Color.White)
  8646. }
  8647. }
  8648. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  8649. .backgroundColor(Color.Transparent)
  8650. .border({
  8651. color: '#FFFFFF',
  8652. radius: 20,
  8653. width: 1.8
  8654. })
  8655. .height(36)
  8656. .width(110)
  8657. .onClick(() => {
  8658. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  8659. })
  8660. .bindPopup(this.isShowPipBgSelectColor, {
  8661. builder: this.SelectColor(false, isPip, true),
  8662. placement: Placement.Top,
  8663. mask: { color: '#33000000' },
  8664. enableArrow: false, //是否显示箭头
  8665. showInSubWindow: false,
  8666. onStateChange: (e) => {
  8667. if (!e.isVisible) {
  8668. this.isShowPipBgSelectColor = false
  8669. }
  8670. }
  8671. })
  8672. }
  8673. .width('76%')
  8674. .margin({ bottom: 5, right: 45, left: 20 })
  8675. }
  8676. if (!isPip) {
  8677. Row() {
  8678. Text(`高亮居中:`)
  8679. .fontSize(14)
  8680. .fontColor(Color.White)
  8681. Column() {
  8682. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  8683. .selectedColor(this.themeColor)
  8684. .switchPointColor(Color.White)
  8685. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8686. .onChange((checked: boolean) => {
  8687. this.isHightLightCenter = checked;
  8688. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  8689. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  8690. })
  8691. .width(50)
  8692. .height(30)
  8693. .alignSelf(ItemAlign.Start)
  8694. .margin({ left: 12 })
  8695. Blank()
  8696. }
  8697. .width('76%')
  8698. }
  8699. .margin({
  8700. left: 20,
  8701. right: 15,
  8702. top: 10,
  8703. bottom: 10
  8704. })
  8705. }
  8706. Row() {
  8707. Text(`歌词颜色:`)
  8708. .fontSize(14)
  8709. .fontColor(Color.White)
  8710. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  8711. .fontSize(15)
  8712. .fontColor(Color.White)
  8713. .margin({ left: 12, right: 12 })
  8714. Column() {
  8715. }
  8716. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  8717. .margin({ right: 12 })
  8718. .borderRadius(20)
  8719. .height(28)
  8720. .width(28)
  8721. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8722. Row() {
  8723. SymbolGlyph($r('sys.symbol.paintbrush'))
  8724. .fontColor([Color.White])
  8725. .effectStrategy(1)
  8726. Text(`选择颜色`)
  8727. .fontSize(13)
  8728. .margin({ left: 10 })
  8729. .fontColor(Color.White)
  8730. }
  8731. }
  8732. .backgroundColor(Color.Transparent)
  8733. .border({
  8734. color: '#FFFFFF',
  8735. radius: 20,
  8736. width: 1.8
  8737. })
  8738. .height(36)
  8739. .width(110)
  8740. .onClick(() => {
  8741. this.isShowSelectColor = !this.isShowSelectColor
  8742. })
  8743. .bindPopup(this.isShowSelectColor, {
  8744. builder: this.SelectColor(false, isPip),
  8745. placement: Placement.Top,
  8746. mask: { color: '#33000000' },
  8747. enableArrow: false, //是否显示箭头
  8748. showInSubWindow: false,
  8749. onStateChange: (e) => {
  8750. if (!e.isVisible) {
  8751. this.isShowSelectColor = false
  8752. }
  8753. }
  8754. })
  8755. }
  8756. .width('76%')
  8757. .margin({
  8758. top: 10,
  8759. bottom: 10,
  8760. right: 45,
  8761. left: 20
  8762. })
  8763. Row() {
  8764. Text(`高亮颜色:`)
  8765. .fontSize(14)
  8766. .fontColor(Color.White)
  8767. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  8768. .fontSize(15)
  8769. .fontColor(Color.White)
  8770. .margin({ left: 12, right: 12 })
  8771. Column() {
  8772. }
  8773. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  8774. .margin({ right: 12 })
  8775. .borderRadius(20)
  8776. .height(28)
  8777. .width(28)
  8778. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8779. Row() {
  8780. SymbolGlyph($r('sys.symbol.paintbrush'))
  8781. .fontColor([Color.White])
  8782. .effectStrategy(1)
  8783. Text(`选择颜色`)
  8784. .fontSize(13)
  8785. .margin({ left: 10 })
  8786. .fontColor(Color.White)
  8787. }
  8788. }
  8789. .backgroundColor(Color.Transparent)
  8790. .border({
  8791. color: '#FFFFFF',
  8792. radius: 20,
  8793. width: 1.8
  8794. })
  8795. .height(36)
  8796. .width(110)
  8797. .onClick(() => {
  8798. this.isShowHLSelectColor = !this.isShowHLSelectColor
  8799. })
  8800. .bindPopup(this.isShowHLSelectColor, {
  8801. builder: this.SelectColor(true, isPip),
  8802. placement: Placement.Top,
  8803. mask: { color: '#33000000' },
  8804. enableArrow: false, //是否显示箭头
  8805. showInSubWindow: false,
  8806. onStateChange: (e) => {
  8807. if (!e.isVisible) {
  8808. this.isShowHLSelectColor = false
  8809. }
  8810. }
  8811. })
  8812. }
  8813. .width('76%')
  8814. .margin({
  8815. top: 10,
  8816. bottom: 10,
  8817. right: 45,
  8818. left: 20
  8819. })
  8820. if (isPip) {
  8821. Row() {
  8822. Text(`显示宽度:`)
  8823. .fontSize(14)
  8824. .fontColor(Color.White)
  8825. Slider({
  8826. value: this.pipLyWidth,
  8827. min: 10,
  8828. max: 800,
  8829. step: 1,
  8830. style: SliderStyle.OutSet
  8831. })
  8832. .blockColor(this.themeColor)
  8833. .trackColor($r('app.color.speed_text_color'))
  8834. .selectedColor(Color.White)
  8835. .trackThickness(6)
  8836. .onChange((value: number) => {
  8837. this.pipLyWidth = value
  8838. if (this.pipController) {
  8839. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  8840. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  8841. }
  8842. })
  8843. .width('76%')
  8844. }
  8845. .margin({
  8846. left: 20,
  8847. right: 15,
  8848. top: 5,
  8849. bottom: 5
  8850. })
  8851. Row() {
  8852. Text(`显示高度:`)
  8853. .fontSize(14)
  8854. .fontColor(Color.White)
  8855. Slider({
  8856. value: this.pipLyHeight,
  8857. min: 10,
  8858. max: 1000,
  8859. step: 1,
  8860. style: SliderStyle.OutSet
  8861. })
  8862. .blockColor(this.themeColor)
  8863. .trackColor($r('app.color.speed_text_color'))
  8864. .selectedColor(Color.White)
  8865. .trackThickness(6)
  8866. .onChange((value: number) => {
  8867. this.pipLyHeight = value
  8868. if (this.pipController) {
  8869. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  8870. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  8871. }
  8872. })
  8873. .width('76%')
  8874. }
  8875. .margin({
  8876. left: 20,
  8877. right: 15,
  8878. top: 5,
  8879. bottom: 5
  8880. })
  8881. }
  8882. Row() {
  8883. Text(`歌词字号:`)
  8884. .fontSize(14)
  8885. .fontColor(Color.White)
  8886. Slider({
  8887. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  8888. min: 12,
  8889. max: 30,
  8890. step: 0.1,
  8891. style: SliderStyle.OutSet
  8892. })
  8893. .blockColor(this.themeColor)
  8894. .trackColor($r('app.color.speed_text_color'))
  8895. .selectedColor(Color.White)
  8896. .trackThickness(6)
  8897. .onChange((value: number) => {
  8898. this.setLyricTextSize(value, isPip)
  8899. })
  8900. .width('76%')
  8901. }
  8902. .margin({
  8903. left: 20,
  8904. right: 15,
  8905. top: 5,
  8906. bottom: 5
  8907. })
  8908. Row() {
  8909. Text(`高亮倍数:`)
  8910. .fontSize(14)
  8911. .fontColor(Color.White)
  8912. Slider({
  8913. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  8914. min: 1,
  8915. max: 2,
  8916. step: 0.1,
  8917. style: SliderStyle.OutSet
  8918. })
  8919. .blockColor(this.themeColor)
  8920. .trackColor($r('app.color.speed_text_color'))
  8921. .selectedColor(Color.White)
  8922. .trackThickness(6)
  8923. .onChange((value: number) => {
  8924. this.setHighLyricTextSize(value, isPip)
  8925. })
  8926. .width('76%')
  8927. }
  8928. .margin({
  8929. left: 20,
  8930. right: 15,
  8931. top: 5,
  8932. bottom: 5
  8933. })
  8934. Row() {
  8935. Text(`歌词间隙:`)
  8936. .fontSize(14)
  8937. .fontColor(Color.White)
  8938. Slider({
  8939. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  8940. min: 0,
  8941. max: 100,
  8942. step: 1,
  8943. style: SliderStyle.OutSet
  8944. })
  8945. .blockColor(this.themeColor)
  8946. .trackColor($r('app.color.speed_text_color'))
  8947. .selectedColor(Color.White)
  8948. .trackThickness(6)
  8949. .onChange((value: number) => {
  8950. this.setLyricLineSpace(value, isPip)
  8951. })
  8952. .width('76%')
  8953. }
  8954. .margin({
  8955. left: 20,
  8956. right: 15,
  8957. top: 5,
  8958. bottom: 5
  8959. })
  8960. //取值间隔为100,默认为400,取值越大,字体越粗
  8961. Row() {
  8962. Text(`歌词字重:`)
  8963. .fontSize(14)
  8964. .fontColor(Color.White)
  8965. Slider({
  8966. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  8967. min: 100,
  8968. max: 900,
  8969. step: 100,
  8970. style: SliderStyle.OutSet
  8971. })
  8972. .blockColor(this.themeColor)
  8973. .trackColor($r('app.color.speed_text_color'))
  8974. .selectedColor(Color.White)
  8975. .trackThickness(6)
  8976. .onChange((value: number) => {
  8977. if (isPip) {
  8978. this.lyricTextWeightPip = value
  8979. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  8980. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  8981. } else {
  8982. this.lyricTextWeight = value
  8983. this.lyricController.setTextWeight(this.lyricTextWeight)
  8984. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  8985. }
  8986. })
  8987. .width('76%')
  8988. }
  8989. .margin({
  8990. left: 20,
  8991. right: 15,
  8992. top: 5,
  8993. bottom: 5
  8994. })
  8995. if (!isPip) {
  8996. Row() {
  8997. Text(`歌词模糊:`)
  8998. .fontSize(14)
  8999. .fontColor(Color.White)
  9000. Slider({
  9001. value: isPip ? this.blurDegreePip : this.blurDegree,
  9002. min: 0,
  9003. max: 5,
  9004. step: 0.1,
  9005. style: SliderStyle.OutSet
  9006. })
  9007. .blockColor(this.themeColor)
  9008. .trackColor($r('app.color.speed_text_color'))
  9009. .selectedColor(Color.White)
  9010. .trackThickness(6)
  9011. .onChange((value: number) => {
  9012. this.setBlurDegree(value, isPip)
  9013. })
  9014. .width('76%')
  9015. }
  9016. .margin({
  9017. left: 20,
  9018. right: 15,
  9019. top: 5,
  9020. bottom: 15
  9021. })
  9022. }
  9023. Row() {
  9024. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  9025. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  9026. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  9027. }
  9028. .justifyContent(FlexAlign.Center)
  9029. .margin({ top: 3, bottom: 10 })
  9030. }
  9031. }
  9032. private setBlurDegree(index: number, isPip: boolean) {
  9033. if (isPip) {
  9034. this.blurDegreePip = index
  9035. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  9036. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  9037. } else {
  9038. this.blurDegree = index
  9039. this.lyricController.setBlurDegree(this.blurDegree)
  9040. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  9041. }
  9042. }
  9043. private setLyricAlignMode(index: number, isPip: boolean) {
  9044. if (isPip) {
  9045. this.currentLyricAlignModePip = index
  9046. if (this.currentLyricAlignModePip === 1) {
  9047. this.lyricControllerXF.setAlignMode("left")
  9048. } else {
  9049. this.lyricControllerXF.setAlignMode("center")
  9050. }
  9051. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  9052. } else {
  9053. this.currentLyricAlignMode = index
  9054. if (this.currentLyricAlignMode === 1) {
  9055. this.lyricController.setAlignMode("left")
  9056. } else {
  9057. this.lyricController.setAlignMode("center")
  9058. }
  9059. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  9060. }
  9061. }
  9062. private setLyricTextSize(index: number, isPip: boolean) {
  9063. if (isPip) {
  9064. this.currentLyricSizePip = index
  9065. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  9066. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  9067. } else {
  9068. this.currentLyricSize = index
  9069. this.lyricController.setTextSize(this.currentLyricSize)
  9070. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  9071. }
  9072. }
  9073. private setHighLyricTextSize(scale: number, isPip: boolean) {
  9074. if (isPip) {
  9075. this.currentHightLyricSizePip = scale
  9076. this.lyricControllerXF
  9077. .setHighlightScale(this.currentHightLyricSizePip)
  9078. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  9079. } else {
  9080. this.currentHightLyricSize = scale
  9081. this.lyricController
  9082. .setHighlightScale(this.currentHightLyricSize)
  9083. PreferencesUtil.putSync('HighLyricTextSize', scale)
  9084. }
  9085. }
  9086. private setLyricLineSpace(index: number, isPip: boolean) {
  9087. if (isPip) {
  9088. this.currentLyricLineSpacePip = index
  9089. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  9090. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  9091. } else {
  9092. this.currentLyricLineSpace = index
  9093. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  9094. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  9095. }
  9096. }
  9097. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  9098. LogUtil.info('onecold isBG = ' + isBG)
  9099. if (isBG) { //如果是设置悬浮背景
  9100. this.pipBg = color
  9101. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  9102. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  9103. return
  9104. }
  9105. if (isPip) {
  9106. this.currentLyricColorPip = color
  9107. this.lyricControllerXF
  9108. .setTextColor(this.currentLyricColorPip)
  9109. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  9110. } else {
  9111. this.currentLyricColor = color
  9112. this.lyricController
  9113. .setTextColor(this.currentLyricColor)
  9114. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  9115. }
  9116. }
  9117. private changeLyricHightLightColor(color: string, isPip: boolean) {
  9118. if (isPip) {
  9119. this.currentHighLightLyricColorPip = color
  9120. this.lyricControllerXF
  9121. .setHighlightColor(this.currentHighLightLyricColorPip)
  9122. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  9123. } else {
  9124. this.currentHighLightLyricColor = color
  9125. this.lyricController
  9126. .setHighlightColor(this.currentHighLightLyricColor)
  9127. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  9128. }
  9129. }
  9130. // 构建时间控制器
  9131. @Builder
  9132. BuildTimeControls() {
  9133. Column() {
  9134. // 时间显示
  9135. Text(this.getTimeText())
  9136. .fontSize(18)
  9137. .fontColor(Color.White)
  9138. .margin({ bottom: 10 })
  9139. Row() {
  9140. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  9141. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  9142. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  9143. }
  9144. .justifyContent(FlexAlign.Center)
  9145. }
  9146. .margin({ top: 12, bottom: 8 })
  9147. }
  9148. // 精度按钮组件
  9149. @Builder
  9150. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  9151. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9152. Column() {
  9153. Image(icon)
  9154. .width(28)
  9155. .margin({ bottom: 5 })
  9156. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  9157. Text(label)
  9158. .fontSize(12)
  9159. .fontColor('#FFFFFF')
  9160. }
  9161. }
  9162. .backgroundColor(Color.Transparent)
  9163. .enabled(!this.isButtonDisabled(step))
  9164. .onClick(() => this.handlePrecisionAdjust(step))
  9165. .padding(5)
  9166. .width(66)
  9167. .height(66)
  9168. .margin({ left: 18, right: 18 })
  9169. .border({
  9170. color: '#FFFFFF',
  9171. width: 1.8
  9172. })
  9173. }
  9174. private handlePrecisionAdjust(step: number) {
  9175. if (step === 0) {
  9176. this.timeOffset = 0
  9177. return
  9178. }
  9179. // 精度处理:保留1位小数
  9180. const newOffset = Number((this.timeOffset + step).toFixed(5))
  9181. // 边界保护(±15.0秒)
  9182. if (newOffset < -30.0 || newOffset > 30.0) {
  9183. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  9184. return
  9185. }
  9186. // 状态更新
  9187. this.timeOffset = newOffset
  9188. }
  9189. // 按钮禁用逻辑
  9190. private isButtonDisabled(step: number): boolean {
  9191. const futureOffset = this.timeOffset + step
  9192. return (futureOffset < -30.0) || (futureOffset > 30.0)
  9193. }
  9194. // 时间显示文本升级
  9195. private getTimeText(): string {
  9196. const absValue = Math.abs(this.timeOffset)
  9197. return this.timeOffset === 0
  9198. ? '歌词时间已重置'
  9199. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  9200. }
  9201. // 导入 本地歌词 搜索歌词
  9202. @Builder
  9203. pushLyricButton(icon: Resource, step: number, label: string) {
  9204. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9205. Row() {
  9206. Image(icon)
  9207. .width(14)
  9208. .margin({ left: 13 })
  9209. Text(label)
  9210. .fontSize(12)
  9211. .margin({ left: 6 })
  9212. .fontColor('#FFFFFF')
  9213. }
  9214. }
  9215. .onClick(() => {
  9216. switch (step) {
  9217. case 0:
  9218. this.callFilePickerSelectFileForLyric()
  9219. break;
  9220. case 1:
  9221. //判断有没有设置api
  9222. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  9223. this.isLyricSetting = false
  9224. this.showTipsDialog()
  9225. return
  9226. }
  9227. if (StrUtil.isNotEmpty(this.videoUrl)) {
  9228. ToastUtil.showToast('正在获取')
  9229. this.isLyricSetting = false
  9230. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  9231. this.initLyric(lyricPath, true);
  9232. }
  9233. break;
  9234. }
  9235. })
  9236. .padding(5)
  9237. .width(110)
  9238. .backgroundColor(Color.Transparent)
  9239. .height(40)
  9240. .margin({ left: 6, right: 6 })
  9241. .border({
  9242. color: '#FFFFFF',
  9243. radius: 20,
  9244. width: 1.8
  9245. })
  9246. }
  9247. showVipDialog() {
  9248. DialogHelper.showCustomContentDialog({
  9249. dialogId: 'vip',
  9250. title: "友情提示",
  9251. autoCancel: false, //点击遮障层时,不关闭弹窗
  9252. backCancel: true, //点击返回键,不关闭弹窗
  9253. contentBuilder: () => {
  9254. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  9255. },
  9256. buttons: [],
  9257. })
  9258. }
  9259. //去赞助的自定义内容
  9260. @Builder
  9261. customVipBuilder(content: string) {
  9262. Column() {
  9263. Text(content)
  9264. .fontColor(Color.Gray)
  9265. .fontSize(16)
  9266. .alignSelf(ItemAlign.Start)
  9267. .margin({ bottom: 15 })
  9268. .fontSize(16)
  9269. Row() {
  9270. Button('取消')
  9271. .fontColor(Color.White)
  9272. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  9273. .height(50)
  9274. .layoutWeight(1)
  9275. .stateEffect(true)
  9276. .margin({ right: 6 })
  9277. .onClick(() => {
  9278. DialogHelper.closeDialog('vip'); //关闭弹框
  9279. })
  9280. Button('开通')
  9281. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  9282. .layoutWeight(1)
  9283. .height(50)
  9284. .backgroundColor(this.themeColor)
  9285. .stateEffect(true)
  9286. .margin({ left: 6 })
  9287. .onClick(() => {
  9288. DialogHelper.closeDialog('vip'); //关闭弹框
  9289. this.isShowPlay = false
  9290. this.mType = 1 //跳转到用户中心
  9291. // router.pushUrl({
  9292. // url: 'pages/VipPage'
  9293. // }, router.RouterMode.Single);
  9294. })
  9295. }
  9296. }
  9297. .width("100%")
  9298. .padding(10)
  9299. }
  9300. showTipsDialog() {
  9301. DialogHelper.showCustomContentDialog({
  9302. dialogId: 'tips',
  9303. title: "友情提示",
  9304. autoCancel: false, //点击遮障层时,不关闭弹窗
  9305. backCancel: true, //点击返回键,不关闭弹窗
  9306. contentBuilder: () => {
  9307. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  9308. },
  9309. buttons: [],
  9310. })
  9311. }
  9312. @Builder
  9313. customTipsBuilder(content: string) {
  9314. Column() {
  9315. Text(content)
  9316. .fontColor(Color.Gray)
  9317. .fontSize(16)
  9318. .alignSelf(ItemAlign.Start)
  9319. .margin({ bottom: 15 })
  9320. .fontSize(16)
  9321. Row() {
  9322. Button('取消')
  9323. .fontColor(Color.White)
  9324. .backgroundColor(this.themeColor)
  9325. .height(50)
  9326. .layoutWeight(1)
  9327. .stateEffect(true)
  9328. .margin({ right: 6 })
  9329. .onClick(() => {
  9330. DialogHelper.closeDialog('tips'); //关闭弹框
  9331. })
  9332. Button('跳转')
  9333. .fontColor(Color.White)//
  9334. .layoutWeight(1)
  9335. .height(50)
  9336. .backgroundColor(this.themeColor)
  9337. .stateEffect(true)
  9338. .margin({ left: 6 })
  9339. .onClick(() => {
  9340. DialogHelper.closeDialog('tips'); //关闭弹框
  9341. this.isShowEdit = false
  9342. this.longItemFilePath = ''
  9343. // if(this.isGridMusic&&!this.isShowPlay){
  9344. // this.longItemFilePath== ''
  9345. // }else{
  9346. // this.isShowEdit = false
  9347. // }
  9348. this.isShowMoreView = false;
  9349. this.isShowPlay = false
  9350. this.mType = 4
  9351. // router.pushUrl({
  9352. // url: 'pages/SettingPage'
  9353. // }, router.RouterMode.Single);
  9354. })
  9355. }
  9356. }
  9357. .width("100%")
  9358. .padding(10)
  9359. }
  9360. @Builder
  9361. PlayMoreSheet() {
  9362. Column() {
  9363. this.MoreList()
  9364. }
  9365. .width('100%')
  9366. .height('100%')
  9367. }
  9368. @Builder
  9369. MoreList() {
  9370. Scroll() {
  9371. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  9372. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  9373. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9374. Row() {
  9375. if (more.id === 3&&this.currentSong) {
  9376. Image(more.image)
  9377. .width(24)
  9378. .height(24)
  9379. .margin({ left: 10, right: 10 })
  9380. Text(more.title)
  9381. .fontSize(16)
  9382. .fontColor(Color.White)
  9383. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  9384. height: this.isCoverOpacity() ? '95%' : '95%',
  9385. dragBar: true,
  9386. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9387. showClose: true,
  9388. blurStyle: BlurStyle.Thin,
  9389. backgroundColor: Color.Transparent,
  9390. title: { title: '歌曲信息' }
  9391. })
  9392. } else if (more.id === 15 && this.currentSong) { //编辑标签
  9393. Image(more.image)
  9394. .width(24)
  9395. .height(24)
  9396. .margin({ left: 10, right: 10 })
  9397. Text(more.title)
  9398. .fontSize(16)
  9399. .fontColor(Color.White)
  9400. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  9401. height: '99%',
  9402. dragBar: true,
  9403. showClose: true,
  9404. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9405. // blurStyle:BlurStyle.Thin,
  9406. // backgroundColor:Color.Transparent,
  9407. title: { title: '编辑标签' }
  9408. })
  9409. } else if (more.id === 5) { //定时关闭
  9410. Image(more.image)
  9411. .width(24)
  9412. .height(24)
  9413. .margin({ left: 10, right: 10 })
  9414. Text(more.title)
  9415. .fontSize(16)
  9416. .fontColor(Color.White)
  9417. .onClick(() => {
  9418. this.doMore(more.id)
  9419. })
  9420. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  9421. height: this.isCoverOpacity() ? '95%' : '95%',
  9422. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9423. dragBar: true,
  9424. showClose: true,
  9425. title: { title: $r('app.string.time_close') }
  9426. })
  9427. } else if (more.id === 2) { //歌词设置
  9428. Image(more.image)
  9429. .width(24)
  9430. .height(24)
  9431. .margin({ left: 10, right: 10 })
  9432. Text(more.title)
  9433. .fontSize(16)
  9434. .fontColor(Color.White)
  9435. } else if (more.id === 16) { //悬浮歌词设置
  9436. Image(more.image)
  9437. .width(24)
  9438. .height(24)
  9439. .margin({ left: 10, right: 10 })
  9440. Text(more.title)
  9441. .fontSize(16)
  9442. .fontColor(Color.White)
  9443. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  9444. height: this.isCoverOpacity() ? '95%' : '95%',
  9445. dragBar: true,
  9446. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9447. showClose: true,
  9448. blurStyle: BlurStyle.Thin,
  9449. backgroundColor: Color.Transparent,
  9450. title: { title: '悬浮歌词' }
  9451. })
  9452. } else if (more.id === 11) {
  9453. Image(more.image)
  9454. .width(24)
  9455. .height(24)
  9456. .margin({ left: 10, right: 10 })
  9457. Text(more.title)
  9458. .fontSize(16)
  9459. .fontColor(Color.White)
  9460. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  9461. height: this.isCoverOpacity() ? '95%' : '60%',
  9462. dragBar: true,
  9463. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9464. showClose: true,
  9465. blurStyle: BlurStyle.Thin,
  9466. backgroundColor: Color.Transparent,
  9467. title: { title: '跳过头尾' }
  9468. })
  9469. } else if (more.id === 12) { //投播
  9470. AVCastPicker({
  9471. customPicker: (): void => this.TPImageBuilder(more),
  9472. onStateChange: (state) => {
  9473. if (state == AVCastPickerState.STATE_APPEARING) {
  9474. console.log(' The picker starts showing.');
  9475. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  9476. console.log(' The picker finishes presenting.');
  9477. }
  9478. },
  9479. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  9480. sessionType: 'video'
  9481. })
  9482. .id('AVCastPicker')
  9483. } else {
  9484. Image(more.image)
  9485. .width(24)
  9486. .height(24)
  9487. .margin({ left: 10, right: 10 })
  9488. .onClick(() => {
  9489. this.doMore(more.id)
  9490. })
  9491. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  9492. .fontSize(16)
  9493. .fontColor(Color.White)
  9494. .onClick(() => {
  9495. this.doMore(more.id)
  9496. })
  9497. Select([//倍速
  9498. { value: '0.25x' },
  9499. { value: '0.5x' },
  9500. { value: '0.75x' },
  9501. { value: '1x' },
  9502. { value: '1.25x' },
  9503. { value: '1.5x' },
  9504. { value: '1.75x' },
  9505. { value: '2x' },
  9506. { value: '3x' }])
  9507. .font({ size: 16, weight: FontWeight.Medium })
  9508. .fontColor($r('sys.color.white'))
  9509. .margin({ left: 25 })
  9510. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  9511. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  9512. .value(Utility.optimizedFormat(this.playSpeed))
  9513. .onSelect(async (_index: number, text?: string | undefined) => {
  9514. let speed = parseFloat(text?.replace('x', '') || '1');
  9515. if (!CommonConstants.video_speed_list.includes(speed)) {
  9516. speed = 1;
  9517. }
  9518. this.playSpeed = speed
  9519. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  9520. })
  9521. Slider({
  9522. value: this.volume,
  9523. min: 0,
  9524. max: 1,
  9525. step: 0.1,
  9526. style: SliderStyle.OutSet
  9527. })
  9528. .margin({ left: 18, right: 8 })
  9529. .blockColor(this.themeColor)
  9530. .trackColor($r('app.color.speed_text_color'))
  9531. .selectedColor(Color.White)
  9532. .trackThickness(9)
  9533. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  9534. .onChange((value: number) => {
  9535. this.volume = value;
  9536. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  9537. PreferencesUtil.putSync('DefalutVolume',this.volume)
  9538. })
  9539. .layoutWeight(1)
  9540. Blank()
  9541. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  9542. .selectedColor(this.themeColor)
  9543. .switchPointColor(Color.White)
  9544. .margin({ right: 15 })
  9545. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9546. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  9547. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  9548. if (more.id == 6) {
  9549. this.isMusicMemoryPlay = checked;
  9550. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  9551. if (this.isMusicMemoryPlay) {
  9552. ToastUtil.showToast('记忆播放已开启')
  9553. } else {
  9554. ToastUtil.showToast('记忆播放已关闭')
  9555. }
  9556. }
  9557. })
  9558. .width(48)
  9559. .height(24);
  9560. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  9561. .selectedColor(this.themeColor)
  9562. .switchPointColor(Color.White)
  9563. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9564. .margin({ right: 15 })
  9565. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  9566. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  9567. if (more.id == 7) {
  9568. this.isMusicBGCover = checked;
  9569. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  9570. if (this.isMusicBGCover) {
  9571. ToastUtil.showToast('播放背景随音乐封面已开启')
  9572. } else {
  9573. ToastUtil.showToast('播放背景随音乐封面已关闭')
  9574. }
  9575. }
  9576. })
  9577. .width(48)
  9578. .height(24);
  9579. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  9580. .selectedColor(this.themeColor)
  9581. .switchPointColor(Color.White)
  9582. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9583. .margin({ right: 15 })
  9584. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  9585. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  9586. if (more.id == 8) {
  9587. this.isSavePlayMode = checked;
  9588. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  9589. if (this.isSavePlayMode) {
  9590. ToastUtil.showToast('保存播放模式已开启')
  9591. } else {
  9592. ToastUtil.showToast('保存播放模式已关闭')
  9593. }
  9594. }
  9595. })
  9596. .width(48)
  9597. .height(24);
  9598. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  9599. .selectedColor(this.themeColor)
  9600. .switchPointColor(Color.White)
  9601. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9602. .margin({ right: 15 })
  9603. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  9604. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  9605. if (more.id == 13) {
  9606. this.isCoverRectangle = checked;
  9607. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  9608. if (this.isCoverRectangle) {
  9609. ToastUtil.showToast('封面方形已开启')
  9610. this.animationRoFun()
  9611. } else {
  9612. ToastUtil.showToast('封面圆形已开启')
  9613. this.animationRoFun()
  9614. }
  9615. }
  9616. })
  9617. .width(48)
  9618. .height(24);
  9619. }
  9620. }
  9621. .width('100%')
  9622. .height(45)
  9623. .padding(15)
  9624. .backgroundColor(Color.Transparent)
  9625. .borderRadius(12)
  9626. .margin({ bottom: 6 })
  9627. }
  9628. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  9629. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  9630. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  9631. .backgroundColor(Color.Transparent)
  9632. .onClick(() => {
  9633. this.doMore(more.id)
  9634. })
  9635. });
  9636. }
  9637. .width('100%')
  9638. .padding(16)
  9639. }.margin({ bottom: 18 })
  9640. }
  9641. @Builder
  9642. TPImageBuilder(more: MoreItem): void {
  9643. Row() {
  9644. Image($r('app.media.tuoping'))
  9645. .width(22)
  9646. .height(22)
  9647. .margin({ left: 10, right: 10 })
  9648. Text(more.title)
  9649. .fontSize(16)
  9650. .fontColor(Color.White)
  9651. }
  9652. .width('100%')
  9653. .layoutWeight(1)
  9654. .alignItems(VerticalAlign.Center)
  9655. .justifyContent(FlexAlign.Start)
  9656. }
  9657. private moreItems: MoreItem[] = [
  9658. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  9659. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  9660. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  9661. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  9662. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  9663. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  9664. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  9665. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  9666. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  9667. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  9668. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  9669. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  9670. { id: 4, image: $r('app.media.share2'), title: '分享' },
  9671. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  9672. // { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  9673. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  9674. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  9675. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  9676. ];
  9677. @State isShowMoreView: boolean = false;
  9678. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  9679. @State isShowTimeCloseMore: boolean = false
  9680. @State isShowDetailMore: boolean = false
  9681. @State isMusicBGCover: boolean = true
  9682. @State isSavePlayMode: boolean = true
  9683. @State isLyricSetting: boolean = false
  9684. @State isJumpSetting: boolean = false
  9685. @State isShowEdit: boolean = false
  9686. @State showPipLyric: boolean = false
  9687. async setRingTone() {
  9688. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  9689. return
  9690. }
  9691. // 确定后的逻辑
  9692. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  9693. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  9694. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  9695. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  9696. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  9697. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  9698. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  9699. , this.videoUrl, this.name).then(res => {
  9700. LogUtil.info('onecold setFlag :' + res);
  9701. });
  9702. }
  9703. doMore(moreId: number) {
  9704. switch (moreId) {
  9705. case 2: //歌词
  9706. this.isLyricSetting = !this.isLyricSetting;
  9707. this.isShowMoreView = false
  9708. break;
  9709. case 3: //详情
  9710. this.isShowDetailMore = !this.isShowDetailMore;
  9711. break;
  9712. case 4: //分享
  9713. if (this.currentSong !== undefined) {
  9714. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  9715. }
  9716. this.isShowMoreView = false
  9717. break;
  9718. case 5: //定时关闭
  9719. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  9720. break;
  9721. case 10: //设为铃声
  9722. this.setRingTone()
  9723. this.isShowMoreView = false
  9724. break;
  9725. case 11: //跳过头尾
  9726. this.isJumpSetting = !this.isJumpSetting;
  9727. break;
  9728. case 13: //倍速
  9729. break;
  9730. case 14: //搜索封面
  9731. if (this.currentSong !== undefined) {
  9732. this.doSearchCover(this.currentSong)
  9733. }
  9734. this.isShowMoreView = false
  9735. break;
  9736. case 15: //编辑标签
  9737. this.setEditStrEmpty()
  9738. this.tempLyricContent = this.lyricContent
  9739. this.isShowEdit = !this.isShowEdit;
  9740. break;
  9741. case 16: //悬浮歌词
  9742. this.showPipLyric = !this.showPipLyric;
  9743. break;
  9744. case 17: //横屏模式
  9745. if (this.isLandscape) {
  9746. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  9747. } else {
  9748. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  9749. }
  9750. this.isShowMoreView = false
  9751. break;
  9752. case 20://AB循环
  9753. this.isOpenAB = !this.isOpenAB;
  9754. this.isABSheet = false
  9755. break;
  9756. }
  9757. }
  9758. //AB循环
  9759. @State isOpenAB:boolean = false
  9760. @State jumpATime:number = 0
  9761. @State jumpBTime:number = 0
  9762. @State isABSheet:boolean = false
  9763. @Builder
  9764. ABLoopSheet() {
  9765. ABLoopComptent({
  9766. jumpATime:this.jumpATime,
  9767. jumpBTime:this.jumpBTime,
  9768. onClickAItem: async ()=>{
  9769. if(this.mIjkMediaPlayer){
  9770. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  9771. }
  9772. },
  9773. onClickBItem: async ()=>{
  9774. if(this.mIjkMediaPlayer){
  9775. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  9776. if(this.jumpBTime<=this.jumpATime){
  9777. ToastUtil.showToast('设置B点时间不能小于A点时间')
  9778. this.jumpBTime = 0
  9779. }
  9780. }
  9781. },
  9782. onCancleButtonClick: async ()=>{
  9783. this.isOpenAB = false
  9784. this.isABSheet = false
  9785. },
  9786. onStartButtonClick: async ()=>{
  9787. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  9788. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  9789. return
  9790. }
  9791. this.isABSheet = false
  9792. this.startABLoop()
  9793. },
  9794. })
  9795. }
  9796. //开始AB循环
  9797. startABLoop(){
  9798. if(this.mIjkMediaPlayer){
  9799. this.seekTo(this.jumpATime+'')
  9800. this.isOpenAB = true
  9801. }
  9802. }
  9803. /**
  9804. * 切换横竖屏
  9805. *
  9806. */
  9807. setOrientation(orientation: number) {
  9808. this.windowClass.setPreferredOrientation(orientation).then(() => {
  9809. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  9810. }).catch((err: BusinessError) => {
  9811. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  9812. });
  9813. }
  9814. /**
  9815. * 画中画功能(悬浮歌词功能)
  9816. *
  9817. */
  9818. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  9819. pipController?: PiPWindow.PiPController;
  9820. navigationId: string = '';
  9821. @State curState: string = '';
  9822. @State curError: ResourceStr = '';
  9823. @State pipBg: string = '#E8E8E8'
  9824. @State buttonAction: string = '';
  9825. //开启画中画功能
  9826. async startPip() {
  9827. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  9828. if (!this.pipController) {
  9829. await this.createPipController();
  9830. }
  9831. if (!this.pipController) {
  9832. Logger.info(`[${TAG}] pipController create error`);
  9833. return;
  9834. }
  9835. await this.pipController.startPiP();
  9836. }
  9837. async stopPip() {
  9838. if (!this.pipController) {
  9839. Logger.info(`[${TAG}] pipController is not exist`);
  9840. return;
  9841. }
  9842. this.isOpenPip = false
  9843. await this.pipController.stopPiP();
  9844. }
  9845. async createPipController() {
  9846. this.pipController = await PiPWindow.create({
  9847. context: getContext(this),
  9848. componentController: this.xcomponentController,
  9849. navigationId: this.navigationId,
  9850. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  9851. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  9852. customUIController: this.nodeController,
  9853. });
  9854. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  9855. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  9856. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  9857. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  9858. this.onStateChange(state, reason);
  9859. });
  9860. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  9861. this.onActionEvent(event, status);
  9862. });
  9863. }
  9864. destroyPipController() {
  9865. if (!this.pipController) {
  9866. return;
  9867. }
  9868. this.pipController.off('stateChange');
  9869. this.pipController.off('controlPanelActionEvent');
  9870. this.pipController = undefined;
  9871. }
  9872. onStateChange(state: PiPWindow.PiPState, reason: string) {
  9873. switch (state) {
  9874. case PiPWindow.PiPState.ABOUT_TO_START:
  9875. this.curState = 'ABOUT_TO_START';
  9876. this.curError = $r('app.string.current_error_hint');
  9877. break;
  9878. case PiPWindow.PiPState.STARTED:
  9879. this.curState = 'STARTED';
  9880. this.curError = $r('app.string.current_error_hint');
  9881. break;
  9882. case PiPWindow.PiPState.ABOUT_TO_STOP:
  9883. this.curState = 'ABOUT_TO_STOP';
  9884. this.curError = $r('app.string.current_error_hint');
  9885. break;
  9886. case PiPWindow.PiPState.STOPPED:
  9887. this.curState = 'STOPPED';
  9888. this.curError = $r('app.string.current_error_hint');
  9889. this.stopPip()
  9890. this.destroyPipController()
  9891. break;
  9892. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  9893. this.curState = 'ABOUT_TO_RESTORE';
  9894. this.curError = $r('app.string.current_error_hint');
  9895. break;
  9896. case PiPWindow.PiPState.ERROR:
  9897. this.curState = 'ERROR';
  9898. this.curError = reason;
  9899. break;
  9900. default:
  9901. break;
  9902. }
  9903. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  9904. }
  9905. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  9906. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  9907. switch (event) {
  9908. case 'playbackStateChanged':
  9909. if (status === 0) {
  9910. this.pause();
  9911. } else {
  9912. console.info('onecold startPlayOrResumePlay 9869')
  9913. this.startPlayOrResumePlay();
  9914. }
  9915. break;
  9916. case 'nextVideo':
  9917. // 切换到下一个视频
  9918. this.playNext()
  9919. break;
  9920. case 'previousVideo':
  9921. // 切换到上一个视频
  9922. this.playPrevious()
  9923. break;
  9924. case 'previousVideo':
  9925. // 切换到上一个视频
  9926. this.playPrevious()
  9927. break;
  9928. default:
  9929. }
  9930. this.buttonAction = event + `-status:${status}`;
  9931. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  9932. }
  9933. /**
  9934. * 画中画功能(悬浮歌词功能)结束
  9935. *
  9936. */
  9937. async doSearchCover(item: VideoItem): Promise<string> {
  9938. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  9939. this.isShowMoreView = false;
  9940. this.showTipsDialog();
  9941. return ''; // Return empty string when no API is configured
  9942. }
  9943. if (!item) {
  9944. return ''; // Return empty string if item is undefined
  9945. }
  9946. const artist = item?.artist || ''; // Use empty string if artist is missing
  9947. return this.searchCover(item, item.name, artist); // Await is not needed here as we return the promise directly
  9948. }
  9949. /**
  9950. *api搜索封面
  9951. *item,根据title和artist
  9952. */
  9953. searchCover(item: VideoItem, title: string, artist: string): Promise<string> {
  9954. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  9955. LogUtil.debug("onecold res =" + res);
  9956. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  9957. if (item.filePath == this.currentSong?.filePath) {
  9958. this.cover = res;
  9959. if (this.currentSong) {
  9960. this.currentSong.pixelMapPath = res;
  9961. }
  9962. }
  9963. // Update pixel map path but always return res regardless of success
  9964. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  9965. if (success) {
  9966. this.doUpdateData();
  9967. console.log("onecold 更新音乐封面成功,数据库已同步");
  9968. } else {
  9969. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  9970. }
  9971. // Note: We don't resolve/reject here because we already returned res
  9972. });
  9973. LogUtil.debug("onecold this.cover =" + this.cover);
  9974. }
  9975. return res; // Always return res regardless of updatePixelMapPath result
  9976. });
  9977. }
  9978. @State jumpTopTime: number = 0
  9979. @State jumpEndTime: number = 0
  9980. @State isOpenJump: boolean = false
  9981. @Builder
  9982. JumpTopEndSheet() {
  9983. Scroll() {
  9984. Column() {
  9985. Column() {
  9986. Text('仅对本播放列表有效')
  9987. .fontSize(16)
  9988. .fontColor($r('app.color.text_color'))
  9989. // 跳过头尾
  9990. Column() {
  9991. Row() {
  9992. Text('跳过片头:')
  9993. .fontSize(16)
  9994. .fontColor($r('app.color.text_color'))
  9995. Text(this.jumpTopTime + 's')
  9996. .fontSize(16)
  9997. .fontColor($r('app.color.text_color'))
  9998. }
  9999. .margin({ bottom: 5 })
  10000. Row() {
  10001. Slider({
  10002. value: this.jumpTopTime,
  10003. min: 0,
  10004. max: 120,
  10005. step: 1,
  10006. style: SliderStyle.OutSet
  10007. })
  10008. .blockColor(this.themeColor)
  10009. .trackColor($r('app.color.speed_text_color'))
  10010. .selectedColor(Color.White)
  10011. .trackThickness(8)
  10012. .onChange((value: number) => {
  10013. this.jumpTopTime = value;
  10014. })
  10015. .width('85%')
  10016. }
  10017. .alignItems(VerticalAlign.Top)
  10018. }
  10019. .margin({ top: 10, bottom: 10 })
  10020. // 跳过头尾
  10021. Column() {
  10022. Row() {
  10023. Text('跳过片尾:')
  10024. .fontSize(16)
  10025. .fontColor($r('app.color.text_color'))
  10026. Text(this.jumpEndTime + 's')
  10027. .fontSize(16)
  10028. .fontColor($r('app.color.text_color'))
  10029. }
  10030. .margin({ bottom: 5 })
  10031. Row() {
  10032. Slider({
  10033. value: this.jumpEndTime,
  10034. min: 0,
  10035. max: 120,
  10036. step: 1,
  10037. style: SliderStyle.OutSet
  10038. })
  10039. .blockColor(this.themeColor)
  10040. .trackColor($r('app.color.speed_text_color'))
  10041. .selectedColor(Color.White)
  10042. .trackThickness(8)
  10043. .onChange((value: number) => {
  10044. this.jumpEndTime = value;
  10045. })
  10046. .width('85%')
  10047. }
  10048. .alignItems(VerticalAlign.Top)
  10049. }
  10050. .margin({ top: 10, bottom: 10 })
  10051. Row() {
  10052. Button('保存设置')
  10053. .fontColor(Color.White)
  10054. .layoutWeight(1)
  10055. .height(40)
  10056. .width(80)
  10057. .backgroundColor(this.themeColor)
  10058. .stateEffect(true)
  10059. .margin({ left: 0, bottom: 20 })
  10060. .onClick(async () => {
  10061. if (!Utility.isNoble()) {
  10062. this.isJumpSetting = false
  10063. this.isShowMoreView = false
  10064. this.showVipDialog()
  10065. return
  10066. }
  10067. if (this.currentSong === undefined) {
  10068. return
  10069. }
  10070. if (this.modeType === 0) {
  10071. let parentPath = FileUtil.getParentPath(this.videoUrl)
  10072. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  10073. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  10074. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  10075. } else if (this.modeType === 1) { //媒体库
  10076. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  10077. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  10078. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  10079. } else if (this.modeType === 2) { //艺术家
  10080. if (this.currentSong?.artist) {
  10081. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  10082. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  10083. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  10084. }
  10085. } else if (this.modeType === 3) { //专辑
  10086. if (this.currentSong?.album) {
  10087. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  10088. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  10089. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  10090. }
  10091. }
  10092. ToastUtil.showShort("保存成功")
  10093. this.isJumpSetting = false
  10094. })
  10095. }
  10096. .margin({
  10097. left: 38,
  10098. right: 38,
  10099. top: 10,
  10100. bottom: 10
  10101. })
  10102. .width(120)
  10103. .height(50)
  10104. }
  10105. }
  10106. }
  10107. .width('100%')
  10108. .height('100%')
  10109. }
  10110. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  10111. private onStateVastChange(state: AVCastPickerState) {
  10112. if (state == AVCastPickerState.STATE_APPEARING) {
  10113. console.log('The picker starts showing.');
  10114. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  10115. console.log('The picker finishes presenting.');
  10116. }
  10117. }
  10118. private showSelectLyric() {
  10119. DialogHelper.showActionSheetDialog({
  10120. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  10121. // sheets: ["本地歌词", "搜索歌词"],
  10122. sheets: [
  10123. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  10124. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  10125. ],
  10126. maskColor: Color.Transparent,
  10127. backgroundColor: $r('app.color.bg_card'),
  10128. transition: AnimationHelper.transitionInDown(666),
  10129. onAction: (index) => {
  10130. switch (index) {
  10131. case 0:
  10132. this.callFilePickerSelectFileForLyric()
  10133. break;
  10134. case 1:
  10135. if (StrUtil.isNotEmpty(this.videoUrl)) {
  10136. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  10137. this.initLyric(lyricPath);
  10138. }
  10139. break;
  10140. }
  10141. }
  10142. })
  10143. }
  10144. // 拉起picker选择文件管理器
  10145. async callFilePickerSelectFileForLyric(): Promise<void> {
  10146. try {
  10147. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  10148. DocumentSelectOptions.maxSelectNumber = 1
  10149. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  10150. let documentPicker = new picker.DocumentViewPicker();
  10151. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  10152. Logger.info(TAG,
  10153. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  10154. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  10155. this.saveVideoDatasLyric(DocumentSelectResult)
  10156. }
  10157. }).catch((err: BusinessError) => {
  10158. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  10159. });
  10160. } catch (err) {
  10161. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  10162. }
  10163. }
  10164. async saveVideoDatasLyric(uris: string[]) {
  10165. if (ArrayUtil.isEmpty(uris)) {
  10166. return
  10167. }
  10168. let newUris: string[] = [];
  10169. for (let i = 0; i < uris.length; i++) {
  10170. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  10171. Logger.info(TAG, 'filePath uri: ' + filePath);
  10172. newUris.push(filePath)
  10173. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  10174. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  10175. fileIo.copyFileSync(file.fd, file2.fd)
  10176. fileIo.closeSync(file);
  10177. fileIo.closeSync(file2);
  10178. this.initLyric(filePath,false,false,true)
  10179. }
  10180. }
  10181. private initDelayPlay(context: object) {
  10182. this.mContext = context;
  10183. }
  10184. startPipLyric() {
  10185. if (this.pipController) {
  10186. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  10187. PiPWindow.PiPControlStatus.PLAY);
  10188. }
  10189. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  10190. if (this.isOpenPip) {
  10191. this.startPip()
  10192. } else {
  10193. this.stopPip()
  10194. }
  10195. }
  10196. //startOffset 从cue分轨时间开始播
  10197. private startPlayOrResumePlay(startOffset?:number) {
  10198. //针对dsf文件高采样率sampleRate>441000,统一转wav播放
  10199. const sampleRate = this.currentSong?.sampleRate||0
  10200. if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
  10201. console.info('onecold 采样率 ='+sampleRate)
  10202. let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  10203. console.info('onecold newDsfPath ='+newDsfPath)
  10204. if(!FileUtil.accessSync(newDsfPath)){
  10205. const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  10206. taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  10207. this.videoUrl = newDsfPath
  10208. this.startPlay(startOffset)
  10209. }).catch((e:object)=>{
  10210. console.info("task1 catch e: " + e);
  10211. })
  10212. }else{
  10213. this.videoUrl = newDsfPath
  10214. this.startPlay(startOffset)
  10215. }
  10216. }else{
  10217. this.startPlay(startOffset)
  10218. }
  10219. }
  10220. startPlay(startOffset?:number) {
  10221. this.startPipLyric()
  10222. this.mDestroyPage = false;
  10223. this.animationState = AnimationStatus.Running
  10224. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  10225. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  10226. this.stopProgressTask();
  10227. this.startProgressTask();
  10228. this.play(this.videoUrl.toString(),startOffset);
  10229. }
  10230. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  10231. this.mIjkMediaPlayer.start();
  10232. this.setProgress()
  10233. this.CONTROL_PlayStatus = PlayStatus.PLAY
  10234. }
  10235. this.setIsPlaying(true)
  10236. this.updateSessionPlayState(true)
  10237. this.watchStatus();
  10238. this.updateLastPlayTimeStr(this.videoUrl)
  10239. }
  10240. updateLastPlayTimeStr(filePath: string) {
  10241. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  10242. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  10243. if (success) {
  10244. this.getHistoryList(false)
  10245. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  10246. } else {
  10247. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  10248. }
  10249. });
  10250. }
  10251. private completionNum(num: number): string | number {
  10252. if (num < 10) {
  10253. return '0' + num;
  10254. } else {
  10255. return num;
  10256. }
  10257. }
  10258. private stringForTime(timeMs: number): string {
  10259. let totalSeconds: number | string = (timeMs / 1000);
  10260. let newSeconds: number | string = totalSeconds % 60;
  10261. let minutes: number | string = (totalSeconds / 60) % 60;
  10262. let hours: number | string = totalSeconds / 3600;
  10263. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  10264. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  10265. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  10266. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  10267. if (this.isCurrentTime) {
  10268. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  10269. this.oldSeconds = newSeconds
  10270. } else {
  10271. newSeconds = this.oldSeconds
  10272. }
  10273. }
  10274. newSeconds = this.completionNum(newSeconds);
  10275. if (hours > 0) {
  10276. return hours + ":" + minutes + ":" + newSeconds;
  10277. } else {
  10278. return minutes + ":" + newSeconds;
  10279. }
  10280. }
  10281. private setProgress() {
  10282. let position = this.mIjkMediaPlayer.getCurrentPosition();
  10283. let duration = this.mIjkMediaPlayer.getDuration();
  10284. let pos = 0;
  10285. if (duration > 0) {
  10286. this.slideEnable = true;
  10287. let curPercent = position / duration;
  10288. pos = curPercent * 100;
  10289. if (pos > this.PROGRESS_MAX_VALUE) {
  10290. this.progressValue = this.PROGRESS_MAX_VALUE
  10291. } else {
  10292. this.progressValue = pos;
  10293. }
  10294. }
  10295. // LogUtils.getInstance()
  10296. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  10297. this.totalTime = this.stringForTime(duration);
  10298. if (position > duration) {
  10299. position = duration;
  10300. }
  10301. this.isCurrentTime = true;
  10302. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  10303. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  10304. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  10305. this.currentTime = this.stringForTime(position);
  10306. this.isCurrentTime = false
  10307. if (this.mIjkMediaPlayer.isPlaying()) {
  10308. this.randomColor =
  10309. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  10310. //如果是开启AB循环
  10311. if(this.isOpenAB){
  10312. if(position >=this.jumpBTime){
  10313. this.seekTo(this.jumpATime+'')
  10314. return
  10315. }
  10316. }
  10317. // 判断是否播放到结束时间
  10318. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  10319. if (position >= duration - this.jumpEndTime * 1000) {
  10320. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  10321. this.CONTROL_PlayStatus = PlayStatus.INIT
  10322. this.startPlayOrResumePlay();
  10323. }else if (this.playType == 2) { //2:正常播放,单曲播完
  10324. this.showRePlay();
  10325. this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
  10326. this.progressValue = this.PROGRESS_MAX_VALUE;
  10327. this.slideEnable = false;
  10328. this.stop();
  10329. // ToastUtil.showToast('开始重新播放')
  10330. }else{
  10331. this.playNext()
  10332. }
  10333. }
  10334. }
  10335. } else {
  10336. this.randomColor = 'rbg(0,0,0)'
  10337. }
  10338. }
  10339. private startProgressTask() {
  10340. let that = this;
  10341. this.updateProgressTimer = setInterval(() => {
  10342. //LogUtils.getInstance().LOGI("startProgressTask");
  10343. if (!that.mDestroyPage) {
  10344. that.setProgress();
  10345. }
  10346. }, 300);
  10347. }
  10348. private stopProgressTask() {
  10349. LogUtils.getInstance().LOGI("stopProgressTask");
  10350. clearInterval(this.updateProgressTimer);
  10351. }
  10352. private showLoadIng() {
  10353. this.loadingVisible = Visibility.Visible;
  10354. this.replayVisible = Visibility.None;
  10355. }
  10356. private hideLoadIng() {
  10357. this.loadingVisible = Visibility.None;
  10358. this.replayVisible = Visibility.None;
  10359. }
  10360. private showRePlay() {
  10361. this.loadingVisible = Visibility.None;
  10362. this.replayVisible = Visibility.Visible;
  10363. }
  10364. private async play(url: string,startOffset?:number) {
  10365. let that = this;
  10366. that.showLoadIng();
  10367. this.isOpenAB = false
  10368. //设置XComponent回调的context
  10369. if (!!this.mContext) {
  10370. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  10371. }
  10372. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  10373. this.mIjkMediaPlayer.reset();
  10374. }
  10375. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  10376. //设置debug模式
  10377. this.mIjkMediaPlayer.setDebug(false);
  10378. //初始化配置
  10379. this.mIjkMediaPlayer.native_setup();
  10380. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  10381. if(this.volumeSmall){
  10382. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  10383. this.mIjkMediaPlayer.setVolume('1', '1');
  10384. }else{
  10385. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  10386. }
  10387. }else{
  10388. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  10389. }
  10390. //设置视频源
  10391. this.mIjkMediaPlayer.setDataSource(url);
  10392. //设置视频源http请求头
  10393. let headers = new Map([
  10394. ["user_agent", "Mozilla/5.0 BiliDroid/7.30.0 (bbcallen@gmail.com)"],
  10395. ["referer", "https://www.bilibili.com"]
  10396. ]);
  10397. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  10398. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  10399. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  10400. // }
  10401. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  10402. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  10403. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  10404. const fileSize = await this.getFileSize(this.videoUrl);
  10405. let bufferSize = 1 * 1024 ; // 默认缓冲区大小为1MB
  10406. if (fileSize > 3 * 1024 * 1024 * 1024) { // 文件大于3GB
  10407. bufferSize = 25 * 1024 * 1024; // 设置缓冲区大小为25MB
  10408. }
  10409. // 使用软件解码(通常比硬件解码更节省内存)
  10410. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", '0');
  10411. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", '0');
  10412. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", '1024');
  10413. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzeduration", '500000');
  10414. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  10415. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  10416. //停止预读的最小帧数
  10417. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  10418. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  10419. // 设置其他缓冲相关选项
  10420. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  10421. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  10422. //启动预加载
  10423. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  10424. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  10425. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  10426. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  10427. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  10428. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  10429. // 因此需要播放器丢包,才不会累积延时
  10430. // 这个和第三个参数packet-buffering无关。
  10431. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  10432. // 无限制收流
  10433. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  10434. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  10435. // 屏幕常亮
  10436. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  10437. // 设置超时
  10438. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  10439. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  10440. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  10441. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  10442. // 变速播放
  10443. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  10444. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  10445. let Speed = this.mIjkMediaPlayer.getSpeed()
  10446. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  10447. //是否开启循环播放
  10448. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  10449. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  10450. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  10451. if (height === 0) {
  10452. return;
  10453. }
  10454. const va = width / height;
  10455. const vpa = that.videoParentAspectRatio;
  10456. if (vpa > va) {
  10457. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  10458. } else {
  10459. that.videoWidth = '100%';
  10460. }
  10461. if (width && height) {
  10462. that.videoAspectRatio = width / height;
  10463. }
  10464. LogUtils.getInstance()
  10465. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  10466. that.hideLoadIng();
  10467. }
  10468. }
  10469. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  10470. let mOnPreparedListener: OnPreparedListener = {
  10471. onPrepared: async () => {
  10472. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  10473. try {
  10474. // this.cover = this.songList[this.curIndex].pixelMapPath
  10475. // this.artist = this.songList[this.curIndex].artist
  10476. // this.videoUrl = this.songList[this.curIndex].filePath
  10477. let isBgCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  10478. if (isBgCover && this.cover !== undefined && StrUtil.isNotEmpty(this.cover)) {
  10479. this.setImageColor2(this.cover)
  10480. } else {
  10481. this.getImageColor();
  10482. }
  10483. //保存碰一碰分享的当前的歌曲
  10484. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  10485. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  10486. await this.initLyric(lyricPath);
  10487. setTimeout(() => {
  10488. this.avSessionController.initAvSession(false);
  10489. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  10490. this.setAvSessionListener();
  10491. this.updateSessionPlayState(true)
  10492. this.setCurrentPlayMode()
  10493. }, 500)
  10494. if(startOffset&&startOffset>0){//cue分轨播放
  10495. this.seekTo(startOffset + "");
  10496. this.saveLastPlayList()
  10497. return
  10498. }
  10499. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  10500. let timeoutPlay = 0
  10501. if (StrUtil.isNotEmpty(this.videoUrl) &&
  10502. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  10503. timeoutPlay = 1000
  10504. }
  10505. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  10506. if (this.modeType === 0) { //文件夹
  10507. let parentPath = FileUtil.getParentPath(this.videoUrl)
  10508. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  10509. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  10510. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  10511. } else if (this.modeType === 1) { //媒体库
  10512. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  10513. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  10514. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  10515. } else if (this.modeType === 2) { //艺术家
  10516. if (this.currentSong?.artist) {
  10517. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  10518. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  10519. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  10520. }
  10521. } else if (this.modeType === 3) { //专辑
  10522. if (this.currentSong?.album) {
  10523. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  10524. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  10525. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  10526. }
  10527. }
  10528. this.duration = this.mIjkMediaPlayer.getDuration()
  10529. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  10530. if (this.mIjkMediaPlayer != null) {
  10531. let jumpTopTimeMs = this.jumpTopTime*1000;
  10532. if (jumpTopTimeMs <= this.duration) {
  10533. // 调用 seekTo 方法,跳到指定时间
  10534. if(PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY,true)){
  10535. console.log('onecold jumpTopTime = '+jumpTopTimeMs);
  10536. const position:number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  10537. console.log('onecold position = '+position);
  10538. if (position > jumpTopTimeMs) {
  10539. jumpTopTimeMs = position
  10540. }
  10541. }
  10542. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  10543. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  10544. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  10545. }
  10546. }, timeoutPlay)
  10547. } else {
  10548. // 提示用户无法跳过
  10549. ToastUtil.showToast('跳过时间超过视频时长');
  10550. }
  10551. }
  10552. } else {
  10553. this.jumpTopTime = 0
  10554. this.jumpEndTime = 0
  10555. console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  10556. console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  10557. console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  10558. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  10559. //记忆播放(每一首都会记忆播放)
  10560. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  10561. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  10562. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  10563. this.restorePlaybackPosition() //读取播放记忆功能
  10564. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  10565. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  10566. this.restorePlaybackPosition() //读取播放记忆功能
  10567. }
  10568. this.isFirstStartPlay = false
  10569. }, timeoutPlay)
  10570. } else {
  10571. this.isFirstStartPlay = false
  10572. }
  10573. }
  10574. this.saveLastPlayList()
  10575. } catch (error) {
  10576. let err: BusinessError = error as BusinessError;
  10577. console.error('onecold failed with err: ' + JSON.stringify(err));
  10578. }
  10579. }
  10580. }
  10581. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  10582. let mOnTimedTextListener: OnTimedTextListener = {
  10583. onTimedText: () => {
  10584. }
  10585. }
  10586. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  10587. let mOnCompletionListener: OnCompletionListener = {
  10588. onCompletion: () => {
  10589. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  10590. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  10591. this.playNext()
  10592. } else if (this.playType == 1) { //1:单片重复播放
  10593. this.CONTROL_PlayStatus = PlayStatus.INIT
  10594. console.info('onecold startPlayOrResumePlay 10592')
  10595. that.startPlayOrResumePlay();
  10596. } else if (this.playType == 2) { //2:正常播放,单曲播完
  10597. that.showRePlay();
  10598. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  10599. that.progressValue = this.PROGRESS_MAX_VALUE;
  10600. that.slideEnable = false;
  10601. that.stop();
  10602. // ToastUtil.showToast('开始重新播放')
  10603. } else if (this.playType == 3) { //3:随机播放
  10604. this.randomPlay()
  10605. }
  10606. }
  10607. }
  10608. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  10609. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  10610. onBufferingUpdate: (percent: number) => {
  10611. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  10612. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  10613. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  10614. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  10615. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  10616. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  10617. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  10618. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  10619. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  10620. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  10621. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  10622. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  10623. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  10624. let Looping = this.mIjkMediaPlayer.isLooping()
  10625. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  10626. }
  10627. }
  10628. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  10629. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  10630. onSeekComplete: () => {
  10631. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  10632. console.info('onecold startPlayOrResumePlay 10643')
  10633. that.startPlayOrResumePlay();
  10634. }
  10635. }
  10636. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  10637. let mOnInfoListener: OnInfoListener = {
  10638. onInfo: (what: number, extra: number) => {
  10639. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  10640. that.hideLoadIng();
  10641. }
  10642. }
  10643. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  10644. let mOnErrorListener: OnErrorListener = {
  10645. onError: (what: number, extra: number) => {
  10646. this.stopProgressTask();
  10647. LogUtils.getInstance().LOGI("OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  10648. that.hideLoadIng();
  10649. if (StrUtil.isNotEmpty(this.videoUrl) && !FileUtil.accessSync(this.videoUrl)) {
  10650. ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
  10651. } else {
  10652. ToastUtil.showToast(getContext()
  10653. .resourceManager
  10654. .getStringByNameSync("Honey_the_video_is_playing_errant_The_system_is_wandering"))
  10655. }
  10656. }
  10657. }
  10658. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  10659. this.mIjkMediaPlayer.setMessageListener();
  10660. this.mIjkMediaPlayer.prepareAsync();
  10661. this.mIjkMediaPlayer.start();
  10662. }
  10663. //保存最后播放的那首歌和已经对应的播放列表
  10664. saveLastPlayList() {
  10665. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  10666. PreferencesUtil.putSync('LastMusicList', this.songList)
  10667. }
  10668. // 清空播放记录
  10669. clearVideoHistory() {
  10670. this.table.clearPlayHistory((success: boolean, error?: string) => {
  10671. if (success) {
  10672. this.historyList = [];
  10673. this.updateListData(this.historyList)
  10674. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  10675. ToastUtil.showToast('清空播放记录成功')
  10676. } else {
  10677. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  10678. }
  10679. });
  10680. }
  10681. public async setAvSessionListener() {
  10682. if (!this.avSessionController) {
  10683. return;
  10684. }
  10685. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  10686. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  10687. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  10688. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  10689. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  10690. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  10691. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  10692. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  10693. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  10694. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  10695. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  10696. }
  10697. setLoopMode() {
  10698. let itype = this.playType + 1
  10699. if (itype >= 4) {
  10700. this.playType = 0
  10701. ToastUtil.showToast('连续播放')
  10702. } else if (itype === 1) {
  10703. this.playType = 1
  10704. ToastUtil.showToast('单曲循环')
  10705. } else if (itype === 2) {
  10706. this.playType = 2
  10707. ToastUtil.showToast('单曲播完')
  10708. } else if (itype === 3) {
  10709. this.playType = 3
  10710. ToastUtil.showToast('随机播放')
  10711. } else if (itype === 0) {
  10712. this.playType = 0
  10713. ToastUtil.showToast('连续播放')
  10714. }
  10715. PreferencesUtil.putSync('musicPlayType', this.playType)
  10716. this.setCurrentPlayMode()
  10717. }
  10718. private sessionSetLoopModeCallback = (mode: number) => {
  10719. if (this.mIjkMediaPlayer != null) {
  10720. ToastUtil.showToast('当前播放模式:' + mode)
  10721. Logger.info('onecold 当前播放模式= ' + mode)
  10722. let hmPlayMode = mode + 1
  10723. if (hmPlayMode >= 4) {
  10724. hmPlayMode = 0
  10725. }
  10726. if (hmPlayMode === 1) {
  10727. this.playType = 1
  10728. ToastUtil.showToast('单曲循环')
  10729. } else if (hmPlayMode === 0) {
  10730. this.playType = 2
  10731. ToastUtil.showToast('单曲播完')
  10732. } else if (hmPlayMode === 3) {
  10733. this.playType = 3
  10734. ToastUtil.showToast('随机播放')
  10735. } else if (hmPlayMode === 2) {
  10736. this.playType = 0
  10737. ToastUtil.showToast('连续播放')
  10738. }
  10739. PreferencesUtil.putSync('musicPlayType', this.playType)
  10740. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  10741. let playBackState: avSession.AVPlaybackState = {
  10742. loopMode: hmPlayMode,
  10743. };
  10744. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  10745. console.info(`set setLoopMode AVPlaybackState successfully`);
  10746. }).catch((err: BusinessError) => {
  10747. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  10748. });
  10749. }
  10750. }
  10751. setCurrentPlayMode() {
  10752. if (!this.avSessionController) {
  10753. return;
  10754. }
  10755. let mLoopMode = 0
  10756. switch (this.playType) {
  10757. case 0:
  10758. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  10759. break;
  10760. case 1:
  10761. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  10762. break;
  10763. case 2:
  10764. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  10765. break;
  10766. case 3:
  10767. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  10768. break;
  10769. }
  10770. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  10771. let playBState: avSession.AVPlaybackState = {
  10772. loopMode: mLoopMode,
  10773. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  10774. };
  10775. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  10776. console.info(`set setLoopMode AVPlaybackState successfully`);
  10777. }).catch((err: BusinessError) => {
  10778. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  10779. });
  10780. }
  10781. private sessionToggleFavoriteCallback = (assetId: string) => {
  10782. if (this.mIjkMediaPlayer != null && this.currentSong) {
  10783. console.info(`on toggleFavorite `);
  10784. // 应用收到收藏命令,进行收藏处理。
  10785. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  10786. this.doFav(this.currentSong)
  10787. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  10788. let playbackState: avSession.AVPlaybackState = {
  10789. isFavorite: !this.isFac,
  10790. };
  10791. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  10792. console.info(`SetAVPlaybackState successfully`);
  10793. }).catch((err: BusinessError) => {
  10794. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  10795. });
  10796. }
  10797. }
  10798. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  10799. device: avSession.OutputDeviceInfo) => {
  10800. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  10801. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  10802. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  10803. await this.startCasting();
  10804. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  10805. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  10806. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  10807. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  10808. if (device) {
  10809. this.endCasting();
  10810. }
  10811. }
  10812. };
  10813. private async startCasting() {
  10814. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  10815. this.setPlaybackStateChangeListener();
  10816. this.pause();
  10817. this.initQueueItem();
  10818. this.prepare();
  10819. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  10820. refToIsCasting?.set(true);
  10821. this.castSeek = true;
  10822. this.isCastPlaying = true;
  10823. }
  10824. async changeCasting() {
  10825. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  10826. this.initQueueItem();
  10827. this.prepare();
  10828. this.setPlaybackStateChangeListener();
  10829. this.isCastPlaying = true;
  10830. this.castSeek = true;
  10831. }
  10832. public endCasting() {
  10833. this.avSessionController.getAvSession()?.stopCasting();
  10834. this.stopCast();
  10835. this.isCastPlaying = false;
  10836. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  10837. refToIsCasting?.set(false);
  10838. this.pause();
  10839. this.setIsPlaying(false);
  10840. // if (this.curIndex === this.curSource.index) {
  10841. // this.play
  10842. // this.seek(this.currentTime * 1000);
  10843. // this.setIsPlaying(true);
  10844. // } else {
  10845. // this.pauseVideo();
  10846. // this.setIsPlaying(false);
  10847. // }
  10848. }
  10849. public setIsPlaying(isPlayer: boolean) {
  10850. this.isPlaying = isPlayer;
  10851. // 发送播放状态变化事件给歌单详情页面
  10852. try {
  10853. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  10854. const currentFilePath = this.currentSong?.filePath || ''
  10855. const eventData: emitter.EventData = {
  10856. data: {
  10857. isPlaying: this.isPlaying,
  10858. curIndex: this.curIndex,
  10859. currentFilePath: currentFilePath
  10860. }
  10861. };
  10862. emitter.emit(eventPlaybackStatus, eventData)
  10863. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  10864. } catch (error) {
  10865. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  10866. }
  10867. }
  10868. private setPlaybackStateChangeListener(): void {
  10869. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  10870. this.castController?.on('endOfStream', this.reloadCasting);
  10871. this.castController?.on('playNext', this.playNextCallback);
  10872. this.castController?.on('playPrevious', this.playPreviousCallback);
  10873. }
  10874. private updateSessionPlayState(isPlay: boolean): void {
  10875. // if(!this.isBgPlayOpen)
  10876. // return
  10877. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  10878. this.setAVSessionPlayState({
  10879. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  10880. position: {
  10881. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  10882. updateTime: new Date().getTime()
  10883. }
  10884. });
  10885. }
  10886. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  10887. this.avSessionController.setAvSessionPlayState(playbackState)
  10888. }
  10889. private positionChange(position: number) {
  10890. this.currentTime2 = position / 1000;
  10891. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  10892. }
  10893. private playDurationChange(duration: number) {
  10894. this.duration = duration;
  10895. this.durationTime = Math.floor(this.duration / 1000);
  10896. this.durationStringTime = secondToTime((this.durationTime));
  10897. }
  10898. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  10899. const duration = playbackState?.extras?.duration;
  10900. if (typeof duration === 'number') {
  10901. this.playDurationChange(duration as number);
  10902. }
  10903. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  10904. this.positionChange(playbackState?.position?.elapsedTime);
  10905. }
  10906. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  10907. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  10908. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  10909. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  10910. this.isCastPlaying = false;
  10911. }
  10912. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  10913. this.isCastPlaying = true;
  10914. }
  10915. };
  10916. private reloadCasting = async () => {
  10917. let item = this.songList[this.curIndex];
  10918. let uri = fileUri.getUriFromPath(item.filePath);
  10919. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  10920. // description.startPosition = 0;
  10921. this.castItem = {
  10922. itemId: this.curIndex,
  10923. description: {
  10924. assetId: item.filePath,
  10925. title: item.name,
  10926. artist: '',
  10927. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  10928. // mediaUri: item.filePath,
  10929. fdSrc: {
  10930. fd: file.fd
  10931. },
  10932. // 该字段大写,音频'AUDIO',视频'VIDEO'
  10933. mediaType: 'VIDEO',
  10934. mediaSize: item.videoSize,
  10935. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  10936. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  10937. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  10938. duration: this.duration,
  10939. // albumCoverUri: 'https://www.example.jpeg',
  10940. // albumTitle: '《ExampleAlbum》',
  10941. appName: this.appName,
  10942. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  10943. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  10944. }
  10945. };
  10946. this.prepare();
  10947. this.isCastPlaying = true;
  10948. };
  10949. public playNextCallback = (): void => {
  10950. this.playNext()
  10951. };
  10952. public playPreviousCallback = (): void => {
  10953. this.playPrevious()
  10954. };
  10955. async prepare() {
  10956. await this.castController?.prepare(this.castItem);
  10957. await this.castController?.start(this.castItem);
  10958. }
  10959. public initQueueItem() {
  10960. let item = this.songList[this.curIndex];
  10961. let time = this.currentTime;
  10962. let uri = fileUri.getUriFromPath(item.filePath);
  10963. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  10964. this.castItem = {
  10965. itemId: this.curIndex,
  10966. description: {
  10967. assetId: item.filePath,
  10968. title: item.name,
  10969. artist: '',
  10970. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  10971. fdSrc: {
  10972. fd: file.fd
  10973. },
  10974. // 该字段大写,音频'AUDIO',视频'VIDEO'
  10975. mediaType: 'AUDIO',
  10976. mediaSize: item.videoSize,
  10977. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  10978. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  10979. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  10980. duration: this.duration,
  10981. // albumCoverUri: 'https://www.example.jpeg',
  10982. // albumTitle: '《ExampleAlbum》',
  10983. appName: this.appName,
  10984. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  10985. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  10986. }
  10987. };
  10988. }
  10989. async stopCast() {
  10990. try {
  10991. this.castController?.off('playbackStateChange');
  10992. this.castController?.off('endOfStream');
  10993. this.castController?.off('playNext');
  10994. this.castController?.off('playPrevious');
  10995. this.castController?.off('error');
  10996. } catch (error) {
  10997. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  10998. }
  10999. }
  11000. private sessionPlayCallback = (): void => {
  11001. console.info('onecold playOrPause 11050')
  11002. this.playOrPause()
  11003. };
  11004. private sessionPauseCallback = (): void => {
  11005. console.info('onecold playOrPause 11054')
  11006. this.pause()
  11007. };
  11008. private playOrPause() {
  11009. if (!this.debounce()) {
  11010. return;
  11011. }
  11012. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  11013. this.pause();
  11014. } else {
  11015. console.info('onecold startPlayOrResumePlay 11064')
  11016. this.startPlayOrResumePlay();
  11017. this.playChange()
  11018. }
  11019. }
  11020. private sessionPlayNextCallback = (): void => {
  11021. this.playNext()
  11022. };
  11023. private sessionPlayPreviousCallback = (): void => {
  11024. this.playPrevious()
  11025. };
  11026. private sessionStopCallback = (): void => {
  11027. this.stop()
  11028. };
  11029. private sessionFastForwardCallback = (time?: number) => {
  11030. if (!time) {
  11031. return;
  11032. }
  11033. if (this.mIjkMediaPlayer != null) {
  11034. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  11035. let seeTime = curPosition + time * 1000;
  11036. // 限制 seekValue 在合法范围内
  11037. if (seeTime < 0) {
  11038. seeTime = 0;
  11039. } else if (seeTime > this.duration) {
  11040. seeTime = this.duration;
  11041. }
  11042. Logger.info('onecold seeTime= ' + seeTime)
  11043. this.setSeekToActionProgress(seeTime)
  11044. this.seekTo(seeTime + "")
  11045. }
  11046. };
  11047. /**
  11048. * Gesture method onActionUpdate.
  11049. *
  11050. * @param event Gesture event.手势拖动设置快进和后退
  11051. */
  11052. private setSeekToActionProgress(position: number) {
  11053. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  11054. let duration = this.mIjkMediaPlayer.getDuration();
  11055. let pos = 0;
  11056. if (duration > 0) {
  11057. this.slideEnable = true;
  11058. let curPercent = position / duration;
  11059. pos = curPercent * 100;
  11060. if (pos > this.PROGRESS_MAX_VALUE) {
  11061. this.progressValue = this.PROGRESS_MAX_VALUE
  11062. } else {
  11063. this.progressValue = pos;
  11064. }
  11065. }
  11066. // LogUtils.getInstance()
  11067. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  11068. this.totalTime = this.stringForTime(duration);
  11069. if (position > duration) {
  11070. position = duration;
  11071. }
  11072. this.isCurrentTime = true;
  11073. this.currentTime = this.stringForTime(position);
  11074. this.isCurrentTime = false
  11075. }
  11076. private sessionRewindCallback = (time?: number) => {
  11077. if (!time) {
  11078. return;
  11079. }
  11080. if (this.mIjkMediaPlayer != null) {
  11081. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  11082. let seeTime = curPosition - time * 1000;
  11083. // 限制 seekValue 在合法范围内
  11084. if (seeTime < 0) {
  11085. seeTime = 0;
  11086. } else if (seeTime > this.duration) {
  11087. seeTime = this.duration;
  11088. }
  11089. Logger.info('onecold seeTime= ' + seeTime)
  11090. this.setSeekToActionProgress(seeTime)
  11091. this.seekTo(seeTime + "")
  11092. }
  11093. };
  11094. private sessionSeekCallback = (seekTime: number) => {
  11095. if (this.mIjkMediaPlayer != null) {
  11096. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  11097. this.seekTo(seekTime + "")
  11098. }
  11099. };
  11100. private async getFileSize(filePath: string): Promise<number> {
  11101. try {
  11102. const stat = await fs.stat(filePath);
  11103. return stat.size;
  11104. } catch (err) {
  11105. console.error('Failed to get file size: ' + err.message);
  11106. return 0;
  11107. }
  11108. }
  11109. private pause() {
  11110. if (this.mIjkMediaPlayer.isPlaying()) {
  11111. this.savePlaybackPosition();
  11112. this.mIjkMediaPlayer.pause();
  11113. this.setProgress();
  11114. this.mDestroyPage = true;
  11115. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  11116. this.updateSessionPlayState(false)
  11117. this.playChange()
  11118. if (this.pipController) {
  11119. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  11120. PiPWindow.PiPControlStatus.PAUSE);
  11121. }
  11122. }
  11123. }
  11124. private stop() {
  11125. this.savePlaybackPosition();
  11126. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11127. this.mIjkMediaPlayer.stop();
  11128. this.mIjkMediaPlayer.release();
  11129. this.stopProgressTask();
  11130. this.updateSessionPlayState(false)
  11131. this.playChange()
  11132. this.watchStatus();
  11133. }
  11134. //保持记忆播放功能
  11135. private savePlaybackPosition() {
  11136. if (this.mIjkMediaPlayer != null) {
  11137. const position = this.mIjkMediaPlayer.getCurrentPosition();
  11138. // ToastUtil.showToast('保存记忆播放 = ' + position)
  11139. const duration = this.mIjkMediaPlayer.getDuration();
  11140. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  11141. // 如果播放位置接近视频末尾,则保存 position 为 0
  11142. const playbackPosition = (duration - position < threshold) ? 0 : position;
  11143. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  11144. }
  11145. }
  11146. //获取记忆播放功能
  11147. private restorePlaybackPosition() {
  11148. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  11149. // ToastUtil.showToast('position = ' + position)
  11150. if (this.mIjkMediaPlayer != null && position > 0) {
  11151. // ToastUtil.showToast('seekTo = ' + position)
  11152. this.seekTo(position + "");
  11153. }
  11154. }
  11155. private seekTo(value: string) {
  11156. if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  11157. ToastUtil.showToast('wma格式不支持拖动快进。')
  11158. return
  11159. }
  11160. this.isSeekTo = true
  11161. this.mIjkMediaPlayer.seekTo(value);
  11162. console.info('onecold startPlayOrResumePlay 11227')
  11163. // this.startPlayOrResumePlay()
  11164. // 在这里恢复计时器状态
  11165. this.setProgress()
  11166. this.isSeekTo = false
  11167. }
  11168. // 添加到下一首播放
  11169. private addToNextPlay(song: VideoItem) {
  11170. if (!this.debounce()) {
  11171. return;
  11172. }
  11173. if (this.currentSong) {
  11174. if (this.currentSong === song) {
  11175. ToastUtil.showToast('当前已经在播放这首歌了!')
  11176. return
  11177. }
  11178. }
  11179. // 如果未开始播放或队列为空
  11180. if (this.curIndex === -1 || this.songList.length === 0) {
  11181. this.songList = [song];
  11182. this.curIndex = 0;
  11183. this.doPlay(song)
  11184. return;
  11185. }
  11186. // 插入到当前索引+1的位置
  11187. const insertPos = this.curIndex + 1;
  11188. this.songList.splice(insertPos, 0, song);
  11189. this.songList = [...this.songList]; // 触发状态更新
  11190. this.sonDataSource.pushArrayData(this.songList)
  11191. ToastUtil.showToast('已添加至下一首播放')
  11192. }
  11193. //后退10s,可再设置设置默认几秒
  11194. backForward() {
  11195. if(this.mIjkMediaPlayer){
  11196. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  11197. let value = pos - Number(this.fastForwardSeconds) * 1000;
  11198. this.seekTo(value+"");
  11199. }
  11200. }
  11201. //快进10s,可再设置设置默认几秒
  11202. fastForward() {
  11203. if(this.mIjkMediaPlayer){
  11204. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  11205. let value = pos + Number(this.fastForwardSeconds) * 1000;
  11206. this.seekTo(value+"");
  11207. }
  11208. }
  11209. //下一个
  11210. private playNext() {
  11211. if (!this.debounce()) {
  11212. return;
  11213. }
  11214. if (this.playType == 3) { //3:随机播放
  11215. this.randomPlay()
  11216. return;
  11217. }
  11218. if (ArrayUtil.isNotEmpty(this.songList)) {
  11219. if (this.curIndex == this.songList.length - 1) {
  11220. this.curIndex = 0;
  11221. } else {
  11222. this.curIndex++;
  11223. }
  11224. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11225. this.stop();
  11226. this.currentSong = this.songList[this.curIndex]
  11227. this.videoUrl = this.songList[this.curIndex].filePath;
  11228. this.artist = this.songList[this.curIndex].artist
  11229. this.name = this.songList[this.curIndex].name
  11230. //this.cover = this.songList[this.curIndex].pixelMapPath
  11231. this.changeImageAnimation()
  11232. }
  11233. }
  11234. changeImageAnimation() {
  11235. if(this.openSkipSongAnimate){
  11236. // 第一步:淡出动画
  11237. this.getUIContext()?.animateTo({
  11238. duration: 500,
  11239. curve: Curve.EaseOut,
  11240. }, () => {
  11241. this.opacityValueImage = 0.1;
  11242. if(this.isCoverRectangle){
  11243. this.scaleValueImage = 0.88
  11244. }
  11245. });
  11246. // 第二步:切换图片后淡入
  11247. setTimeout(() => {
  11248. this.cover = this.songList[this.curIndex].pixelMapPath
  11249. this.getUIContext()?.animateTo({
  11250. duration: 500,
  11251. curve: Curve.EaseIn,
  11252. }, () => {
  11253. this.opacityValueImage = 1;
  11254. this.scaleValueImage = 1 // 图标恢复到原始大小
  11255. this.startPlayOrResumePlay()
  11256. });
  11257. }, 500);
  11258. }else{
  11259. this.cover = this.songList[this.curIndex].pixelMapPath
  11260. this.startPlayOrResumePlay()
  11261. }
  11262. }
  11263. // 存储已播放的歌曲索引
  11264. private playedIndices: Set<number> = new Set();
  11265. //随机播放
  11266. private randomPlay() {
  11267. // if (!this.debounce()) {
  11268. // return;
  11269. // }
  11270. if (ArrayUtil.isNotEmpty(this.songList)) {
  11271. if (this.songList.length > 3) {
  11272. // 如果所有歌曲都播放过一次,清空已播放索引集合
  11273. if (this.playedIndices.size === this.songList.length) {
  11274. this.playedIndices.clear();
  11275. }
  11276. // 随机选择一个未播放的歌曲索引
  11277. let newIndex: number;
  11278. // 添加超时机制防止无限循环
  11279. let attempt = 0;
  11280. const maxAttempts = 100; // 根据需求调整
  11281. do {
  11282. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  11283. attempt++;
  11284. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  11285. if (attempt >= maxAttempts) {
  11286. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  11287. newIndex = Math.floor(Math.random() * this.songList.length);
  11288. }
  11289. this.curIndex = newIndex;
  11290. this.playedIndices.add(newIndex);
  11291. } else {
  11292. // 当歌曲数量小于或等于3时,直接播放下一首
  11293. if (this.curIndex == this.songList.length - 1) {
  11294. this.curIndex = 0;
  11295. } else {
  11296. this.curIndex++;
  11297. }
  11298. }
  11299. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11300. this.stop();
  11301. this.currentSong = this.songList[this.curIndex];
  11302. this.videoUrl = this.songList[this.curIndex].filePath;
  11303. this.name = this.songList[this.curIndex].name;
  11304. this.artist = this.songList[this.curIndex].artist
  11305. // this.cover = this.songList[this.curIndex].pixelMapPath
  11306. this.changeImageAnimation()
  11307. }
  11308. }
  11309. private playIndex(index: number) {
  11310. if (!this.debounce()) {
  11311. return;
  11312. }
  11313. if (ArrayUtil.isNotEmpty(this.songList)) {
  11314. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11315. this.stop();
  11316. this.currentSong = this.songList[this.curIndex]
  11317. this.videoUrl = this.songList[index].filePath;
  11318. this.name = this.songList[index].name
  11319. this.artist = this.songList[this.curIndex].artist
  11320. this.curIndex = index;
  11321. this.changeImageAnimation()
  11322. }
  11323. }
  11324. //上一个
  11325. private playPrevious() {
  11326. if (!this.debounce()) {
  11327. return;
  11328. }
  11329. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  11330. this.randomModePlayFromHistory()
  11331. return;
  11332. }
  11333. if (this.curIndex == 0) {
  11334. this.curIndex = this.songList.length - 1;
  11335. } else {
  11336. this.curIndex--;
  11337. }
  11338. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11339. this.stop();
  11340. this.currentSong = this.songList[this.curIndex]
  11341. this.videoUrl = this.songList[this.curIndex].filePath;
  11342. this.name = this.songList[this.curIndex].name
  11343. this.artist = this.songList[this.curIndex].artist
  11344. this.changeImageAnimation()
  11345. }
  11346. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  11347. private randomModePlayFromHistory() {
  11348. if (this.historyList.length >= 2) {
  11349. // 播放历史记录的第二首
  11350. const prevSong = this.historyList[1];
  11351. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  11352. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11353. this.stop();
  11354. this.currentSong = prevSong;
  11355. this.videoUrl = prevSong.filePath;
  11356. this.cover = prevSong.pixelMapPath
  11357. this.artist = prevSong.artist
  11358. this.name = prevSong.name;
  11359. console.info('onecold startPlayOrResumePlay 11434')
  11360. this.startPlayOrResumePlay();
  11361. } else {
  11362. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  11363. if (this.curIndex === 0) {
  11364. this.curIndex = this.songList.length - 1;
  11365. } else {
  11366. this.curIndex--;
  11367. }
  11368. this.CONTROL_PlayStatus = PlayStatus.INIT;
  11369. this.stop();
  11370. this.currentSong = this.songList[this.curIndex];
  11371. this.videoUrl = this.songList[this.curIndex].filePath;
  11372. this.artist = this.songList[this.curIndex].artist
  11373. this.name = this.songList[this.curIndex].name;
  11374. this.changeImageAnimation()
  11375. }
  11376. }
  11377. debounce() {
  11378. const delay = 600;
  11379. let cur = new Date().getTime();
  11380. if (cur - this.last > delay) {
  11381. this.last = cur;
  11382. return true;
  11383. }
  11384. return false;
  11385. }
  11386. /**
  11387. * Sets whether the screen is a constant based on the playback status.
  11388. */
  11389. watchStatus() {
  11390. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  11391. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  11392. this.windowClass.setWindowKeepScreenOn(true);
  11393. } else {
  11394. this.windowClass.setWindowKeepScreenOn(false);
  11395. }
  11396. }
  11397. /**
  11398. * Volume gesture method onActionStart.
  11399. *
  11400. * @param event Gesture event.
  11401. */
  11402. private customDialogComponentIdMM: number = 0
  11403. @Builder
  11404. customDialogComponentMM() {
  11405. Column() {
  11406. Row() {
  11407. Blank()
  11408. Text('验证密码')
  11409. .fontSize(22)
  11410. .fontColor($r('app.color.pri_bg'))
  11411. .margin({ top: 18 })
  11412. Blank()
  11413. Image($r('app.media.close'))
  11414. .fillColor(Color.White)
  11415. .margin({ top: 18, right: 18 })
  11416. .width(20)
  11417. .onClick(() => {
  11418. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  11419. })
  11420. }
  11421. .width('100%') // 使Row占据整个宽度
  11422. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  11423. Verify({
  11424. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  11425. });
  11426. }.height('60%')
  11427. .backgroundColor($r('app.color.index_background'))
  11428. .justifyContent(FlexAlign.SpaceBetween)
  11429. }
  11430. private handleVerifyCompleted(isSuccess: boolean) {
  11431. if (isSuccess) {
  11432. console.log('验证成功');
  11433. // 在这里处理验证成功后的逻辑
  11434. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  11435. this.currentPath = this.lockPath
  11436. this.getSortedFiles(this.currentPath)
  11437. } else {
  11438. // console.log('验证失败');
  11439. ToastUtil.showToast('验证失败')
  11440. }
  11441. }
  11442. private showVerifyDialog() {
  11443. promptAction.openCustomDialog({
  11444. transition: TransitionEffect.asymmetric(
  11445. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  11446. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  11447. ,
  11448. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  11449. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  11450. ),
  11451. builder: () => {
  11452. this.customDialogComponentMM()
  11453. },
  11454. isModal: true,
  11455. autoCancel: true,
  11456. maskColor: Color.Transparent,
  11457. alignment: DialogAlignment.Bottom,
  11458. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  11459. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  11460. console.log("dialog onWillDismiss")
  11461. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  11462. dismissDialogAction.dismiss()
  11463. }
  11464. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  11465. dismissDialogAction.dismiss()
  11466. }
  11467. }
  11468. }).then((dialogId: number) => {
  11469. this.customDialogComponentIdMM = dialogId
  11470. })
  11471. }
  11472. //左滑操作 移动文件 重命名 删除等操作
  11473. @Builder
  11474. DeleteButton(item: VideoItem, index: number, filePath: string) {
  11475. Row() {
  11476. //加入收藏
  11477. Button() {
  11478. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  11479. .fillColor(Color.White)
  11480. .width(20)
  11481. }
  11482. .width(40)
  11483. .height(40)
  11484. .type(ButtonType.Circle)
  11485. .backgroundColor(this.themeColor)
  11486. .margin(5)
  11487. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  11488. .onClick(() => {
  11489. if (item) {
  11490. this.doFav(item)
  11491. }
  11492. })
  11493. //加入下一首播放
  11494. Button() {
  11495. Image($r('app.media.next_to_play'))
  11496. .fillColor(Color.White)
  11497. .width(20)
  11498. }
  11499. .width(40)
  11500. .height(40)
  11501. .type(ButtonType.Circle)
  11502. .backgroundColor(this.themeColor)
  11503. .margin(5)
  11504. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  11505. .onClick(() => {
  11506. this.addToNextPlay(item);
  11507. })
  11508. //复制文件
  11509. Button() {
  11510. Image($r('app.media.copy'))
  11511. .fillColor(Color.White)
  11512. .width(20)
  11513. }
  11514. .width(40)
  11515. .height(40)
  11516. .type(ButtonType.Circle)
  11517. .backgroundColor(this.themeColor)
  11518. .margin(5)
  11519. .id(filePath + 'copy')
  11520. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  11521. .onClick(() => {
  11522. this.showCopyDialog(false, item, index, filePath + 'copy');
  11523. })
  11524. //移动文件
  11525. Button() {
  11526. Image($r('app.media.cut'))
  11527. .fillColor(Color.White)
  11528. .width(20)
  11529. }
  11530. .width(40)
  11531. .height(40)
  11532. .type(ButtonType.Circle)
  11533. .backgroundColor(this.themeColor)
  11534. .margin(5)
  11535. .id(filePath)
  11536. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  11537. .onClick(() => {
  11538. this.showCutDialog(false, item, index, filePath);
  11539. })
  11540. Button() {
  11541. Image($r('app.media.cut_current'))
  11542. .fillColor(Color.White)
  11543. .width(20)
  11544. }
  11545. .width(40)
  11546. .height(40)
  11547. .type(ButtonType.Circle)
  11548. .backgroundColor(this.themeColor)
  11549. .margin(5)
  11550. .id(filePath + 'current')
  11551. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  11552. (this.isHasDir ? Visibility.Visible : Visibility.None))
  11553. .onClick(() => {
  11554. this.showCutDialog(true, item, index, filePath + 'current');
  11555. })
  11556. //重命名
  11557. Button() {
  11558. Image($r('app.media.rename2'))
  11559. .fillColor(Color.White)
  11560. .width(20)
  11561. }
  11562. .width(40)
  11563. .height(40)
  11564. .type(ButtonType.Circle)
  11565. .backgroundColor(this.themeColor)
  11566. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  11567. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  11568. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  11569. .margin(5)
  11570. .onClick(() => {
  11571. this.showReNameDialog(item, index + '', filePath)
  11572. })
  11573. Button() {
  11574. Image($r('app.media.delete2'))
  11575. .fillColor(Color.White)
  11576. .width(20)
  11577. }
  11578. .width(40)
  11579. .height(40)
  11580. .type(ButtonType.Circle)
  11581. .backgroundColor(this.themeColor)
  11582. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  11583. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  11584. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  11585. .margin(5)
  11586. .onClick(() => {
  11587. this.selectedFiles.push(item)
  11588. this.showWarnIsDelete()
  11589. // this.showWarnIsDeleteFile(item, index + '', filePath)
  11590. })
  11591. Button() {
  11592. Image($r('app.media.share2'))
  11593. .fillColor(Color.White)
  11594. .width(20)
  11595. }
  11596. .width(40)
  11597. .height(40)
  11598. .type(ButtonType.Circle)
  11599. .backgroundColor(this.themeColor)
  11600. .margin(5)
  11601. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  11602. .onClick(() => {
  11603. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  11604. })
  11605. }
  11606. }
  11607. /**
  11608. * 穿山甲banner广告
  11609. */
  11610. // private declare bannerAd: CSJNativeExpressAd;
  11611. // @State private status: string = "未加载"
  11612. // @State private isShowAd: boolean = false
  11613. // private declare mAdSlot: AdSlot;
  11614. // private mBiddingAdm = '' //服务端bidding才需要设置
  11615. // private expressLoadAdListener: NativeExpressAdListener = {
  11616. // /**
  11617. // * 加载失败的回调
  11618. // *
  11619. // * @param code
  11620. // * @param message
  11621. // */
  11622. // onError: (code: number, message: string) => {
  11623. // console.error("加载广告失败,code=" + code + ",message=" + message);
  11624. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  11625. // },
  11626. //
  11627. // /**
  11628. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  11629. // *
  11630. // * @param ads 返回的广告列表
  11631. // */
  11632. //
  11633. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  11634. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  11635. // if (ads && ads.length > 0) {
  11636. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  11637. // ad.setExpressInteractionListener({
  11638. // /**
  11639. // *广告的点击回调
  11640. // * @param type 广告的交互类型
  11641. // */
  11642. // onAdClicked: (type: number) => {
  11643. // console.log("BannerExpressAdPage==onAdClicked......");
  11644. // },
  11645. //
  11646. // /**
  11647. // * 广告的展示回调 每个广告仅回调一次
  11648. // * @param type 广告的交互类型
  11649. // */
  11650. // onAdShow: (type: number) => {
  11651. // console.log("BannerExpressAdPage==onAdShow......");
  11652. // },
  11653. //
  11654. // /**
  11655. // * 模板渲染失败
  11656. // */
  11657. // onRenderFail: (code: number, msg: string) => {
  11658. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  11659. // },
  11660. //
  11661. // /**
  11662. // * 模板渲染成功
  11663. // * @param width 返回view的宽 单位 vp
  11664. // * @param height 返回view的高 单位 vp
  11665. // */
  11666. // onRenderSuccess: (width: number, height: number) => {
  11667. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  11668. // this.bannerAd = ad;
  11669. // this.status = "广告加载完成待展示";
  11670. //
  11671. // this.showBannerAd()
  11672. // }
  11673. // })
  11674. // //渲染广告
  11675. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  11676. // this.setDislikeCallback(ad); //设置dislike
  11677. // ad.render(this.getUIContext())
  11678. // this.status = "广告加载中...";
  11679. // });
  11680. // }
  11681. // }
  11682. // }
  11683. //
  11684. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  11685. // ad.setDislikeCallback({
  11686. // /**
  11687. // * dislike show
  11688. // */
  11689. // onShow: () => {
  11690. // console.log("BannerExpressAdPage==dislike......show");
  11691. // },
  11692. //
  11693. // /**
  11694. // * @param position 选择的位置
  11695. // * @param value 选择的内容
  11696. // * @param enforceRemove 是否强制关闭广告
  11697. // */
  11698. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  11699. // this.isShowAd = false;
  11700. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  11701. // ",enforce=" + enforceRemove);
  11702. // },
  11703. //
  11704. // /**
  11705. // * 点击取消
  11706. // */
  11707. // onCancel: () => {
  11708. // console.log("BannerExpressAdPage==dislike......onCancel");
  11709. // }
  11710. //
  11711. // })
  11712. // }
  11713. /**
  11714. * 加载Banner广告
  11715. */
  11716. loadBannerAd(rit: string) {
  11717. // if (Utility.isNoble()) {
  11718. // return
  11719. // }
  11720. // if (!Utility.isPassInstallTime(2)) {
  11721. // return
  11722. // }
  11723. // this.isShowAd = false;
  11724. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  11725. // this.mAdSlot = new AdSlotBuilder()
  11726. // .setCodeId(rit)
  11727. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  11728. // .setAdCount(1)
  11729. // .setBidAdm(this.mBiddingAdm)
  11730. // .build()
  11731. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  11732. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  11733. // this.status = "广告加载中..."
  11734. }
  11735. /**
  11736. * 展示Banner广告
  11737. */
  11738. // showBannerAd() {
  11739. // if (!this.bannerAd) {
  11740. // return
  11741. // }
  11742. // this.isShowAd = true
  11743. // this.status = "已展示"
  11744. // }
  11745. /**
  11746. * 穿山甲广告代码结束
  11747. */
  11748. /**
  11749. * 处理歌单播放请求
  11750. */
  11751. private handlePlaylistPlayRequest(playlistId: string, playlistName: string, songFilePaths: string[], startIndex: number) {
  11752. try {
  11753. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 歌曲数量: ${songFilePaths.length}, 开始索引: ${startIndex}`)
  11754. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  11755. const songMap: Map<number, VideoItem> = new Map()
  11756. let completedQueries = 0
  11757. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  11758. // 遍历所有文件路径,使用索引记录位置
  11759. for (let i = 0; i < songFilePaths.length; i++) {
  11760. const filePath = songFilePaths[i]
  11761. const index = i
  11762. Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  11763. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  11764. const queryPromise = this.table.queryVideoByFilePath(filePath)
  11765. Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  11766. queryPromise.then((videoItem) => {
  11767. completedQueries++
  11768. Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  11769. if (videoItem) {
  11770. // 使用索引作为key保存到Map中,保持原始顺序
  11771. songMap.set(index, videoItem)
  11772. Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  11773. } else {
  11774. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  11775. }
  11776. // 检查是否所有歌曲都已加载完成
  11777. if (completedQueries === songFilePaths.length) {
  11778. Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  11779. // 按照索引顺序重建歌曲数组
  11780. const songs: VideoItem[] = []
  11781. for (let j = 0; j < songFilePaths.length; j++) {
  11782. const song = songMap.get(j)
  11783. if (song) {
  11784. songs.push(song)
  11785. Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  11786. }
  11787. }
  11788. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  11789. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  11790. }
  11791. }).catch((error: Error) => {
  11792. completedQueries++
  11793. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  11794. // 即使出错也要检查是否完成所有查询
  11795. if (completedQueries === songFilePaths.length) {
  11796. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  11797. // 按照索引顺序重建歌曲数组
  11798. const songs: VideoItem[] = []
  11799. for (let j = 0; j < songFilePaths.length; j++) {
  11800. const song = songMap.get(j)
  11801. if (song) {
  11802. songs.push(song)
  11803. }
  11804. }
  11805. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  11806. }
  11807. })
  11808. }
  11809. } catch (error) {
  11810. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  11811. ToastUtil.showToast('播放失败')
  11812. }
  11813. }
  11814. /**
  11815. * 完成歌单加载并开始播放
  11816. */
  11817. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string) {
  11818. if (songs.length === 0) {
  11819. Logger.error('heanup 没有找到任何可播放的歌曲')
  11820. ToastUtil.showToast('没有找到可播放的歌曲')
  11821. return
  11822. }
  11823. this.songList = songs
  11824. this.sonDataSource.pushArrayData(songs)
  11825. this.sonDataSource.notifyDataReload()
  11826. this.curIndex = startIndex
  11827. if (songs[startIndex]) {
  11828. // 确保当前播放的歌曲也更新到存储
  11829. AppStorage.setOrCreate('currentSong', songs[startIndex])
  11830. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  11831. this.doPlay(songs[startIndex], startIndex, true)
  11832. }
  11833. PreferencesUtil.putSync('LastMusicList', this.songList)
  11834. ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  11835. }
  11836. }
  11837. //视频气泡窗口的布局
  11838. @Builder
  11839. function customPopupBuilder(dataBu: BubbleBean) {
  11840. List() {
  11841. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  11842. ListItem() {
  11843. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  11844. Row() {
  11845. Column() {
  11846. Image(dataBu.imageRes[index])
  11847. .height(28)
  11848. .fillColor(dataBu.color)
  11849. .alignSelf(ItemAlign.Center)
  11850. }
  11851. .width(32)
  11852. Text(item)
  11853. .padding({
  11854. top: 10,
  11855. bottom: 10,
  11856. right: 10,
  11857. left: 10
  11858. })
  11859. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  11860. .textAlign(TextAlign.Start)
  11861. .width("100%")
  11862. }
  11863. }
  11864. .backgroundColor($r('app.color.settings_background_main'))
  11865. .margin({ top: 6, bottom: 6 })
  11866. }
  11867. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  11868. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  11869. TransitionEffect.scale({ x: 0, y: 0 })))
  11870. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  11871. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  11872. .onClick(() => {
  11873. dataBu.onItemClick?.(index)
  11874. })
  11875. })
  11876. }
  11877. .scrollBar(BarState.Off)
  11878. .width(120)
  11879. .divider({
  11880. strokeWidth: 1,
  11881. color: "#22FFFFFF"
  11882. })
  11883. }
  11884. // Function to calculate a hash for the file list
  11885. function simpleHash(fileList: string[]): string {
  11886. let hash = 0;
  11887. const str = fileList.join(',');
  11888. for (let i = 0; i < str.length; i++) {
  11889. const char = str.charCodeAt(i);
  11890. hash = (hash << 5) - hash + char;
  11891. hash |= 0; // Convert to 32bit integer
  11892. }
  11893. return hash.toString();
  11894. }
  11895. interface MoreItem {
  11896. id: number;
  11897. image: Resource;
  11898. title: string;
  11899. }
  11900. //视频气泡窗口的布局
  11901. @Builder
  11902. function cutPopupBuilder(dataBu: BubbleBean) {
  11903. Column() {
  11904. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  11905. .padding({
  11906. top: 10,
  11907. bottom: 10,
  11908. right: 10,
  11909. left: 10
  11910. })
  11911. .textAlign(TextAlign.Start)
  11912. .width(160)
  11913. .fontWeight(666)
  11914. .fontSize(16)
  11915. List() {
  11916. ForEach(dataBu.data, (item: string, index: number) => {
  11917. ListItem() {
  11918. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  11919. Row() {
  11920. Column() {
  11921. Image($r('app.media.music_group'))
  11922. .height(28)
  11923. .fillColor(dataBu.color)
  11924. .alignSelf(ItemAlign.Center)
  11925. }
  11926. .width(32)
  11927. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  11928. .padding({
  11929. top: 10,
  11930. bottom: 10,
  11931. right: 10,
  11932. left: 10
  11933. })
  11934. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  11935. .fontSize(15)
  11936. }
  11937. }
  11938. .backgroundColor(Color.Transparent)
  11939. .margin({ top: 7, bottom: 7 })
  11940. }
  11941. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  11942. .animation({ duration: 500 }),
  11943. TransitionEffect.scale({ x: 0, y: 0 })))
  11944. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  11945. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  11946. .onClick(() => {
  11947. dataBu.onItemClick?.(index)
  11948. })
  11949. })
  11950. }
  11951. .scrollBar(BarState.Off)
  11952. .width(150)
  11953. .divider({
  11954. strokeWidth: 1,
  11955. color: "#22FFFFFF"
  11956. })
  11957. }
  11958. .height(300)
  11959. .padding({
  11960. bottom: 30
  11961. })
  11962. }
  11963. function getFileDirName(filePath: string,rootPath:string): string{
  11964. if(filePath===rootPath){
  11965. return '首页'
  11966. }
  11967. let result = FileUtil.getFileName(filePath)
  11968. if(StrUtil.isEmpty(result))
  11969. return ''
  11970. if(result.startsWith('.'))
  11971. result = result.replace(/\./g, '')
  11972. return result
  11973. }
  11974. //只扫描当前目录下文件(不扫描子文件夹)的方法
  11975. @Concurrent
  11976. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  11977. const table: MediaTable = new MediaTable(context);
  11978. try {
  11979. // 直接获取当前目录下的文件列表
  11980. const files = FileUtil.listFileSync(dirPath);
  11981. await Promise.all(files.map(async (file) => {
  11982. const fPath = `${dirPath}/${file}`;
  11983. // 跳过目录,只处理文件
  11984. if (FileUtil.isDirectory(fPath)) {
  11985. return;
  11986. }
  11987. // 跳过特定格式文件
  11988. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  11989. return;
  11990. }
  11991. // 检查是否为媒体文件
  11992. if (Utility.isMeidaByExtension(fPath)) {
  11993. let mType = CommonConstants.TYPE_LOCAL;
  11994. if (fPath.includes(lockPath)) {
  11995. mType = CommonConstants.TYPE_LOCK;
  11996. }
  11997. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  11998. context, fPath, mType, true
  11999. );
  12000. table.insert(mediaItem, (id: number) => {
  12001. // 插入回调函数
  12002. }, cover_api);
  12003. }
  12004. }));
  12005. } catch (error) {
  12006. console.error(' 扫描当前目录失败:', error);
  12007. }
  12008. }