LocalMusic.ets 268 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293
  1. import TitleBar from './TitleBar'
  2. import { Animator, curves, display, PromptAction, promptAction, router, window } from '@kit.ArkUI';
  3. import { VideoItem } from '../viewmodel/VideoItem';
  4. import {
  5. AppUtil,
  6. ArrayUtil,
  7. Base64Util,
  8. DateUtil,
  9. DeviceUtil,
  10. DisplayUtil,
  11. FileUtil,
  12. ImageUtil,
  13. LogUtil,
  14. MD5,
  15. PickerUtil,
  16. PreferencesUtil,
  17. RandomUtil,
  18. StrUtil,
  19. ToastUtil
  20. } from '@pura/harmony-utils';
  21. import { CommonConstants } from '../common/constants/CommonConstants';
  22. import Logger from '../common/util/Logger';
  23. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  24. import { Utility } from '../common/util/Utility';
  25. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  26. import { dataSharePredicates, uniformTypeDescriptor } from '@kit.ArkData';
  27. import { BubbleBean } from '../viewmodel/BubbleBean';
  28. import { PopupPosition, XPopup } from '@chinalike/popup';
  29. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  30. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  31. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  32. import { CSJUtil } from '../common/util/CSJUtil';
  33. import {
  34. AdSlot,
  35. AdSlotBuilder,
  36. CSJAdCreator,
  37. CSJAdSdk,
  38. CSJNativeExpressAd,
  39. NativeExpressAdListener
  40. } from '@csj/openadsdk';
  41. import { PrintBiddingTokenUtils } from '../common/util/PrintBiddintTokenUtils';
  42. import { ArrayList, MessageEvents, util, worker } from '@kit.ArkTS';
  43. import { Verify } from './Verify';
  44. import { DrawerOptions } from '../dialog/DrawerOptions';
  45. import { RotatingCover } from './RotatingCover';
  46. import { PlayConstants } from '../common/constants/PlayConstants';
  47. import { displaySync, effectKit } from '@kit.ArkGraphics2D';
  48. import { ColorConversion } from '../common/util/ColorConversion';
  49. import { LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  50. import { AvSessionController } from '../controller/AvSessionController';
  51. import {
  52. IjkMediaPlayer,
  53. InterruptEvent,
  54. InterruptHintType,
  55. LogUtils,
  56. OnBufferingUpdateListener,
  57. OnCompletionListener,
  58. OnErrorListener,
  59. OnInfoListener,
  60. OnPreparedListener,
  61. OnSeekCompleteListener,
  62. OnTimedTextListener,
  63. OnVideoSizeChangedListener
  64. } from '@ohos/ijkplayer';
  65. import { PlayStatus } from '../common/PlayStatus';
  66. import fs from '@ohos.file.fs';
  67. import { image } from '@kit.ImageKit';
  68. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  69. import * as chardet from '@changwei/chardet';
  70. import { SettingPage } from '../pages/SettingPage';
  71. import { secondToTime } from '../common/util/CommUtils';
  72. import { CommonConstants2 } from '../common/util/CommonConstants2';
  73. import { hilog } from '@kit.PerformanceAnalysisKit';
  74. import { LazyDataSource } from '../common/util/LazyDataSource';
  75. import MediaTable from '../common/util/MediaTable';
  76. import { ImageKnifeComponent } from '@ohos/imageknife';
  77. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  78. import ImageUtils from '../common/util/ImageUtils';
  79. import { ringtone } from '@kit.RingtoneKit';
  80. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  81. import { resourceManager } from '@kit.LocalizationKit';
  82. import File from '@system.file';
  83. import { deviceInfo } from '@kit.BasicServicesKit';
  84. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  85. import { DEBUG } from 'BuildProfile';
  86. import { LrcParser } from '@sgaolei/lrc_parser';
  87. const TAG = 'LocalMusic';
  88. //排序类型
  89. function getTypeOrder(type: number) {
  90. switch (type) {
  91. case CommonConstants.TYPE_IS_DIR:
  92. return 1; // First
  93. case CommonConstants.TYPE_IS_CSJAD:
  94. return 2; // Middle
  95. case CommonConstants.TYPE_LOCAL:
  96. return 3; // Last
  97. default:
  98. return 4; // Unknown types, if any, go last
  99. }
  100. }
  101. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  102. interface GeneratedObjectLiteralInterface_1 {
  103. assetId: string;
  104. title: string;
  105. artist: string;
  106. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  107. mediaUri: string;
  108. // 该字段大写,音频'AUDIO',视频'VIDEO'
  109. mediaType: string;
  110. mediaSize: number;
  111. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  112. startPosition: number;
  113. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  114. duration: number;
  115. albumCoverUri: string;
  116. albumTitle: string;
  117. appName: string;
  118. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  119. drmScheme: string;
  120. }
  121. //功能强大的音乐播放器
  122. @Preview
  123. @Component
  124. export struct LocalMusic {
  125. themeMode: number=0;
  126. @State titleName: string = '首页'
  127. @State textStr: string = ''
  128. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  129. // private download_path: string = '';
  130. @Consume rootPath: string //音频根目录
  131. @Consume currentPath: string
  132. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  133. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  134. @State lockPath: string = ''
  135. @State favPath: string = ''
  136. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  137. @State historyPath: string = ''
  138. @State historyList: Array<VideoItem> = []
  139. @Consume isHistory: boolean
  140. static readonly HISTORY_MUSIC: string = 'music_historyList';
  141. private table: MediaTable = new MediaTable(getContext(this))
  142. @State isZero: boolean = false
  143. @State fileList: Array<string> = []
  144. @State dirList: Array<VideoItem> = []
  145. @Consume videoLocalList: Array<VideoItem>
  146. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  147. @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  148. @State artistList: Array<VideoItem> = []; //艺术家文件
  149. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  150. @State albumList: Array<VideoItem> = []; //专辑文件
  151. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  152. @State imageOpacities: number[] = [];
  153. @Consume isCanBack: boolean
  154. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  155. @State showSingleLyric: boolean = false
  156. @State sortType: number = 4 //默认排序方式
  157. @State isShowSimi:boolean = false //是否显示私密音频
  158. @State isShowFAV:boolean = true //是否显示我的收藏
  159. @State isShowHistory:boolean = true //是否显示最近播放
  160. @State isCustomizeBg: boolean = false //自定义背景界面
  161. @State isGridMusic: boolean = false //是否网格布局
  162. @State customizeBgPath: string | undefined = '';
  163. @State isDarkMode: boolean = false
  164. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  165. ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT;
  166. onColorModeChange() {
  167. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  168. }
  169. onModeChange() {
  170. this.isFavMusic = false
  171. if (this.modeType === 2 || this.modeType === 3) {
  172. this.titleBarModel.setRightIcon(null)
  173. } else {
  174. this.titleBarModel.setRightIcon(($r('app.media.add')))
  175. }
  176. LogUtil.info('onecold onModeChange = ' + this.modeType)
  177. switch (this.modeType) {
  178. case 0:
  179. this.getSortedFiles(this.currentPath)
  180. break
  181. case 1:
  182. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  183. this.updateListData(this.mediaKuList)
  184. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  185. break
  186. case 2:
  187. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  188. this.updateListData(this.artistList)
  189. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  190. break
  191. case 3:
  192. this.titleBarModel.setLeftIconMainNoAnimate($r('app.media.menu'))
  193. this.updateListData(this.albumList)
  194. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  195. break
  196. }
  197. }
  198. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  199. // @StorageLink('isPlay') isPlay: boolean = false;
  200. @StorageLink('isShowPlay') isShowPlay: boolean = false;
  201. @StorageProp('windowHeight') windowHeight: number = 0;
  202. @StorageLink('songList') songList: Array<VideoItem> = [];
  203. @State translateY: number = 0;
  204. @State isShowSheet: boolean = false;
  205. @State isShowSheetView: boolean = false;
  206. @State isShowTimeCloseView: boolean = false;
  207. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  208. @StorageLink('currIndex') curIndex: number = 0;
  209. @Consume isShowDrawer: boolean;
  210. @Consume offsetX: number;
  211. @State isFac: boolean = false;
  212. @State facList: Array<String> = []
  213. @State favList: Array<VideoItem>= []
  214. @Consume isFavMusic:boolean
  215. @State isClickedPLayAll: boolean = false;
  216. private scrollerForlist: ListScroller = new ListScroller();
  217. imagesF: ImageFrameInfo[] = [
  218. { src: $r("app.media.app_loading0") },
  219. { src: $r("app.media.app_loading1") },
  220. { src: $r("app.media.app_loading2") },
  221. { src: $r("app.media.app_loading3") },
  222. ]
  223. @State animationState: AnimationStatus = AnimationStatus.Initial
  224. // 缓存机制
  225. private cache: Map<string, Array<VideoItem>> = new Map();
  226. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  227. // 持久化缓存
  228. private async saveCacheToStorage() {
  229. const cacheArray = Array.from(this.cache.entries());
  230. const stringCacheArray = Array.from(this.stringCache.entries());
  231. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  232. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray)); // 保存字符串缓存
  233. }
  234. // 载入缓存
  235. private async loadCacheFromStorage() {
  236. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  237. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  238. if (cacheString) {
  239. const cacheArray: [string, Array<VideoItem>][] = JSON.parse(cacheString);
  240. this.cache = new Map(cacheArray);
  241. }
  242. if (stringCacheString) {
  243. const stringCacheArray: [string, string][] = JSON.parse(stringCacheString);
  244. this.stringCache = new Map(stringCacheArray);
  245. }
  246. }
  247. // 查找缓存
  248. private findCache(key: string): Array<VideoItem> | undefined {
  249. return this.cache.get(key);
  250. }
  251. // 查找字符串缓存
  252. private findStringCache(key: string): string | undefined {
  253. return this.stringCache.get(key);
  254. }
  255. // 添加缓存
  256. private addCache(key: string, value: Array<VideoItem>) {
  257. this.cache.set(key, value);
  258. }
  259. // 添加字符串缓存
  260. private addStringCache(key: string, value: string) {
  261. this.stringCache.set(key, value);
  262. }
  263. // 删除缓存
  264. private deleteCache(key: string) {
  265. this.cache.delete(key);
  266. this.saveCacheToStorage()
  267. }
  268. // 删除字符串缓存
  269. private deleteStringCache(key: string) {
  270. this.stringCache.delete(key);
  271. }
  272. // 多选机制
  273. @State selectedFiles: Array<VideoItem> = [];
  274. @State isMultiSelect: boolean = false;
  275. @State isAllSelected: boolean = false;
  276. @State appName: string = ''
  277. @State isHasDir: boolean = false
  278. @State packName: string = ''
  279. context = getContext(this);
  280. @State titleBarModel: TitleBar.Model = new TitleBar.Model()
  281. .setTitleTextStyle(FontStyle.Normal)
  282. .setTitleBarStyle(TitleBar.BarStyle.TRANSPARENT)
  283. .setLeftIcon($r('app.media.menu'))
  284. .setLeftIconWidth(25)
  285. .setLeftIconHeight(25)
  286. .setTitleName('首页')
  287. .setTitleFontSize(18)
  288. .setTitleFontColor(Color.White)
  289. .setTitleBarBackground($r('app.color.title_bar_bg'))
  290. .setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  291. .setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  292. .setRightIcon($r('app.media.add'))
  293. .setOnRightClickListener(() => {
  294. this.showSheelDialog()
  295. })
  296. .setOnTitleClickListener(() => {
  297. this.showPupDialog()
  298. })
  299. .setOnLeftClickListener(() => {
  300. this.doSwipBack()
  301. })
  302. doSwipBack() {
  303. if (this.modeType !== 0 && this.isCanBack) {
  304. this.onModeChange()
  305. this.isCanBack = false
  306. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  307. return
  308. }
  309. if (this.isHistory||this.isFavMusic) {
  310. this.isHistory = false
  311. this.getSortedFiles(this.currentPath)
  312. return
  313. }
  314. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  315. animateTo({ duration: 555 }, () => {
  316. // 动画闭包内控制Image组件的出现和消失
  317. this.isShowDrawer = true
  318. this.offsetX = 0
  319. })
  320. return
  321. }
  322. this.currentPath = Utility.getParentDirectory(this.currentPath)
  323. Logger.info('this.currentPath2 = ' + this.currentPath)
  324. this.getSortedFiles(this.currentPath)
  325. }
  326. // 组件生命周期
  327. aboutToAppear() {
  328. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  329. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  330. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  331. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, false)
  332. if(this.isCustomizeBg){
  333. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  334. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  335. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  336. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  337. }else{
  338. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  339. this.titleBarModel.setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  340. // this.titleBarModel .setRightTitleBackground($r('app.color.title_bar_bg'))
  341. }
  342. Utility.getAppName(getContext(this)).then((appName: string) => {
  343. this.appName = appName
  344. })
  345. this.packName = AppUtil.getBundleName()
  346. this.loadCacheFromStorage(); // 加载缓存
  347. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  348. if (this.isSavePlayMode) {
  349. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  350. }
  351. this.historyList = PreferencesUtil.getSync(LocalMusic.HISTORY_MUSIC, this.historyList) as Array<VideoItem>
  352. this.mkDownLoadDir()
  353. let eventMusic: emitter.InnerEvent = { eventId: 2 }
  354. // 监听广播事件(打开其他应用处理)
  355. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  356. this.saveVideoDatas([eventData.data?.message], true)
  357. });
  358. //侧滑广播接收时间
  359. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: 888 }
  360. // 监听广播事件(打开其他应用处理)
  361. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  362. this.doSwipBack()
  363. });
  364. //ScanFilePage广播接收时间
  365. let eventScanUpdate: emitter.InnerEvent = { eventId: 101 }
  366. // 监听ScanFilePage广播事件(更新数据库)
  367. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  368. this.doUpdateData()
  369. });
  370. let eventSetting: emitter.InnerEvent = { eventId: 333 }
  371. // 监听广播事件(打开其他应用处理)
  372. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  373. this.doChangeSetting()
  374. });
  375. let event: Callback<InterruptEvent> = (event) => {
  376. LogUtils.getInstance().LOGI(`event: ${JSON.stringify(event)}`);
  377. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  378. this.pause();
  379. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  380. this.startPlayOrResumePlay();
  381. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  382. this.stop();
  383. }
  384. }
  385. this.mIjkMediaPlayer.on('audioInterrupt', event);
  386. this.makeWorker()
  387. this.windowClass.on('windowSizeChange', (size) => {
  388. this.doChangeBarHeight()
  389. });
  390. //折叠屏的屏幕显示模式变化
  391. display.on('foldDisplayModeChange', (data) => {
  392. this.doChangeBarHeight()
  393. });
  394. display.on('foldStatusChange', (data) => {
  395. Logger.info('onecold foldStatusChange ')
  396. });
  397. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, false)
  398. // 读取 themeMode 并同步 currentColorMode
  399. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  400. this.applyThemeMode(this.themeMode)
  401. }
  402. applyThemeMode(mode: number) {
  403. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  404. if (mode === 1) {
  405. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  406. } else if (mode === 2) {
  407. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  408. }
  409. AppStorage.setOrCreate('currentColorMode', colorMode)
  410. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  411. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  412. AppStorage.setOrCreate('themeMode', mode)
  413. this.isDarkMode=colorMode===ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  414. // 只有强制浅色/深色时才主动设置
  415. const context = getContext(this) as common.UIAbilityContext
  416. context.getApplicationContext().setColorMode(colorMode)
  417. }
  418. doChangeSetting(){
  419. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  420. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  421. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  422. if(this.isCustomizeBg){
  423. this.titleBarModel.setRightTitleStateNormalStyleColor(Color.Transparent)
  424. this.titleBarModel.setTitleBarBackground(Color.Transparent)
  425. this.titleBarModel.setTitleBarBottomLineColor(Color.Transparent)
  426. this.titleBarModel.setLeftTitleStateNormalStyleColor(Color.Transparent)
  427. }else{
  428. this.titleBarModel.setTitleBarBackground($r('app.color.title_bar_bg'))
  429. this.titleBarModel .setTitleBarBottomLineColor($r('app.color.title_bar_bg'))
  430. this.titleBarModel.setRightTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  431. this.titleBarModel.setLeftTitleStateNormalStyleColor($r('app.color.title_bar_bg'))
  432. }
  433. this.doUpdateData()
  434. }
  435. doChangeBarHeight() {
  436. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  437. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  438. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  439. this.hideDone = false;
  440. this.getUIContext().animateTo({
  441. duration: 300
  442. }, () => {
  443. this.bottomBarHeight = 55 + 0;
  444. this.topBarHeight = 50 + 0;
  445. this.barOpacity = 1;
  446. this.currentYOffset = 0;
  447. this.isHiding = false;
  448. });
  449. }
  450. }
  451. onPageShow() {
  452. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  453. }
  454. //开启线程查看各个数据库
  455. makeWorker() {
  456. setTimeout(() => {
  457. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  458. //发送worker通知扫描文件入库
  459. workerInstance.postMessage({
  460. code: 1,
  461. data1: this.context,
  462. data2: this.rootPath,
  463. data3: this.lockPath,
  464. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  465. });
  466. PreferencesUtil.putSync('isFirstApp', false)
  467. } else {
  468. workerInstance.postMessage({ code: 2, data: this.context });
  469. workerInstance.postMessage({ code: 3, data: this.context });
  470. workerInstance.postMessage({ code: 4, data: this.context });
  471. }
  472. }, 1000)
  473. workerInstance.onmessage = (e: MessageEvents): void => {
  474. switch (e.data.code) {
  475. case 101: //第一次扫描文件夹入库
  476. ToastUtil.showToast('刷新同步数据库成功!')
  477. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  478. this.doUpdateData()
  479. break;
  480. case 102: //查询媒体库列表
  481. this.mediaKuList = e.data.data
  482. Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
  483. Utility.doSortListAscending(this.mediaKuList)
  484. if (this.modeType === 1) {
  485. this.updateListData(this.mediaKuList)
  486. }
  487. break;
  488. case 103: //收到查询艺术家列表
  489. this.artistMap = e.data.data1;
  490. this.artistList = e.data.data2;
  491. break;
  492. case 104: //收到查询专辑列表
  493. this.albumMap = e.data.data1;
  494. this.albumList = e.data.data2
  495. break;
  496. }
  497. };
  498. // 在调用terminate后,执行onexit
  499. workerInstance.onexit = (code) => {
  500. console.log("main thread terminate");
  501. }
  502. }
  503. //获取download_path
  504. async mkDownLoadDir() {
  505. const documentViewPicker = new picker.DocumentViewPicker()
  506. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  507. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  508. // this.rootPath = this.download_path
  509. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  510. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  511. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  512. Logger.info('onecold rootPath = ' + this.rootPath)
  513. Logger.info('onecold lockPath = ' + this.lockPath)
  514. if (!FileUtil.accessSync(this.lockPath)) {
  515. FileUtil.mkdirSync(this.lockPath)
  516. }
  517. if (!FileUtil.accessSync(this.favPath)) {
  518. FileUtil.mkdirSync(this.favPath)
  519. }
  520. if (!FileUtil.accessSync(this.historyPath)) {
  521. FileUtil.mkdirSync(this.historyPath)
  522. }
  523. this.getSortedFiles(this.rootPath).then(() => {
  524. this.isFavMusic = false
  525. //穿山甲
  526. this.loadBannerAd(CSJUtil.getBannerID())
  527. // this.songList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  528. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  529. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  530. if (ArrayUtil.isEmpty(this.songList)) {
  531. this.songList = this.getCurFileList()
  532. } else {
  533. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  534. }
  535. if (ArrayUtil.isNotEmpty(this.songList)) {
  536. this.sonDataSource.pushArrayData(this.songList)
  537. if (this.currentSong === undefined) {
  538. this.currentSong = this.songList[0]
  539. }
  540. this.videoUrl = this.currentSong.filePath
  541. this.name = this.currentSong.name
  542. this.cover = this.currentSong.pixelMapPath
  543. } else {
  544. this.name = '空空如也'
  545. }
  546. })
  547. // if (FileUtil.accessSync(this.favPath)) {
  548. // this.facList = FileUtil.listFileSync(this.favPath)
  549. // }
  550. this.getFavList(false)
  551. }
  552. getFavList(isFavRefresh:boolean){
  553. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  554. this.favList = result
  555. if(isFavRefresh||this.isFavMusic){//如果是我的收藏,更新我的收藏数据
  556. this.videoLocalList = this.favList
  557. this.updateListData(this.videoLocalList)
  558. }
  559. })
  560. }
  561. // 组件消失生命周期
  562. aboutToDisappear() {
  563. console.info('LifeCycleComponent aboutToDisappear');
  564. emitter.off(2);
  565. this.mDestroyPage = true;
  566. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  567. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  568. this.stop();
  569. }
  570. this.mIjkMediaPlayer.off('audioInterrupt');
  571. if (workerInstance) {
  572. workerInstance.terminate();
  573. }
  574. }
  575. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean) {
  576. this.isFavMusic = false
  577. if (isWorkerPost) {
  578. workerInstance.postMessage({ code: 2, data: this.context }); //刷新媒体库列表
  579. }
  580. if (this.modeType !== 0) {
  581. return
  582. }
  583. this.isCanBack = false
  584. this.currentPath = curPath
  585. this.titleBarModel.setTitleName(Utility.getFileDirName(this.currentPath, this.rootPath))
  586. if (curPath === this.rootPath) {
  587. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  588. } else {
  589. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  590. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  591. }
  592. }
  593. // Get the current file list and calculate its hash
  594. this.fileList = FileUtil.listFileSync(curPath);
  595. const currentHash = simpleHash(this.fileList);
  596. // Check cache
  597. const cachedValue = this.findCache(curPath);
  598. Logger.info('onecold cachedValue = ' + cachedValue)
  599. const cachedHash = this.findStringCache(curPath + '_hash');
  600. const cachedDirList = this.findCache(curPath + "_dirList");
  601. if (cachedValue !== undefined) {
  602. // this.videoLocalList = cachedValue;
  603. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  604. this.updateListData(cachedValue)
  605. }
  606. if (cachedDirList !== undefined) {
  607. this.dirList = cachedDirList
  608. }
  609. //通过当前hash值和缓存hash判断list有没有变化
  610. if (cachedValue && cachedHash === currentHash) {
  611. return;
  612. }
  613. this.fileList = FileUtil.listFileSync(curPath)
  614. let directories: Array<VideoItem> = [];
  615. let files: Array<VideoItem> = [];
  616. for (let i = 0; i < this.fileList.length; i++) {
  617. console.info(`The name of file: ${this.fileList[i]}`);
  618. let path = curPath + '/' + this.fileList[i]
  619. if (FileUtil.isDirectory(path)) {
  620. let item: VideoItem =
  621. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  622. '')
  623. if(this.isShowDir(item.name)){
  624. directories.push(item);
  625. }
  626. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  627. // Utility.doSortListAscending(directories)
  628. } else {
  629. if (this.currentPath === this.lockPath) {
  630. let item: VideoItem =
  631. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  632. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  633. files.push(item);
  634. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  635. // this.doSortListAscending(files)
  636. }
  637. }
  638. }
  639. }
  640. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  641. if (this.currentPath !== this.lockPath) {
  642. files = result;
  643. }
  644. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  645. Utility.doSortListAscending(files)
  646. if (this.currentPath === this.rootPath) {
  647. this.dirList = directories
  648. this.addCache(curPath + "_dirList", this.dirList);
  649. }
  650. if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  651. let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  652. directories.push(adItem)
  653. }
  654. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  655. this.videoLocalList = directories.concat(files);
  656. this.updateListData(this.videoLocalList)
  657. if (ArrayUtil.isNotEmpty(files)) {
  658. // 缓存结果
  659. this.addCache(curPath, this.videoLocalList);
  660. await this.saveCacheToStorage(); // 保存缓存至本地存储
  661. this.addStringCache(curPath + '_hash', currentHash);
  662. }
  663. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  664. // for (let i = 0; i < this.videoLocalList.length; i++) {
  665. //
  666. // console.info(`onecold gengxin 1: ${this.videoLocalList[i].pixelMapPath}`);
  667. //
  668. // }
  669. // this.setButtonStatus()
  670. if (isOpen) {
  671. if (destPath === undefined) {
  672. // 处理 destPath 为 undefined 的情况
  673. return
  674. }
  675. if (destPath.endsWith('.lrc')) {
  676. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  677. if (StrUtil.isNotEmpty(this.videoUrl)) {
  678. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  679. this.initLyric(lyricPath);
  680. }
  681. return
  682. }
  683. let item2 = new VideoItem(Utility.getMediaNameByUri(destPath), destPath, destPath, 0, 0, '')
  684. this.doPlay(item2)
  685. }
  686. });
  687. }
  688. //扫描文件夹入库
  689. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  690. const files = FileUtil.listFileSync(curPath);
  691. let mediaItems: VideoItem[] = [];
  692. Logger.info('onecold scanDirectory start ')
  693. for (const file of files) {
  694. const fPath = `${curPath}/${file}`;
  695. if (fPath === this.lockPath) {
  696. Logger.info(`Skipping locked path: ${fPath}`);
  697. continue;
  698. }
  699. if (FileUtil.isDirectory(fPath)) {
  700. // Recursively scan subdirectories
  701. const subDirItems = await this.scanDirectory(fPath);
  702. mediaItems = mediaItems.concat(subDirItems);
  703. } else {
  704. Logger.info('onecold scanDirectory filePath = ' + fPath)
  705. // Process media files
  706. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  707. let mediaItem: VideoItem =
  708. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, true);
  709. mediaItems.push(mediaItem);
  710. this.table.insert(mediaItem, (id: number) => {
  711. });
  712. }
  713. }
  714. }
  715. return mediaItems;
  716. }
  717. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  718. animateTo({ duration: 888 }, () => {
  719. this.opacityItem = 0;
  720. });
  721. setTimeout(() => {
  722. this.videoLocalList = mList;
  723. if (!noSort) {
  724. if (this.modeType === 0 || this.modeType === 1) {
  725. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  726. this.doSortType(this.sortType)
  727. }
  728. }
  729. this.dataSource.pushArrayData(this.videoLocalList)
  730. animateTo({ duration: 888 }, () => {
  731. this.opacityItem = 1;
  732. });
  733. this.setButtonStatus()
  734. }, 200);
  735. }
  736. //获取视频缩略图头像
  737. async updatePixelMaps(curPath: string) {
  738. console.info('updatePixelMaps: ', curPath);
  739. const updatedList = [...this.videoLocalList]; // 创建一个新的列表
  740. for (const videoItem of updatedList) {
  741. if (videoItem.type === CommonConstants.TYPE_LOCAL) {
  742. let pixelMap: image.PixelMap | undefined = undefined;
  743. const uri = videoItem.filePath;
  744. // 获取缩略图
  745. // if (Utility.isVideoByExtension(uri)) {
  746. // pixelMap = await Utility.getFetchFrameByTime(uri);
  747. // } else {
  748. // pixelMap = await Utility.getFetchMetadataFromFdSrcByPromise(uri);
  749. // }
  750. let name = await MD5.digestSync(uri)
  751. let imagePath = this.context.filesDir + FileUtil.separator + name
  752. console.info('onecold release success. name= ' + name);
  753. imagePath = fileUri.getUriFromPath(imagePath)
  754. videoItem.pixelMapPath = imagePath
  755. // videoItem.pixelMap = pixelMap;
  756. // videoItem.pixelMapToString = pixelMap ? await ImageUtil.pixelMapToBase64StrBig(pixelMap) : undefined;
  757. }
  758. }
  759. // console.info('updatePixelMaps完毕: ', updatedList.length);
  760. this.updateListData(updatedList)
  761. // this.videoLocalList = updatedList; // 重新赋值以触发更新
  762. // 缓存结果
  763. this.addCache(curPath, updatedList);
  764. await this.saveCacheToStorage(); // 保存缓存至本地存储
  765. }
  766. //排序模式和多选模式
  767. showPupDialog() {
  768. if (this.modeType === 2 || this.modeType === 3) {
  769. this.titleBarModel.setRightIcon(null)
  770. } else {
  771. this.titleBarModel.setRightIcon(($r('app.media.add')))
  772. }
  773. let dataBean = new BubbleBean()
  774. dataBean.data = ["首页", "媒体库", "艺术家", "专辑", "同步数据"]
  775. dataBean.imageRes =
  776. [$r('app.media.home_press'), $r('app.media.kp_music'), $r('app.media.music_menu'), $r('app.media.llq'),
  777. $r('app.media.refresh')]
  778. let pup: XPopup;
  779. if (this.isDarkMode) {
  780. pup = XPopup.Builder()
  781. .setPopupPosition(PopupPosition.BOTTOM)
  782. .atView('pup_positon_music')
  783. .setBackgroundColor(Color.Black)
  784. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  785. .show()
  786. }else {
  787. pup = XPopup.Builder()
  788. .setPopupPosition(PopupPosition.BOTTOM)
  789. .atView('pup_positon_music')
  790. .setBackgroundColor(Color.White)
  791. .asBubble(wrapBuilder(customPopupBuilder), dataBean)
  792. .show()
  793. }
  794. dataBean.onItemClick = (i) => {
  795. XPopup.dismissTop()
  796. switch (i) {
  797. case 0: //首页
  798. this.modeType = 0
  799. this.getSortedFiles(this.currentPath)
  800. break
  801. case 1:
  802. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  803. this.modeType = 1
  804. this.updateListData(this.mediaKuList)
  805. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.media_ku')))
  806. break
  807. case 2:
  808. this.modeType = 2
  809. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  810. this.updateListData(this.artistList)
  811. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.artist')))
  812. break
  813. case 3:
  814. this.modeType = 3
  815. this.titleBarModel.setLeftIconMain($r('app.media.menu'))
  816. this.updateListData(this.albumList)
  817. this.titleBarModel.setTitleName(Utility.resourceToString(this.context, $r('app.string.album')))
  818. break
  819. case 4: //同步数据
  820. workerInstance.postMessage({
  821. code: 1,
  822. data1: this.context,
  823. data2: this.rootPath,
  824. data3: this.lockPath,
  825. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  826. });
  827. break
  828. }
  829. }
  830. }
  831. getCurFileList(): Array<VideoItem> {
  832. let files: Array<VideoItem> = [];
  833. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  834. for (let i = 0; i < this.videoLocalList.length; i++) {
  835. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  836. files.push(this.videoLocalList[i]);
  837. }
  838. }
  839. }
  840. return files
  841. }
  842. setButtonStatus() {
  843. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  844. this.isZero = false
  845. } else {
  846. this.isZero = true
  847. }
  848. if (this.currentPath !== this.rootPath &&
  849. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  850. this.isHasDir = true //不为空,说明有子文件夹
  851. } else {
  852. this.isHasDir = false
  853. }
  854. }
  855. showRankDialog() {
  856. if (this.modeType === 2 || this.modeType === 3) {
  857. //动作面板
  858. DialogHelper.showBottomSheetDialog({
  859. title: "请选择排序模式",
  860. maskColor: Color.Transparent,
  861. // sheets: ["按名称升序", "按名称降序"],
  862. sheets:[
  863. {value:'按名称升序',fontColor: $r('app.color.text_color') },
  864. {value:'按名称降序',fontColor: $r('app.color.text_color') },
  865. ],
  866. backgroundColor:$r('app.color.bg_card'),
  867. height: '30%',
  868. transition: AnimationHelper.transitionInDown(555),
  869. onAction: (index) => {
  870. switch (index) {
  871. case 0:
  872. Utility.doSortListAscending(this.videoLocalList)
  873. break;
  874. case 1:
  875. Utility.doSortListDescending(this.videoLocalList)
  876. break;
  877. }
  878. this.updateListData(this.videoLocalList)
  879. }
  880. })
  881. return
  882. }
  883. //动作面板
  884. DialogHelper.showBottomSheetDialog({
  885. title: "请选择排序模式",
  886. maskColor: Color.Transparent,
  887. height: '75%',
  888. // sheets: ["按艺术家升序", "按艺术家降序", "按专辑升序", "按专辑降序", "按名称升序", "按名称降序", "按添加时间升序","按添加时间降序"],
  889. sheets:[
  890. { value: "按艺术家升序", fontColor: $r('app.color.text_color') },
  891. { value: "按艺术家降序", fontColor: $r('app.color.text_color') },
  892. { value: "按专辑升序", fontColor: $r('app.color.text_color') },
  893. { value: "按专辑降序", fontColor: $r('app.color.text_color') },
  894. { value: "按名称升序", fontColor: $r('app.color.text_color') },
  895. { value: "按名称降序", fontColor: $r('app.color.text_color') },
  896. { value: "按添加时间升序", fontColor: $r('app.color.text_color') },
  897. { value: "按添加时间降序", fontColor: $r('app.color.text_color') },
  898. ],
  899. backgroundColor: $r('app.color.bg_card'),
  900. transition: AnimationHelper.transitionInDown(555),
  901. onAction: (index) => {
  902. this.doSortType(index)
  903. this.updateListData(this.videoLocalList, true)
  904. }
  905. })
  906. }
  907. doSortType(index: number) {
  908. switch (index) {
  909. case 0:
  910. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  911. // 类型排序优先级
  912. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  913. if (typeOrder !== 0) {
  914. return typeOrder;
  915. }
  916. // 处理艺术家可能为undefined的字符串比较
  917. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  918. const artistB = b.artist?.trim() || '';
  919. return artistA.localeCompare(artistB);
  920. });
  921. break;
  922. case 1:
  923. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  924. // 类型排序优先级
  925. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  926. if (typeOrder !== 0) {
  927. return typeOrder;
  928. }
  929. // 处理艺术家可能为undefined的字符串比较
  930. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  931. const artistB = b.artist?.trim() || '';
  932. return artistB.localeCompare(artistA);
  933. });
  934. break;
  935. case 2:
  936. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  937. // 类型排序优先级
  938. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  939. if (typeOrder !== 0) {
  940. return typeOrder;
  941. }
  942. // 处理专辑可能为undefined的字符串比较
  943. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  944. const albumB = b.album?.trim() || '';
  945. return albumA.localeCompare(albumB);
  946. });
  947. break;
  948. case 3:
  949. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  950. // 类型排序优先级
  951. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  952. if (typeOrder !== 0) {
  953. return typeOrder;
  954. }
  955. // 处理专辑可能为undefined的字符串比较
  956. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  957. const albumB = b.album?.trim() || '';
  958. return albumB.localeCompare(albumA);
  959. });
  960. break;
  961. case 4:
  962. Utility.doSortListAscending(this.videoLocalList)
  963. break;
  964. case 5:
  965. Utility.doSortListDescending(this.videoLocalList)
  966. break;
  967. case 6:
  968. this.videoLocalList.sort((a, b) => {
  969. // First, sort by type
  970. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  971. if (typeOrder !== 0) {
  972. return typeOrder;
  973. }
  974. // If types are the same, sort by cTime in ascending order
  975. return a.cTime.localeCompare(b.cTime);
  976. });
  977. break;
  978. case 7:
  979. this.videoLocalList.sort((a, b) => {
  980. // First, sort by type
  981. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  982. if (typeOrder !== 0) {
  983. return typeOrder;
  984. }
  985. // If types are the same, sort by cTime in descending order
  986. return b.cTime.localeCompare(a.cTime);
  987. });
  988. break;
  989. }
  990. }
  991. showSheelDialog() {
  992. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  993. // this.showTips()
  994. // return
  995. // }
  996. this.showAddDialog()
  997. }
  998. showAddDialog() {
  999. if (this.modeType === 2 || this.modeType === 3) {
  1000. return
  1001. }
  1002. DialogHelper.showActionSheetDialog({
  1003. title: "请选择添加方式(建议歌词文件一起导入)",
  1004. // sheets: ["新建歌单", "手动导入", "自动导入"],
  1005. sheets:[
  1006. { value: "新建歌单", fontColor: $r('app.color.text_color') },
  1007. { value: "手动导入", fontColor: $r('app.color.text_color') },
  1008. { value: "自动导入", fontColor: $r('app.color.text_color') },
  1009. ],
  1010. maskColor: Color.Transparent,
  1011. backgroundColor: $r('app.color.bg_card'),
  1012. transition: AnimationHelper.transitionInDown(555),
  1013. onAction: (index) => {
  1014. switch (index) {
  1015. case 0:
  1016. if (this.modeType === 0) {
  1017. this.showMkDialog()
  1018. } else {
  1019. ToastUtil.showToast('请切换到首页才能新建歌单!')
  1020. }
  1021. break;
  1022. case 1:
  1023. this.callFilePickerSelectFile()
  1024. break;
  1025. case 2:
  1026. this.showTips()
  1027. break;
  1028. }
  1029. }
  1030. })
  1031. }
  1032. async showTips() {
  1033. DialogHelper.showTipsDialog({
  1034. title: '使用提示:自动导入教程',
  1035. content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  1036. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  1037. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  1038. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  1039. onAction: (action) => {
  1040. if (action == DialogAction.TWO) {
  1041. PreferencesUtil.putSync('isFirstMusic', false)
  1042. router.pushUrl({
  1043. url: 'pages/ScanFilePage'
  1044. });
  1045. }
  1046. }
  1047. })
  1048. }
  1049. showMkDialog() {
  1050. DialogHelper.showTextInputDialog({
  1051. title: '新建歌单',
  1052. maskColor: Color.Transparent,
  1053. text: '',
  1054. transition: AnimationHelper.transitionInDown(666),
  1055. onChange: (text) => {
  1056. console.error("onChange: " + text);
  1057. },
  1058. onAction: (action, dialogId, content) => {
  1059. // ToastUtil.showToast('content = ' +content)
  1060. if (action == DialogAction.TWO) {
  1061. const newName = content
  1062. const newPath = this.currentPath + '/' + newName
  1063. FileUtil.mkdir(newPath, true).then(() => {
  1064. this.cache.delete(this.currentPath); // 删除目标路径缓存
  1065. this.getSortedFiles(this.currentPath)
  1066. }).catch((error: BusinessError) => {
  1067. console.error(error.message);
  1068. });
  1069. }
  1070. }
  1071. })
  1072. }
  1073. @State progress: number = 0;
  1074. async saveVideoDatas(uris: string[], isOpen?: boolean) {
  1075. if (ArrayUtil.isEmpty(uris)) {
  1076. return;
  1077. }
  1078. let newUris: string[] = [];
  1079. this.progress = 0
  1080. DialogHelper.showLoadingProgress({
  1081. progress: this.progress,
  1082. backCancel: false,
  1083. autoCancel: false,
  1084. loadColor: $r('app.color.title_bar_bg'),
  1085. fontColor: $r('app.color.title_bar_bg')
  1086. });
  1087. // 计算所有文件的总大小
  1088. let totalSize = 0;
  1089. for (let uri of uris) {
  1090. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  1091. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  1092. await fileIo.close(sourceFile.fd);
  1093. }
  1094. let totalRead = 0;
  1095. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  1096. Logger.info(TAG, 'destPath uri: ' + destPath);
  1097. for (let i = 0; i < uris.length; i++) {
  1098. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  1099. Logger.info(TAG, 'filePath uri: ' + filePath);
  1100. newUris.push(filePath);
  1101. try {
  1102. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  1103. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  1104. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  1105. const buffer = new ArrayBuffer(buffSize);
  1106. let len = await fileIo.read(sourceFile.fd, buffer);
  1107. while (len > 0) {
  1108. await fileIo.write(destFile.fd, buffer.slice(0, len));
  1109. totalRead += len;
  1110. // 计算总进度
  1111. this.progress = Math.floor((totalRead / totalSize) * 100);
  1112. DialogHelper.updateLoading('正在导入', this.progress);
  1113. len = await fileIo.read(sourceFile.fd, buffer);
  1114. }
  1115. await fileIo.close(sourceFile.fd);
  1116. await fileIo.close(destFile.fd);
  1117. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  1118. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  1119. let mediaItem: VideoItem =
  1120. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, true);
  1121. this.table.insert(mediaItem, (id: number) => {
  1122. // 删除目标路径缓存
  1123. this.cache.delete(this.currentPath);
  1124. this.getSortedFiles(this.currentPath, true, destPath, isOpen)
  1125. });
  1126. }
  1127. }
  1128. } catch (error) {
  1129. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  1130. }
  1131. }
  1132. DialogHelper.closeLoading()
  1133. this.isZero = false
  1134. // setTimeout(() => {
  1135. // // 删除目标路径缓存
  1136. // this.cache.delete(this.currentPath);
  1137. // this.getSortedFiles(this.currentPath,true,destPath,isOpen)
  1138. // }, 500);
  1139. Logger.info(TAG, 'scan select video result:' + newUris)
  1140. }
  1141. //拉起音频
  1142. // goSelectMusic(){
  1143. //
  1144. // try {
  1145. // let audioSelectOptions = new picker.AudioSelectOptions();
  1146. // let audioPicker = new picker.AudioViewPicker(this.context);
  1147. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  1148. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  1149. // this.saveVideoDatas(audioSelectResult)
  1150. // }
  1151. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  1152. // }).catch((err: BusinessError) => {
  1153. //
  1154. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  1155. // });
  1156. // } catch (error) {
  1157. // let err: BusinessError = error as BusinessError;
  1158. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  1159. // }
  1160. //
  1161. //
  1162. //
  1163. // }
  1164. goSelectImage() {
  1165. if (!this.currentSong) {
  1166. return
  1167. }
  1168. let selectUris: Array<string> = [];
  1169. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  1170. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  1171. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; // 过滤选择媒体文件类型为IMAGE
  1172. photoSelectOptions.maxSelectNumber = 1; // 选择媒体文件的最大数目
  1173. photoPicker.select(photoSelectOptions).then(async (photoSelectResult: photoAccessHelper.PhotoSelectResult) => {
  1174. //用一个全局变量存储返回的uri
  1175. selectUris = photoSelectResult.photoUris;
  1176. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  1177. //使用fs.openSync接口,通过uri打开这个文件得到fd
  1178. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  1179. console.info('file fd: ' + file.fd);
  1180. let name = await MD5.digestSync(this.videoUrl)
  1181. let imagePath = this.context.filesDir + FileUtil.separator + name
  1182. imagePath = fileUri.getUriFromPath(imagePath)
  1183. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  1184. fileIo.copyFileSync(file.fd, file2.fd)
  1185. fileIo.closeSync(file);
  1186. fileIo.closeSync(file2);
  1187. this.cover = imagePath
  1188. if (this.currentSong) {
  1189. this.currentSong.pixelMapPath = imagePath
  1190. }
  1191. this.table.updatePixelMapPath(this.videoUrl, this.cover, (success: boolean, error?: string) => {
  1192. if (success) {
  1193. this.doUpdateData()
  1194. console.log(" onecold 更新音乐封面成功,数据库已同步");
  1195. } else {
  1196. console.error(" onecold 更新音乐封面数据库失败原因: " + error);
  1197. }
  1198. });
  1199. LogUtil.debug("onecold this.cover =" + this.cover)
  1200. }).catch((err: BusinessError) => {
  1201. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  1202. })
  1203. }
  1204. // 拉起picker选择文件管理器
  1205. async callFilePickerSelectFile(): Promise<void> {
  1206. try {
  1207. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  1208. DocumentSelectOptions.multiAuthMode = true
  1209. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  1210. let documentPicker = new picker.DocumentViewPicker();
  1211. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  1212. Logger.info(TAG,
  1213. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  1214. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  1215. this.saveVideoDatas(DocumentSelectResult)
  1216. }
  1217. }).catch((err: BusinessError) => {
  1218. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  1219. });
  1220. } catch (err) {
  1221. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  1222. }
  1223. }
  1224. showWarnIsDeleteFile(item: VideoItem, index: string, filePath: string) {
  1225. //操作确认类弹出框
  1226. DialogHelper.showAlertDialog({
  1227. maskColor: Color.Transparent,
  1228. content: "确定要删除这个文件吗?",
  1229. backgroundColor: Color.Grey,
  1230. transition: AnimationHelper.transitionInUp(555),
  1231. onAction: (action) => {
  1232. if (action == DialogAction.ONE) {
  1233. // ToastUtil.showToast(`您点击了取消按钮`);
  1234. } else if (action == DialogAction.TWO) {
  1235. // ToastUtil.showToast(`您点击了确认按钮`);
  1236. this.doDelete(item, index + '', filePath)
  1237. }
  1238. }
  1239. })
  1240. }
  1241. //删除单个索引index的视频
  1242. doDelete(item: VideoItem, index: string, filePath: string) {
  1243. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1244. Logger.info(TAG, 'delete filePath = ' + filePath);
  1245. if (item.type === CommonConstants.TYPE_IS_DIR) {
  1246. //旧文件删除
  1247. this.table.deleteDataForParentPath(item.filePath, () => {
  1248. FileUtil.rmdir(filePath).then(() => {
  1249. this.videoLocalList.splice(Number(index), 1)
  1250. this.deleteCache(this.currentPath)
  1251. this.getSortedFiles(this.currentPath, true)
  1252. }).catch((error: BusinessError) => {
  1253. console.error(error.message);
  1254. });
  1255. });
  1256. } else {
  1257. this.table.deleteData(item, () => {
  1258. FileUtil.unlink(filePath).then(() => {
  1259. this.videoLocalList.splice(Number(index), 1)
  1260. this.deleteCache(this.currentPath)
  1261. this.getSortedFiles(this.currentPath, true)
  1262. }).catch((error: BusinessError) => {
  1263. console.error(error.message);
  1264. });
  1265. });
  1266. }
  1267. }
  1268. }
  1269. //重命名的对话框
  1270. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  1271. DialogHelper.showTextInputDialog({
  1272. title: '重命名',
  1273. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  1274. maskColor: Color.Transparent,
  1275. backgroundColor: Color.Grey,
  1276. transition: AnimationHelper.transitionInDown(666),
  1277. onChange: (text) => {
  1278. console.error("onChange: " + text);
  1279. },
  1280. onAction: (action, dialogId, content) => {
  1281. // ToastUtil.showToast('content = ' +content)
  1282. if (action == DialogAction.TWO) {
  1283. const newName = content
  1284. const newPath = this.currentPath + '/' + newName
  1285. console.log("onecold item = " + item.type);
  1286. this.doReName(index, newName, filePath, newPath, item)
  1287. }
  1288. }
  1289. })
  1290. }
  1291. //剪切 移动到另个文件夹的对话框
  1292. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1293. Logger.info('onecold showCutDialog')
  1294. let mList: Array<string> = []
  1295. let rPath = this.rootPath
  1296. if (isCurrent) {
  1297. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1298. rPath = this.currentPath
  1299. } else {
  1300. mList = Utility.getNameList(this.dirList);
  1301. rPath = this.rootPath
  1302. }
  1303. let dataBean = new BubbleBean()
  1304. dataBean.data = mList
  1305. dataBean.onItemClick = (i) => {
  1306. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1307. Logger.info('newPath = ' + newPath)
  1308. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  1309. ToastUtil.showToast('移动成功')
  1310. this.table.deleteData(item, () => {
  1311. });
  1312. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1313. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1314. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1315. CommonConstants.TYPE_LOCAL, true);
  1316. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1317. this.table.insert(newItem, (id: number) => {
  1318. //加入数据库
  1319. });
  1320. }
  1321. this.cache.delete(this.currentPath); // 删除原路径缓存
  1322. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1323. this.getSortedFiles(this.currentPath, true)
  1324. }).catch((error: BusinessError) => {
  1325. console.error(error.message);
  1326. });
  1327. XPopup.dismissTop()
  1328. }
  1329. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1330. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1331. popupPosition = PopupPosition.TOP
  1332. }
  1333. if (index <= 3) {
  1334. popupPosition = PopupPosition.BOTTOM
  1335. }
  1336. let pup:XPopup
  1337. if(this.isDarkMode){
  1338. pup = XPopup.Builder()
  1339. .setPopupPosition(popupPosition)
  1340. .atView(id)
  1341. // .setHeight(this.isCoverOpacity()?100:420)
  1342. .setBackgroundColor(Color.Black)
  1343. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1344. .show()
  1345. }else {
  1346. pup = XPopup.Builder()
  1347. .setPopupPosition(popupPosition)
  1348. .atView(id)
  1349. // .setHeight(this.isCoverOpacity()?280:420)
  1350. .setBackgroundColor(Color.White)
  1351. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1352. .show()
  1353. }
  1354. }
  1355. //复制 到另个文件夹的对话框
  1356. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  1357. Logger.info('onecoldv showCopyDialog')
  1358. let mList: Array<string> = []
  1359. let rPath = this.rootPath
  1360. if (isCurrent) {
  1361. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1362. rPath = this.currentPath
  1363. } else {
  1364. mList = Utility.getNameList(this.dirList);
  1365. rPath = this.rootPath
  1366. }
  1367. let dataBean = new BubbleBean()
  1368. dataBean.data = mList
  1369. dataBean.isCopy = true
  1370. dataBean.onItemClick = (i) => {
  1371. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  1372. Logger.info('newPath = ' + newPath)
  1373. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  1374. ToastUtil.showToast('复制成功')
  1375. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  1376. this.getSortedFiles(this.currentPath)
  1377. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1378. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1379. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1380. CommonConstants.TYPE_LOCAL, true);
  1381. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1382. this.table.insert(newItem, (id: number) => {
  1383. //加入数据库
  1384. });
  1385. }
  1386. }).catch((error: BusinessError) => {
  1387. console.error(error.message);
  1388. });
  1389. XPopup.dismissTop()
  1390. }
  1391. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  1392. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  1393. popupPosition = PopupPosition.TOP
  1394. }
  1395. if (index <= 3) {
  1396. popupPosition = PopupPosition.BOTTOM
  1397. }
  1398. // let pup = XPopup.Builder()
  1399. // .setPopupPosition(popupPosition)
  1400. // .atView(id)
  1401. // .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1402. // .show()
  1403. let pup:XPopup
  1404. if (this.isDarkMode) {
  1405. pup = XPopup.Builder()
  1406. .setPopupPosition(popupPosition)
  1407. .atView(id)
  1408. .setMaxHeight('60%')
  1409. .setBackgroundColor(Color.Black)
  1410. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1411. .show();
  1412. }else {
  1413. pup = XPopup.Builder()
  1414. .setPopupPosition(popupPosition)
  1415. .atView(id)
  1416. .setMaxHeight('60%')
  1417. .setBackgroundColor(Color.White)
  1418. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1419. .show();
  1420. }
  1421. }
  1422. //重命名索引index的视频
  1423. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  1424. FileUtil.rename(oldPath, newPath).then(async () => {
  1425. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1426. if (info.type === CommonConstants.TYPE_IS_DIR) {
  1427. //如果是文件夹先删除源数据,再添加新数据
  1428. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  1429. if (success) {
  1430. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  1431. } else {
  1432. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  1433. }
  1434. });
  1435. this.scanDirectory(newPath)
  1436. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  1437. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  1438. if (success) {
  1439. console.log(" onecold 重命名成功,数据库已同步");
  1440. } else {
  1441. console.error(" onecold 重命名数据库失败原因: " + error);
  1442. }
  1443. });
  1444. }
  1445. let mediaItem: VideoItem =
  1446. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, true);
  1447. this.videoLocalList[index] = mediaItem;
  1448. }
  1449. this.cache.delete(this.currentPath)
  1450. this.getSortedFiles(this.currentPath, true)
  1451. }).catch((error: BusinessError) => {
  1452. console.error(error.message);
  1453. });
  1454. }
  1455. build() {
  1456. Scroll() {
  1457. Column() {
  1458. Column(){
  1459. Line().width('100%').height('100%')
  1460. }
  1461. .height(this.isPhoneLan()?0:px2vp(AppUtil.getStatusBarHeight()))
  1462. .backgroundColor(this.isCustomizeBg?Color.Transparent:$r('app.color.title_bar_bg'))
  1463. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
  1464. TitleBar({ model: $titleBarModel })
  1465. .id('pup_positon_music')
  1466. Stack() {
  1467. Column() {
  1468. XComponent({
  1469. id: 'xcomponentId',
  1470. type: 'surface',
  1471. libraryname: 'ijkplayer_napi',
  1472. controller: this.xcomponentController
  1473. })
  1474. .onLoad((event?: object) => {
  1475. if (!!event) {
  1476. this.initDelayPlay(event);
  1477. }
  1478. })
  1479. .onDestroy(() => {
  1480. })
  1481. .width('100%')// .width(this.videoWidth)
  1482. .aspectRatio(this.videoAspectRatio)
  1483. }
  1484. .aspectRatio(this.videoAspectRatio)
  1485. .justifyContent(FlexAlign.Center)
  1486. .backgroundColor(Color.Transparent)
  1487. .visibility(Visibility.Hidden)
  1488. .height(CommonConstants.FULL_PERCENT)
  1489. .width(CommonConstants.FULL_PERCENT)
  1490. Column() {
  1491. this.tabTitle()
  1492. this.listViewTitle()
  1493. this.getGridView()
  1494. this.getListView()
  1495. }
  1496. .layoutWeight(1)
  1497. .height('100%')
  1498. Row() {
  1499. Button(this.isAllSelected ? '全不选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  1500. .width('35%')
  1501. .height(60)
  1502. .margin({ top: 10, bottom: 10, right: 6 })
  1503. .backgroundColor($r('app.color.tab_item_bg'))
  1504. .onClick(() => {
  1505. if (this.isAllSelected) {
  1506. // 全不选
  1507. this.selectedFiles = [];
  1508. } else {
  1509. // 全选
  1510. this.selectedFiles = [...this.getCurFileList()];
  1511. }
  1512. this.isAllSelected = !this.isAllSelected;
  1513. })
  1514. Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  1515. .width('35%')
  1516. .height(60)
  1517. .id('music_cut')
  1518. .margin({ top: 10, bottom: 10, right: 6 })
  1519. .backgroundColor($r('app.color.tab_item_bg'))
  1520. .onClick(() => {
  1521. this.showCutDialogForMultipleFiles(false, 'music_cut')
  1522. })
  1523. Button('移动', { type: ButtonType.Circle, stateEffect: true })
  1524. .width('35%')
  1525. .height(60)
  1526. .id('music_cut_current')
  1527. .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  1528. .margin({ top: 10, bottom: 10, right: 6 })
  1529. .backgroundColor($r('app.color.tab_item_bg'))
  1530. .onClick(() => {
  1531. this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  1532. })
  1533. Button('复制', { type: ButtonType.Circle, stateEffect: true })
  1534. .width('35%')
  1535. .height(60)
  1536. .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  1537. .margin({ top: 10, bottom: 10, right: 6 })
  1538. .backgroundColor($r('app.color.tab_item_bg'))
  1539. .onClick(() => {
  1540. this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  1541. })
  1542. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  1543. .width('35%')
  1544. .height(60)
  1545. .margin({ top: 10, bottom: 10, right: 6 })
  1546. .visibility(this.isFavMusic?Visibility.None:Visibility.Visible)
  1547. .backgroundColor($r('app.color.tab_item_bg'))
  1548. .onClick(() => {
  1549. this.showWarnIsDelete()
  1550. })
  1551. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  1552. .width('35%')
  1553. .height(60)
  1554. .margin({ top: 10, bottom: 10, right: 6 })
  1555. .backgroundColor($r('app.color.tab_item_bg'))
  1556. .onClick(() => {
  1557. this.selectedFiles = [];
  1558. this.isAllSelected = false
  1559. this.isMultiSelect = false
  1560. })
  1561. }
  1562. .width('100%')
  1563. .justifyContent(FlexAlign.Center)
  1564. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  1565. .opacity(this.isMultiSelect ? 1 : 0)
  1566. .animation({
  1567. duration: 666,
  1568. curve: 'ease-in-out' // 可选动画曲线
  1569. })
  1570. .position({ bottom:this.isPhoneLan()?130: 168 }) // 将 Row 固定在底部
  1571. // Column() {
  1572. // Button('导入音乐', { type: ButtonType.Capsule, stateEffect: true })
  1573. // .width('50%')
  1574. // .height(55)
  1575. // .margin({ top: 50, bottom: 40 })
  1576. // .backgroundColor($r('app.color.title_bar_bg'))
  1577. //
  1578. // .onClick(() => {
  1579. // this.showSheelDialog()
  1580. // })
  1581. //
  1582. // }
  1583. // .height('100%')
  1584. // .justifyContent(FlexAlign.Center)
  1585. // .opacity(this.isZero ? 1 : 0)
  1586. // .visibility(this.isZero && this.modeType === 0 ? Visibility.None : Visibility.None)
  1587. // .animation({
  1588. // duration: 666,
  1589. // curve: 'ease-in-out' // 可选动画曲线
  1590. // })
  1591. // .width('100%')
  1592. }
  1593. .width('100%')
  1594. .height('100%')
  1595. .alignContent(Alignment.Top)
  1596. Column() {
  1597. this.PlayController()
  1598. }
  1599. .hitTestBehavior(HitTestMode.Transparent)
  1600. .position({ bottom: 0 }) // 将 Row 固定在底部
  1601. .opacity(this.barOpacity)
  1602. }
  1603. .width('100%')
  1604. .height('100%')
  1605. .backgroundImage(this.isCustomizeBg?this.customizeBgPath:$r('app.color.bottom_control_background'))
  1606. .backgroundImageSize(this.isCoverOpacity()?{width:'100%'}:{ height: '100%'})
  1607. .backgroundImagePosition(Alignment.Center)
  1608. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  1609. }
  1610. }
  1611. // 处理文件选择的函数
  1612. handleFileSelection(item: VideoItem, checked: boolean) {
  1613. if (checked) {
  1614. this.selectedFiles.push(item);
  1615. } else {
  1616. const index = this.selectedFiles.indexOf(item);
  1617. if (index > -1) {
  1618. this.selectedFiles.splice(index, 1);
  1619. }
  1620. }
  1621. }
  1622. showWarnIsDelete() {
  1623. //操作确认类弹出框
  1624. DialogHelper.showAlertDialog({
  1625. content: "确定要删除这些文件吗?",
  1626. transition: AnimationHelper.transitionInUp(666),
  1627. maskColor: Color.Transparent,
  1628. backgroundColor: Color.Grey,
  1629. onAction: (action) => {
  1630. if (action == DialogAction.ONE) {
  1631. // ToastUtil.showToast(`您点击了取消按钮`);
  1632. } else if (action == DialogAction.TWO) {
  1633. // ToastUtil.showToast(`您点击了确认按钮`);
  1634. this.deleteMultipleFiles()
  1635. }
  1636. }
  1637. })
  1638. }
  1639. //多选删除文件
  1640. deleteMultipleFiles() {
  1641. if (ArrayUtil.isNotEmpty(this.selectedFiles)) {
  1642. this.selectedFiles.forEach((item) => {
  1643. Logger.info(TAG, 'delete filePath = ' + item.filePath);
  1644. if (item.type === CommonConstants.TYPE_IS_DIR) {
  1645. this.table.deleteDataForParentPath(item.filePath, () => {
  1646. FileUtil.rmdir(item.filePath).then(() => {
  1647. this.videoLocalList = this.videoLocalList.filter(v => v !== item);
  1648. this.selectedFiles = [];
  1649. this.isMultiSelect = false
  1650. this.isAllSelected = false
  1651. this.cache.delete(this.currentPath);
  1652. this.getSortedFiles(this.currentPath, true);
  1653. }).catch((error: Error) => {
  1654. console.error(error.message);
  1655. });
  1656. });
  1657. } else {
  1658. this.table.deleteData(item, () => {
  1659. FileUtil.unlink(item.filePath).then(() => {
  1660. this.videoLocalList = this.videoLocalList.filter(v => v !== item);
  1661. this.selectedFiles = [];
  1662. this.isMultiSelect = false
  1663. this.isAllSelected = false
  1664. this.cache.delete(this.currentPath);
  1665. this.getSortedFiles(this.currentPath, true);
  1666. }).catch((error: Error) => {
  1667. console.error(error.message);
  1668. });
  1669. });
  1670. }
  1671. });
  1672. }
  1673. }
  1674. //多选移动文件
  1675. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  1676. Logger.info('onecold showCutDialogForMultipleFiles')
  1677. let mList: Array<string> = []
  1678. let rPath = this.rootPath
  1679. if (isCurrent) {
  1680. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1681. rPath = this.currentPath
  1682. } else {
  1683. mList = Utility.getNameList(this.dirList);
  1684. rPath = this.rootPath
  1685. }
  1686. let dataBean = new BubbleBean();
  1687. dataBean.data = mList;
  1688. dataBean.onItemClick = (i) => {
  1689. const newDirPath = rPath + '/' + mList[i];
  1690. // Logger.info('newDirPath = ' + newDirPath)
  1691. this.selectedFiles.forEach((item) => {
  1692. const newPath = newDirPath + '/' + item.fileName;
  1693. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  1694. ToastUtil.showToast('移动成功');
  1695. this.table.deleteData(item, () => {
  1696. this.cache.delete(this.currentPath); // 删除原路径缓存
  1697. this.cache.delete(newDirPath); // 删除目标路径缓存
  1698. this.getSortedFiles(this.currentPath, true);
  1699. });
  1700. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1701. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1702. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1703. CommonConstants.TYPE_LOCAL, true);
  1704. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1705. this.table.insert(newItem, (id: number) => {
  1706. //加入数据库
  1707. });
  1708. }
  1709. }).catch((error: Error) => {
  1710. console.error(error.message);
  1711. });
  1712. });
  1713. this.isMultiSelect = false
  1714. this.selectedFiles = [];
  1715. this.isAllSelected = false
  1716. XPopup.dismissTop();
  1717. };
  1718. // let pup = XPopup.Builder()
  1719. // .setPopupPosition(PopupPosition.TOP)
  1720. // .atView(viewId)
  1721. // .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1722. // .show();
  1723. let pup:XPopup
  1724. if (this.isDarkMode) {
  1725. pup = XPopup.Builder()
  1726. .setPopupPosition(PopupPosition.TOP)
  1727. .atView(viewId)
  1728. .setBackgroundColor(Color.Black)
  1729. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1730. .show();
  1731. }else {
  1732. pup = XPopup.Builder()
  1733. .setPopupPosition(PopupPosition.TOP)
  1734. .atView(viewId)
  1735. .setBackgroundColor(Color.White)
  1736. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1737. .show();
  1738. }
  1739. }
  1740. doFav(item:VideoItem){
  1741. LogUtil.info('onecold doFav isFav=' +item.isFav)
  1742. let isFav = 0
  1743. if(Utility.getIsFav(this.favList,item)){
  1744. isFav = 0
  1745. }else{
  1746. isFav = 1
  1747. }
  1748. this.table.updateIsFavByFilePath(item.filePath,isFav, async (result: boolean) => {
  1749. if(result){
  1750. if(isFav===1){
  1751. ToastUtil.showToast('收藏成功');
  1752. }else{
  1753. ToastUtil.showToast('取消收藏成功');
  1754. }
  1755. this.deleteCache(this.currentPath)
  1756. this.getFavList(false)
  1757. if(this.modeType===0&&!this.isFavMusic){
  1758. LogUtil.info('onecold doFav currentPath ='+ this.currentPath)
  1759. this.getSortedFiles(this.currentPath)
  1760. }
  1761. workerInstance.postMessage({ code: 2, data: this.context });
  1762. workerInstance.postMessage({ code: 3, data: this.context });
  1763. workerInstance.postMessage({ code: 4, data: this.context });
  1764. }
  1765. })
  1766. }
  1767. //多选复制文件
  1768. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  1769. console.log('onecold showCopyDialogForMultipleFiles');
  1770. let mList: Array<string> = []
  1771. let rPath = this.rootPath
  1772. if (isCurrent) {
  1773. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  1774. rPath = this.currentPath
  1775. } else {
  1776. mList = Utility.getNameList(this.dirList);
  1777. rPath = this.rootPath
  1778. }
  1779. let dataBean = new BubbleBean();
  1780. dataBean.data = mList;
  1781. dataBean.isCopy = true
  1782. dataBean.onItemClick = (i) => {
  1783. const newDirPath = rPath + '/' + mList[i];
  1784. // Logger.info('newDirPath = ' + newDirPath)
  1785. this.selectedFiles.forEach((item) => {
  1786. const newPath = newDirPath + '/' + item.fileName;
  1787. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  1788. ToastUtil.showToast('复制成功');
  1789. this.cache.delete(newDirPath); // 删除目标路径缓存
  1790. this.getSortedFiles(this.currentPath);
  1791. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  1792. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  1793. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  1794. CommonConstants.TYPE_LOCAL, true);
  1795. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  1796. this.table.insert(newItem, (id: number) => {
  1797. //加入数据库
  1798. });
  1799. }
  1800. }).catch((error: Error) => {
  1801. console.error(error.message);
  1802. });
  1803. });
  1804. this.isMultiSelect = false
  1805. this.selectedFiles = [];
  1806. this.isAllSelected = false
  1807. XPopup.dismissTop();
  1808. };
  1809. let pup:XPopup
  1810. if (this.isDarkMode) {
  1811. pup = XPopup.Builder()
  1812. .setPopupPosition(PopupPosition.TOP)
  1813. .atView(viewId)
  1814. .setBackgroundColor(Color.Black)
  1815. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1816. .show();
  1817. }else {
  1818. pup = XPopup.Builder()
  1819. .setPopupPosition(PopupPosition.TOP)
  1820. .atView(viewId)
  1821. .setBackgroundColor(Color.White)
  1822. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  1823. .show();
  1824. }
  1825. }
  1826. @Builder
  1827. private DirItem(item: VideoItem, index?: number) {
  1828. Row() {
  1829. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  1830. $r('app.media.music_group'))
  1831. .height(33)
  1832. .width(33)
  1833. .alt($r('app.media.music_group'))
  1834. .borderRadius('100%')
  1835. .clip(true)
  1836. .margin({ left: 20, top: 8, bottom: 8 })
  1837. Column() {
  1838. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  1839. .fontSize(16)
  1840. .maxLines(1)// .width('88%')
  1841. .animation({
  1842. duration: 555,
  1843. curve: 'ease-in-out',
  1844. })
  1845. .transition({
  1846. type: TransitionType.Insert,
  1847. opacity: 0,
  1848. translate: { x: 160 }
  1849. })
  1850. .margin({ left: 10, right: 20 })
  1851. .fontColor($r('app.color.text_color'))
  1852. Row() {
  1853. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  1854. .fontSize(11)
  1855. .padding({ top: 8 })
  1856. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  1857. .fontColor($r('app.color.text_color'))
  1858. .margin({ left: 10 })
  1859. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  1860. .fontSize(11)
  1861. .padding({ top: 8 })
  1862. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  1863. .fontColor($r('app.color.text_color'))
  1864. .margin({ left: 10 })
  1865. Blank()
  1866. }
  1867. }
  1868. .height('100%')
  1869. .layoutWeight(1)
  1870. .justifyContent(FlexAlign.Center)
  1871. .alignItems(HorizontalAlign.Start)
  1872. Blank()
  1873. Image($r('app.media.arrow_right'))
  1874. .height(25)
  1875. .margin({ right: 10 })
  1876. .alignSelf(ItemAlign.Center)
  1877. .id(item.filePath)
  1878. }
  1879. .height(58)
  1880. .width('100%')
  1881. .visibility(this.isShowDir(item.name)?Visibility.Visible:Visibility.None)
  1882. .opacity(this.opacityItem) // 绑定透明度
  1883. .stateStyles({
  1884. pressed: { opacity: 0.6 } // 按压反馈
  1885. })
  1886. }
  1887. isShowDir(dirName:string){
  1888. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  1889. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  1890. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  1891. if(dirName ===undefined)
  1892. return true
  1893. if(dirName === LocalMusic.STR_LOCK_VIDEO){
  1894. return this.isShowSimi
  1895. }
  1896. if(dirName === LocalMusic.STR_FAC_VIDEO){
  1897. return this.isShowFAV
  1898. }
  1899. if(dirName === LocalMusic.STR_HISTORY_MUSIC){
  1900. return this.isShowHistory
  1901. }
  1902. return true
  1903. }
  1904. @State opacityItem: number = 1; // 控制透明度的状态变量
  1905. @Builder
  1906. private MusicItem(item: VideoItem, index?: number) {
  1907. Row() {
  1908. Stack() {
  1909. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  1910. .height(33)
  1911. .width(33)
  1912. .alt($r('app.media.music_red'))
  1913. .borderRadius('100%')
  1914. .clip(true)
  1915. .opacity(this.opacityItem)// 绑定透明度
  1916. .margin({ left: 20 })
  1917. }
  1918. .width('15%')
  1919. Column() {
  1920. Column() {
  1921. Text(item.name)
  1922. .fontSize(14)
  1923. .maxLines(1)
  1924. .animation({
  1925. duration: 555,
  1926. curve: 'Linear',
  1927. })
  1928. .fontColor(this.currentSong?.filePath === item.filePath ? $r('app.color.title_bar_bg_text') :
  1929. $r('app.color.text_color'))
  1930. .margin({ left: 10 })
  1931. Row() {
  1932. Text(StrUtil.isEmpty(item.artist) ? item.cTime : item.artist + ' ' + item?.album)
  1933. .fontSize(11)
  1934. .padding({ top: 8 })
  1935. .fontColor(this.currentSong?.filePath === item.filePath ? $r('app.color.title_bar_bg_text') :
  1936. $r('app.color.text_color'))
  1937. .margin({ left: 10 })
  1938. Blank()
  1939. Text(item.size)
  1940. .fontSize(11)
  1941. .padding({ top: 8 })
  1942. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  1943. .fontColor(this.currentSong?.filePath === item.filePath ? $r('app.color.title_bar_bg_text') :
  1944. $r('app.color.text_color'))
  1945. .margin({ left: 10 })
  1946. }
  1947. }
  1948. .height('100%')
  1949. .width('100%')
  1950. .justifyContent(FlexAlign.Center)
  1951. .alignItems(HorizontalAlign.Start)
  1952. }
  1953. .height('100%')
  1954. .width('65%')
  1955. Column() {
  1956. Checkbox({ name: 'checkbox' + index })
  1957. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  1958. .selectedColor(0x39a2db)
  1959. .shape(CheckBoxShape.CIRCLE)
  1960. .opacity(this.isMultiSelect ? 1 : 0)
  1961. .animation({
  1962. duration: 666,
  1963. curve: 'Smooth' // 可选动画曲线
  1964. })
  1965. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  1966. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  1967. .margin({ left: 20, top: 8, bottom: 8 })
  1968. .width(22)
  1969. .height(22)
  1970. ImageAnimator()
  1971. .images(this.imagesF)// 动画数组
  1972. .duration(1000)// 持续
  1973. .state(this.animationState)// 动画状态
  1974. .fillMode(FillMode.Forwards)
  1975. .width(18)
  1976. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  1977. Visibility.None)
  1978. .height(18)
  1979. .iterations(-1) // 播放次数
  1980. }
  1981. .width('18%')
  1982. }
  1983. .width('100%')
  1984. .height(58)
  1985. .justifyContent(FlexAlign.SpaceBetween)
  1986. .stateStyles({
  1987. pressed: { opacity: 0.6 } // 按压反馈
  1988. })
  1989. }
  1990. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  1991. @Builder
  1992. tabTitle() {
  1993. Column() {
  1994. // 使用 Stack 布局来实现绝对定位效果
  1995. Stack() {
  1996. // 背景动画容器
  1997. Row() {
  1998. ForEach(this.tabs, (i: string, index) => {
  1999. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2000. Flex()
  2001. .backgroundColor($r('app.color.tab_item_bg'))
  2002. .borderRadius(20)
  2003. .padding(10)
  2004. .margin(6)
  2005. .width('100%')
  2006. .height('100%')
  2007. .visibility(this.modeType === index ? Visibility.Visible : Visibility.None)
  2008. .opacity(this.modeType === index ? 1 : 0)
  2009. .animation({
  2010. duration: 666,
  2011. playMode: PlayMode.Normal,
  2012. curve: 'ease-in-out'
  2013. });
  2014. }
  2015. .layoutWeight(1)
  2016. .margin({ left: this.currentBreakpoint !== BreakpointTypeEnum.SM?50:5,
  2017. right: this.currentBreakpoint !== BreakpointTypeEnum.SM?50:5, bottom: 1 });
  2018. });
  2019. }
  2020. .width('100%')
  2021. .height(50);
  2022. // 导航栏容器
  2023. Row() {
  2024. ForEach(this.tabs, (item: string, index) => {
  2025. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  2026. Text(item)
  2027. .fontSize(16)
  2028. .fontColor(this.modeType === index ? Color.White : $r('app.color.text_color'))
  2029. .padding(15)
  2030. .onClick(() => {
  2031. this.modeType = index;
  2032. this.onModeChange();
  2033. });
  2034. }
  2035. .layoutWeight(1)
  2036. .stateStyles({
  2037. pressed: { opacity: 0.6 } // 按压反馈
  2038. });
  2039. });
  2040. }
  2041. .width('100%')
  2042. .height(this.topBarHeight)
  2043. .opacity(this.barOpacity)
  2044. .backgroundColor(Color.Transparent);
  2045. }
  2046. .width('100%')
  2047. .height(this.topBarHeight)
  2048. .opacity(this.barOpacity)
  2049. Line().width('100%').height(1).backgroundColor($r('app.color.index_background'))
  2050. .opacity(this.barOpacity)
  2051. .visibility(this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
  2052. }
  2053. }
  2054. @Builder
  2055. listViewTitle() {
  2056. Column() {
  2057. Row({ space: 8 }) {
  2058. Row({ space: 8 }) {
  2059. Image($r("app.media.hm_playlist"))
  2060. .width(25)
  2061. .margin({ left: 8 })
  2062. .fillColor('#ff5186')
  2063. Text(`共找到${this.artistList.length}位艺术家`)
  2064. .fontColor($r('app.color.text_color'))
  2065. .fontSize(14)
  2066. .opacity(this.opacityItem)
  2067. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  2068. Text(`共找到${this.albumList.length}张专辑`)
  2069. .fontColor($r('app.color.text_color'))
  2070. .opacity(this.opacityItem)
  2071. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2072. .fontSize(14)
  2073. }
  2074. .layoutWeight(1)
  2075. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  2076. Row() {
  2077. TextInput({
  2078. placeholder: this.modeType === 2 ? '输入艺术家名称...' : '输入专辑名称...',
  2079. text: this.searchText
  2080. })
  2081. .height(35)
  2082. .onChange((value: string) => {
  2083. this.onSearchInput(value);
  2084. })
  2085. .layoutWeight(1)
  2086. Text(`取消`)
  2087. .margin({ left: 10, right: 10 })
  2088. .fontColor($r('app.color.text_color'))
  2089. .fontSize(16)
  2090. .onClick(() => {
  2091. this.isSearchMode = false
  2092. this.searchText = ''
  2093. if (this.modeType === 2) {
  2094. this.updateListData(this.artistList)
  2095. } else {
  2096. this.updateListData(this.albumList)
  2097. }
  2098. })
  2099. }
  2100. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  2101. .animation({
  2102. duration: 666,
  2103. curve: 'ease-in-out' // 可选动画曲线
  2104. })
  2105. Blank()
  2106. Image($r("app.media.search"))
  2107. .width(25)
  2108. .visibility(this.modeType === 2 || this.modeType === 3 ? Visibility.Visible : Visibility.None)
  2109. .animation({
  2110. duration: 666,
  2111. curve: 'ease-in-out' // 可选动画曲线
  2112. })// .opacity(this.opacityItem)
  2113. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  2114. .onClick(() => {
  2115. this.isSearchMode = true
  2116. })
  2117. Image($r("app.media.top_rank"))
  2118. .width(25)// .opacity(this.opacityItem)
  2119. .animation({
  2120. duration: 666,
  2121. curve: 'ease-in-out' // 可选动画曲线
  2122. })
  2123. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  2124. .onClick(() => {
  2125. this.showRankDialog()
  2126. })
  2127. }
  2128. .visibility(((this.modeType === 2 || this.modeType === 3) && !this.isCanBack) ? Visibility.Visible :
  2129. Visibility.None)
  2130. .width('100%')
  2131. .padding(10)
  2132. .height(50)
  2133. .border({
  2134. width: { bottom: 1 },
  2135. color: this.isCustomizeBg?Color.Transparent:'#12ec5c87'
  2136. })
  2137. Row({ space: 8 }) {
  2138. Row({ space: 8 }) {
  2139. Image($r("app.media.hm_play"))
  2140. .width(25)
  2141. .margin({ left: 8 })
  2142. .fillColor('#ff5186')
  2143. Text(`播放全部`)
  2144. .fontColor($r('app.color.text_color'))
  2145. .fontSize(14)
  2146. .animation({
  2147. duration: 666,
  2148. curve: 'ease-in-out' // 可选动画曲线
  2149. })
  2150. Text(`(${Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL).length}首)`)
  2151. .fontColor($r('app.color.text_color'))
  2152. .fontSize(14)
  2153. .opacity(this.opacityItem)
  2154. .animation({
  2155. duration: 666,
  2156. curve: 'ease-in-out' // 可选动画曲线
  2157. })
  2158. }
  2159. .visibility(this.isSearchMode ? Visibility.None : Visibility.Visible)
  2160. .animation({
  2161. duration: 666,
  2162. curve: 'ease-in-out' // 可选动画曲线
  2163. })
  2164. .backgroundColor(this.isClickedPLayAll ? $r('app.color.button_click') : Color.Transparent)
  2165. .onTouch((event: TouchEvent) => {
  2166. if (event.type === TouchType.Down) {
  2167. this.isClickedPLayAll = true;
  2168. } else if (event.type === TouchType.Up || event.type === TouchType.Cancel) {
  2169. this.isClickedPLayAll = false;
  2170. }
  2171. })
  2172. .onClick(() => {
  2173. if (this.modeType === 0) {
  2174. if (ArrayUtil.isNotEmpty(this.getCurFileList())) {
  2175. this.doPlay(this.getCurFileList()[0])
  2176. }
  2177. } else {
  2178. if (ArrayUtil.isNotEmpty(this.mediaKuList)) {
  2179. this.doPlay(this.mediaKuList[0])
  2180. }
  2181. }
  2182. })
  2183. Row() {
  2184. TextInput({ placeholder: '输入名称...', text: this.searchText })
  2185. .height(35)
  2186. .onChange((value: string) => {
  2187. this.onSearchInput(value);
  2188. })
  2189. .layoutWeight(1)
  2190. Text(`取消`)
  2191. .margin({ left: 10, right: 10 })
  2192. .fontColor($r('app.color.text_color'))
  2193. .fontSize(16)
  2194. .onClick(() => {
  2195. this.isSearchMode = false
  2196. this.searchText = ''
  2197. this.updateListData(this.mediaKuList)
  2198. })
  2199. }
  2200. .visibility(this.isSearchMode ? Visibility.Visible : Visibility.None)
  2201. .animation({
  2202. duration: 666,
  2203. curve: 'ease-in-out' // 可选动画曲线
  2204. })
  2205. Blank()
  2206. Image($r("app.media.search"))
  2207. .width(25)// .visibility(this.modeType===1?Visibility.Visible:Visibility.None)
  2208. .animation({
  2209. duration: 666,
  2210. curve: 'ease-in-out' // 可选动画曲线
  2211. })// .opacity(this.opacityItem)
  2212. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  2213. .onClick(() => {
  2214. this.isSearchMode = true
  2215. })
  2216. Image($r("app.media.refresh"))
  2217. .width(25)
  2218. .visibility(this.isHistory || this.isCanBack || this.isSearchMode ? Visibility.None : Visibility.Visible)
  2219. .animation({
  2220. duration: 666,
  2221. curve: 'ease-in-out' // 可选动画曲线
  2222. })// .opacity(this.opacityItem)
  2223. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  2224. .onClick(() => {
  2225. if(this.isFavMusic){
  2226. this.getFavList(true)
  2227. }else{
  2228. this.deleteCache(this.currentPath)
  2229. this.getSortedFiles(this.currentPath)
  2230. }
  2231. })
  2232. Image($r("app.media.top_rank"))
  2233. .width(25)
  2234. .visibility(this.isHistory || this.isSearchMode ? Visibility.None :
  2235. Visibility.Visible)// .opacity(this.opacityItem)
  2236. .animation({
  2237. duration: 666,
  2238. curve: 'ease-in-out' // 可选动画曲线
  2239. })
  2240. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  2241. .onClick(() => {
  2242. this.showRankDialog()
  2243. })
  2244. Image(this.isMultiSelect ? $r("app.media.cancel_multi") : $r("app.media.top_flower"))
  2245. .width(24)
  2246. .margin({ right: 10 })
  2247. .fillColor('#ff5186')// .opacity(this.opacityItem)
  2248. .visibility(this.isHistory || this.isSearchMode ? Visibility.None : Visibility.Visible)
  2249. .animation({
  2250. duration: 666,
  2251. curve: 'ease-in-out' // 可选动画曲线
  2252. })
  2253. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  2254. .onClick(() => {
  2255. this.isMultiSelect = !this.isMultiSelect
  2256. })
  2257. Image($r("app.media.uninstall_green"))
  2258. .width(24)
  2259. .margin({ right: 10 })
  2260. .fillColor('#ff5186')
  2261. .visibility(this.isHistory ? Visibility.Visible : Visibility.None)
  2262. .animation({
  2263. duration: 666,
  2264. curve: 'ease-in-out' // 可选动画曲线
  2265. })
  2266. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  2267. .onClick(() => {
  2268. this.clearVideoHistory() //清空播放记录
  2269. })
  2270. }
  2271. .width('100%')
  2272. .padding(10)
  2273. .height(50)
  2274. .visibility(this.modeType === 0 || this.modeType === 1 || this.isCanBack ? Visibility.Visible : Visibility.None)
  2275. .border({
  2276. width: { bottom: 1 },
  2277. color: this.isCustomizeBg?Color.Transparent:'#12ec5c87'
  2278. })
  2279. }
  2280. .height(this.topBarHeight)
  2281. .opacity(this.barOpacity)
  2282. }
  2283. //搜索功能的实现
  2284. @State searchText: string = ''; // 用户输入内容
  2285. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  2286. @State isSearchMode: boolean = false
  2287. // 实时搜索逻辑(带防抖)
  2288. private onSearchInput(value: string) {
  2289. this.searchText = value.trim();
  2290. let mSearchList: Array<VideoItem> = []
  2291. switch (this.modeType) {
  2292. case 0:
  2293. mSearchList = this.videoLocalList
  2294. break;
  2295. case 1:
  2296. mSearchList = this.mediaKuList
  2297. break;
  2298. case 2:
  2299. mSearchList = this.artistList
  2300. break;
  2301. case 3:
  2302. mSearchList = this.albumList
  2303. break;
  2304. }
  2305. // 新增条件判断:空输入时显示所有数据
  2306. if (this.searchText === '') {
  2307. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  2308. } else {
  2309. this.filteredList = mSearchList.filter((item: VideoItem) => {
  2310. return item.name.toLowerCase().includes(this.searchText.toLowerCase());
  2311. });
  2312. }
  2313. this.updateListData(this.filteredList);
  2314. // this.isSearchMode = false; // 根据业务需求决定是否启用
  2315. }
  2316. @State dragItem: number = -1
  2317. @State scaleItem: number = -1
  2318. @State neighborItem: number = -1
  2319. @State neighborScale: number = -1
  2320. @State offsetY: number = 0
  2321. private dragRefOffset: number = 0
  2322. private ITEM_INTV: number = 78
  2323. scaleSelect(item: number): number {
  2324. if (this.scaleItem === item) {
  2325. return 1.05
  2326. } else if (this.neighborItem === item) {
  2327. return this.neighborScale
  2328. } else {
  2329. return 1
  2330. }
  2331. }
  2332. itemMove(index: number, newIndex: number): void {
  2333. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  2334. return;
  2335. }
  2336. let tmp = this.videoLocalList.splice(index, 1);
  2337. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  2338. this.dataSource.pushArrayData(this.videoLocalList)
  2339. }
  2340. // Grid布局的开始
  2341. private dragRefOffSetX: number = 0;
  2342. private dragRefOffSetY: number = 0;
  2343. private FIX_VP_X: number = 180;
  2344. private FIX_VP_Y: number = 84;
  2345. isDraggable(index: number): boolean {
  2346. return index >= 0;
  2347. }
  2348. getRowEnd(item: number) {
  2349. if (item.toString() === '0') {
  2350. return 1;
  2351. } else {
  2352. return 0;
  2353. }
  2354. }
  2355. // [Start itemMove_start]
  2356. // itemMoveGrid(index: number, newIndex: number): void {
  2357. // if (!this.isDraggable(newIndex)) {
  2358. // return;
  2359. // }
  2360. // let tmp = this.videoLocalList.splice(index, 1);
  2361. // this.videoLocalList.splice(newIndex, 0, tmp[0]);
  2362. // // this.bigItemIndex = this.videoLocalList.findIndex((item) => item === 0);
  2363. // }
  2364. isInLeft(index: number) {
  2365. return index % 2 == 0;
  2366. }
  2367. down(index: number): void {
  2368. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  2369. return;
  2370. }
  2371. this.offsetY -= this.FIX_VP_Y;
  2372. this.dragRefOffSetY += this.FIX_VP_Y;
  2373. this.itemMove(index, index + 1);
  2374. }
  2375. up(index: number): void {
  2376. if (!this.isDraggable(index - 2)) {
  2377. return;
  2378. }
  2379. this.offsetY += this.FIX_VP_Y;
  2380. this.dragRefOffSetY -= this.FIX_VP_Y;
  2381. this.itemMove(index, index - 1);
  2382. }
  2383. left(index: number): void {
  2384. if (this.isInLeft(index)) {
  2385. return;
  2386. }
  2387. if (!this.isDraggable(index - 1)) {
  2388. return;
  2389. }
  2390. this.offsetX += this.FIX_VP_X;
  2391. this.dragRefOffSetX -= this.FIX_VP_X;
  2392. this.itemMove(index, index - 1)
  2393. }
  2394. right(index: number): void {
  2395. if (!this.isInLeft(index)) {
  2396. return;
  2397. }
  2398. if (!this.isDraggable(index + 1)) {
  2399. return;
  2400. }
  2401. this.offsetX -= this.FIX_VP_X;
  2402. this.dragRefOffSetX += this.FIX_VP_X;
  2403. this.itemMove(index, index + 1)
  2404. }
  2405. @Builder
  2406. getGridView(){
  2407. Grid() {
  2408. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  2409. GridItem() {
  2410. Stack({ alignContent: Alignment.TopEnd }) {
  2411. this.MusicItemGrid(item,index)
  2412. }
  2413. }
  2414. .rowStart(0)
  2415. .rowEnd(this.getRowEnd(index))
  2416. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  2417. .zIndex(this.dragItem === index ? 1 : 0)
  2418. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  2419. .hitTestBehavior(this.isDraggable(this.videoLocalList.indexOf(item)) ? HitTestMode.Default : HitTestMode.None)
  2420. //长按拖动代码
  2421. .gesture(
  2422. GestureGroup(GestureMode.Sequence,
  2423. LongPressGesture({ repeat: true })
  2424. .onAction(() => {
  2425. this.getUIContext().animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  2426. this.scaleItem = index;
  2427. })
  2428. })
  2429. .onActionEnd(() => {
  2430. this.getUIContext().animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  2431. this.scaleItem = -1;
  2432. })
  2433. }),
  2434. PanGesture({ fingers: 1, direction: null, distance: 0 })
  2435. .onActionStart(() => {
  2436. this.dragItem = index;
  2437. this.dragRefOffSetX = 0;
  2438. this.dragRefOffSetY = 0;
  2439. })
  2440. .onActionUpdate((event: GestureEvent) => {
  2441. this.offsetX = event.offsetX - this.dragRefOffSetX;
  2442. this.offsetY = event.offsetY - this.dragRefOffSetY;
  2443. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  2444. let index = this.videoLocalList.indexOf(item);
  2445. if (this.offsetY >= this.FIX_VP_Y / 2 && (this.offsetX <= 44 && this.offsetX >= -44)) {
  2446. this.down(index);
  2447. } else if (this.offsetY <= -this.FIX_VP_Y / 2 && (this.offsetX <= 44 && this.offsetX >= -44)) {
  2448. this.up(index);
  2449. } else if (this.offsetX >= this.FIX_VP_X / 2 && (this.offsetY <= 50 && this.offsetY >= -50)) {
  2450. this.right(index);
  2451. } else if (this.offsetX <= -this.FIX_VP_Y / 2 && (this.offsetY <= 50 && this.offsetY >= -50)) {
  2452. this.left(index);
  2453. }
  2454. })
  2455. })
  2456. .onActionEnd(() => {
  2457. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  2458. this.dragItem = -1;
  2459. })
  2460. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150 }, () => {
  2461. this.scaleItem = -1;
  2462. })
  2463. })
  2464. )
  2465. .onCancel(() => {
  2466. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  2467. this.dragItem = -1;
  2468. })
  2469. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150 }, () => {
  2470. this.scaleItem = -1;
  2471. })
  2472. })
  2473. )
  2474. // [End gesture_start]
  2475. // [EndExclude GridItem_start]
  2476. }, (item: VideoItem) => item.filePath)
  2477. }
  2478. .width('100%')
  2479. .height('100%')
  2480. .editMode(true)
  2481. .scrollBar(BarState.Off)
  2482. // .columnsTemplate('1fr 1fr')
  2483. .supportAnimation(true)
  2484. .columnsTemplate('1fr '.repeat(this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM ? 2 : 4))
  2485. .columnsGap(12)
  2486. .rowsGap(12)
  2487. .visibility(this.isGridMusic?Visibility.Visible:Visibility.None)
  2488. .enableScrollInteraction(true)
  2489. }
  2490. @Builder
  2491. private MusicItemGrid(item: VideoItem, index?: number) {
  2492. Column() {
  2493. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.ic_avatar6') : item.pixelMapPath)
  2494. .height(150)
  2495. .width(150)
  2496. .alt($r('app.media.ic_avatar6'))
  2497. .borderRadius(20)
  2498. .clip(true)
  2499. .draggable(false)
  2500. .opacity(this.opacityItem)// 绑定透明度
  2501. .animation({ curve: Curve.Sharp, duration: 300 })
  2502. .margin({ left: this.currentBreakpoint !== BreakpointTypeEnum.SM?40:20 ,
  2503. right: this.currentBreakpoint !== BreakpointTypeEnum.SM?40:20})
  2504. Column() {
  2505. Column() {
  2506. Text(item.name)
  2507. .fontSize(14)
  2508. .maxLines(1)
  2509. .animation({
  2510. duration: 555,
  2511. curve: 'Linear',
  2512. })
  2513. .fontColor(this.currentSong?.filePath === item.filePath ? $r('app.color.title_bar_bg_text') :
  2514. $r('app.color.text_color'))
  2515. .margin({ left: 10 })
  2516. Row() {
  2517. Text(StrUtil.isEmpty(item.artist) ? item.cTime : item.artist + ' ' + item?.album)
  2518. .fontSize(11)
  2519. .padding({ top: 8 })
  2520. .fontColor(this.currentSong?.filePath === item.filePath ? $r('app.color.title_bar_bg_text') :
  2521. $r('app.color.text_color'))
  2522. .margin({ left: 10 })
  2523. Blank()
  2524. Text(item.size)
  2525. .fontSize(11)
  2526. .padding({ top: 8 })
  2527. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  2528. .fontColor(this.currentSong?.filePath === item.filePath ? $r('app.color.title_bar_bg_text') :
  2529. $r('app.color.text_color'))
  2530. .margin({ left: 10 })
  2531. }
  2532. }
  2533. .height('100%')
  2534. .width('100%')
  2535. .justifyContent(FlexAlign.Center)
  2536. .alignItems(HorizontalAlign.Start)
  2537. }
  2538. .layoutWeight(1)
  2539. .margin({ left: this.currentBreakpoint !== BreakpointTypeEnum.SM?40:20 ,
  2540. right: this.currentBreakpoint !== BreakpointTypeEnum.SM?40:20})
  2541. }
  2542. .width('100%')
  2543. .height(200)
  2544. .animation({ curve: Curve.Sharp, duration: 300 })
  2545. .justifyContent(FlexAlign.SpaceBetween)
  2546. .stateStyles({
  2547. pressed: { opacity: 0.6 } // 按压反馈
  2548. })
  2549. .onClick(() => {
  2550. this.doPlay(item, index)
  2551. })
  2552. }
  2553. @Builder
  2554. getListView() {
  2555. List() {
  2556. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  2557. ListItem() {
  2558. Column() {
  2559. if (item.type === CommonConstants.TYPE_IS_DIR
  2560. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  2561. this.DirItem(item, index)
  2562. } else if (item.type === CommonConstants.TYPE_IS_CSJAD) { //如果是穿山甲广告
  2563. //穿山甲
  2564. if (this.isShowAd) {
  2565. Row() {
  2566. NodeContainer(this.bannerAd.getAdComponent())
  2567. .width('92%')
  2568. .height(this.mAdSlot.getAcceptHeight())
  2569. .alignSelf(ItemAlign.Center)
  2570. .align(Alignment.Center)
  2571. // .margin({left:10})
  2572. Image($r('app.media.close'))
  2573. .height(15)
  2574. .aspectRatio(1)
  2575. .visibility(Visibility.None)
  2576. .margin({ right: 15 })// .position({ x:20 })
  2577. .onClick(() => {
  2578. this.isShowAd = false
  2579. })
  2580. Blank()
  2581. }
  2582. .opacity(this.opacityItem) // 绑定透明度
  2583. }
  2584. } else {
  2585. this.MusicItem(item, index)
  2586. }
  2587. }
  2588. .shadow(this.scaleItem === index ? {
  2589. radius: 70,
  2590. color: '#15000000',
  2591. offsetX: 0,
  2592. offsetY: 0
  2593. } :
  2594. {
  2595. radius: 0,
  2596. color: '#15000000',
  2597. offsetX: 0,
  2598. offsetY: 0
  2599. })
  2600. .animation({ curve: Curve.Sharp, duration: 300 })
  2601. }
  2602. .swipeAction((this.modeType !== 3 && this.modeType !== 2 && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  2603. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath) } : {}) //左滑
  2604. .onClick(() => {
  2605. this.doPlay(item, index)
  2606. })
  2607. //拖动List关键代码开始
  2608. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  2609. .zIndex(this.dragItem === index ? 1 : 0)
  2610. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  2611. .gesture(
  2612. GestureGroup(GestureMode.Sequence,
  2613. LongPressGesture({ repeat: true })
  2614. .onAction((event?: GestureEvent) => {
  2615. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  2616. this.scaleItem = index
  2617. })
  2618. })
  2619. .onActionEnd(() => {
  2620. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  2621. this.scaleItem = -1
  2622. })
  2623. }),
  2624. PanGesture({ fingers: 1, direction: null, distance: 0 })
  2625. .onActionStart(() => {
  2626. this.dragItem = index // 记录当前拖动项索引
  2627. this.dragRefOffset = 0 // 重置偏移基准
  2628. })
  2629. .onActionUpdate((event: GestureEvent) => {
  2630. this.offsetY = event.offsetY - this.dragRefOffset;
  2631. this.neighborItem = -1;
  2632. let indexA = this.videoLocalList.indexOf(item);
  2633. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  2634. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  2635. let value: number = 0;
  2636. if (this.offsetY < 0) {
  2637. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  2638. this.neighborItem = indexA - 1;
  2639. this.neighborScale = 1 - value / 20;
  2640. } else if (this.offsetY > 0) {
  2641. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  2642. this.neighborItem = indexA + 1;
  2643. this.neighborScale = 1 - value / 20;
  2644. }
  2645. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  2646. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  2647. this.offsetY -= this.ITEM_INTV;
  2648. this.dragRefOffset += this.ITEM_INTV;
  2649. this.itemMove(indexA, indexA + 1);
  2650. });
  2651. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  2652. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  2653. this.offsetY += this.ITEM_INTV;
  2654. this.dragRefOffset -= this.ITEM_INTV;
  2655. this.itemMove(indexA, indexA - 1);
  2656. });
  2657. }
  2658. })
  2659. .onActionEnd((event: GestureEvent) => {
  2660. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  2661. this.dragItem = -1
  2662. this.neighborItem = -1
  2663. })
  2664. animateTo({
  2665. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  2666. }, () => {
  2667. this.scaleItem = -1
  2668. })
  2669. })
  2670. )
  2671. .onCancel(() => {
  2672. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  2673. this.dragItem = -1
  2674. this.neighborItem = -1
  2675. })
  2676. animateTo({
  2677. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  2678. }, () => {
  2679. this.scaleItem = -1
  2680. })
  2681. })
  2682. ) //拖动List关键代码结束
  2683. }, (item: VideoItem) => item.filePath)
  2684. }
  2685. // .divider({ strokeWidth: 1, color: this.isDarkMode? '#333333':'#ffe9f0f0' })
  2686. .margin({ bottom: this.isCoverOpacity() ? 50 : 158 })
  2687. .cachedCount(30)
  2688. .borderRadius(20)
  2689. .layoutWeight(1)
  2690. .visibility(this.isGridMusic?Visibility.None:Visibility.Visible)
  2691. .lanes(
  2692. new BreakpointType<number>({
  2693. sm: 1,
  2694. md: 2,
  2695. lg: 3,
  2696. xl: 4,
  2697. xxl: 4
  2698. }).getValue(this.currentBreakpoint),
  2699. new BreakpointType<number>({
  2700. sm: 0,
  2701. md: 12,
  2702. lg: 16,
  2703. xl: 18,
  2704. xxl: 20
  2705. }).getValue(this.currentBreakpoint)
  2706. )
  2707. .onScrollFrameBegin((offset: number) => {
  2708. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  2709. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  2710. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  2711. this.hideDone = false;
  2712. this.getUIContext().animateTo({
  2713. duration: 300
  2714. }, () => {
  2715. this.bottomBarHeight = 55 + 0;
  2716. this.topBarHeight = 50 + 0;
  2717. this.barOpacity = 1;
  2718. this.currentYOffset = 0;
  2719. this.isHiding = false;
  2720. });
  2721. return { offsetRemain: offset };
  2722. }
  2723. if (offset > 0 && !this.hideDone) {
  2724. this.currentYOffset += offset;
  2725. if (this.currentYOffset <= 100) {
  2726. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  2727. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  2728. this.barOpacity = 1 - this.currentYOffset / 100;
  2729. } else {
  2730. this.topBarHeight = 0;
  2731. this.bottomBarHeight = 0;
  2732. this.barOpacity = 0;
  2733. this.hideDone = true;
  2734. }
  2735. this.isHiding = true;
  2736. }
  2737. if (offset < 0 && this.isHiding) {
  2738. this.hideDone = false;
  2739. this.getUIContext().animateTo({
  2740. duration: 300
  2741. }, () => {
  2742. this.bottomBarHeight = 55 + 0;
  2743. this.topBarHeight = 50 + 0;
  2744. this.barOpacity = 1;
  2745. this.currentYOffset = 0;
  2746. this.isHiding = false;
  2747. });
  2748. }
  2749. return { offsetRemain: offset };
  2750. })
  2751. }
  2752. private doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean) {
  2753. switch (item.type) {
  2754. case CommonConstants.TYPE_IS_DIR:
  2755. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  2756. this.showVerifyDialog()
  2757. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  2758. this.titleBarModel.setTitleName('最近播放')
  2759. //加载动画效果
  2760. this.updateListData(this.historyList)
  2761. // this.videoLocalList = this.historyList
  2762. if (ArrayUtil.isEmpty(this.historyList)) {
  2763. ToastUtil.showToast('最近播放记录空空如也')
  2764. }
  2765. this.isHistory = true
  2766. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  2767. } else if(item.name === LocalMusic.STR_FAC_VIDEO){
  2768. this.titleBarModel.setTitleName('我的收藏')
  2769. //加载动画效果
  2770. this.updateListData(this.favList)
  2771. if(ArrayUtil.isEmpty(this.favList)){
  2772. ToastUtil.showToast('无音乐收藏记录')
  2773. }
  2774. this.isFavMusic = true
  2775. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  2776. }else {
  2777. this.currentPath = item.filePath
  2778. this.getSortedFiles(this.currentPath)
  2779. }
  2780. break;
  2781. case CommonConstants.TYPE_IS_ARTIST:
  2782. let mList = this.artistMap.get(item.name)
  2783. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  2784. Utility.doSortListAscending(mList)
  2785. this.isCanBack = true
  2786. this.titleBarModel.setTitleName(item.name)
  2787. this.updateListData(mList)
  2788. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  2789. }
  2790. break;
  2791. case CommonConstants.TYPE_IS_ALBUM:
  2792. let albumList = this.albumMap.get(item.name)
  2793. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  2794. Utility.doSortListAscending(albumList)
  2795. this.isCanBack = true
  2796. this.titleBarModel.setTitleName(item.name)
  2797. this.updateListData(albumList)
  2798. this.titleBarModel.setLeftIconMain($r('app.media.left_back_white'))
  2799. }
  2800. break;
  2801. case CommonConstants.TYPE_IS_CSJAD:
  2802. return
  2803. break;
  2804. case CommonConstants.TYPE_LOCAL:
  2805. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  2806. this.stop();
  2807. }
  2808. if (isFromSonPlayList) { //点击来自右下角的播放列表
  2809. this.currentSong = item
  2810. if (index !== undefined) {
  2811. this.curIndex = index
  2812. }
  2813. } else {
  2814. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  2815. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  2816. this.songList = globalVideoList
  2817. this.sonDataSource.pushArrayData(this.songList)
  2818. this.currentSong = globalVideoList[this.curIndex]
  2819. }
  2820. if (FileUtil.accessSync(this.favPath)) {
  2821. this.facList = FileUtil.listFileSync(this.favPath)
  2822. this.isFac = Utility.getIsFac(this.facList, item)
  2823. }
  2824. this.videoUrl = this.currentSong.filePath
  2825. this.name = this.currentSong.name
  2826. this.cover = this.currentSong.pixelMapPath
  2827. this.startPlayOrResumePlay()
  2828. break;
  2829. }
  2830. }
  2831. @Builder
  2832. PlayController() {
  2833. Column() {
  2834. Line().width('100%').height(1).backgroundColor($r('app.color.index_background'))
  2835. .visibility(this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
  2836. Row() {
  2837. Row() {
  2838. RotatingCover({ songLabel: this.currentSong?.pixelMapPath })
  2839. Column() {
  2840. Text(this.currentSong?.name)
  2841. .fontSize(13)
  2842. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  2843. .maxLines(1)
  2844. .fontColor($r('app.color.text_color'))
  2845. .fontWeight(500)
  2846. Row() {
  2847. Text(this.currentSong?.artist)
  2848. .margin({ top: 2 })
  2849. .fontSize(11)
  2850. .fontColor($r('app.color.text_color'))
  2851. }
  2852. }
  2853. .alignItems(HorizontalAlign.Start)
  2854. .margin({ right: 22 })
  2855. }
  2856. .layoutWeight(1)
  2857. .onClick(() => {
  2858. if (ArrayUtil.isNotEmpty(this.songList)) {
  2859. this.isShowPlay = true;
  2860. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  2861. this.initLyric(lyricPath);
  2862. if (FileUtil.accessSync(this.favPath)) {
  2863. this.facList = FileUtil.listFileSync(this.favPath)
  2864. this.isFac = this.currentPath === this.favPath ? true : Utility.getIsFac(this.facList, this.currentSong)
  2865. }
  2866. } else {
  2867. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  2868. }
  2869. })
  2870. Row() {
  2871. Image($r('app.media.hm_previous'))
  2872. .height(24)
  2873. .width(24)
  2874. .margin({ left: 8, right: 16 })
  2875. .displayPriority(2)
  2876. .onClick(() => {
  2877. if (ArrayUtil.isNotEmpty(this.songList)) {
  2878. this.playPrevious()
  2879. } else {
  2880. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  2881. }
  2882. })
  2883. //播放进度条
  2884. Stack() {
  2885. Progress({
  2886. value: Math.floor(this.progressValue),
  2887. type: ProgressType.Ring,
  2888. })
  2889. .color($r('app.color.title_bar_bg'))// 进度条前景色为灰色
  2890. .backgroundColor(Color.Pink)
  2891. .height(36)
  2892. .aspectRatio(CommonConstants.ASPECT_RATIO)
  2893. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ? $r('app.media.hm_pause') : $r('app.media.hm_play2'))
  2894. .height(32)
  2895. .width(32)
  2896. .displayPriority(3)
  2897. .onClick(() => {
  2898. if (ArrayUtil.isNotEmpty(this.songList)) {
  2899. this.playOrPause()
  2900. } else {
  2901. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  2902. }
  2903. })
  2904. }
  2905. Image($r('app.media.hm_next'))
  2906. .height(24)
  2907. .width(24)
  2908. .margin({
  2909. right: 16,
  2910. left: 16
  2911. })
  2912. .displayPriority(2)
  2913. .onClick(() => {
  2914. if (ArrayUtil.isNotEmpty(this.songList)) {
  2915. this.playNext()
  2916. } else {
  2917. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  2918. }
  2919. })
  2920. Image($r('app.media.hm_playlist'))
  2921. .height(24)
  2922. .width(24)
  2923. .displayPriority(1)
  2924. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  2925. height: '95%',
  2926. dragBar: true,
  2927. showClose: true,
  2928. blurStyle: BlurStyle.Thin,
  2929. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  2930. backgroundColor: Color.Transparent,
  2931. title: {
  2932. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  2933. + `(${this.songList.length}首)`
  2934. }
  2935. })
  2936. .onClick(() => {
  2937. if (ArrayUtil.isNotEmpty(this.songList)) {
  2938. this.isShowSheet = !this.isShowSheet;
  2939. this.isFrontWhite = false
  2940. } else {
  2941. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  2942. }
  2943. })
  2944. }
  2945. }
  2946. .width('100%')
  2947. .height(this.bottomBarHeight)
  2948. .justifyContent(FlexAlign.Center)
  2949. .hitTestBehavior(HitTestMode.Transparent)
  2950. .backgroundColor(this.isCustomizeBg?Color.Transparent:$r('app.color.bottom_control_background'))
  2951. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  2952. // modalTransition: ModalTransition.DEFAULT,
  2953. transition: AnimationHelper.transitionInDown(666),
  2954. backgroundColor: 'rgba(0, 0, 0, 0.9)',
  2955. })
  2956. .padding({
  2957. left: 16,
  2958. right: 16
  2959. })
  2960. Line().width('100%').height(25).backgroundColor($r('app.color.bottom_control_background'))
  2961. // .visibility(this.isPhoneLan()?Visibility.None:this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
  2962. .visibility(this.isCustomizeBg?Visibility.Hidden:Visibility.Visible)
  2963. }
  2964. }
  2965. @State isFrontWhite: boolean = false
  2966. //播放列表布局
  2967. @Builder
  2968. PlayListSheet() {
  2969. Column() {
  2970. this.PlayList()
  2971. }
  2972. .width('100%')
  2973. .height('100%')
  2974. }
  2975. @State titleStr: string = ''
  2976. @State ablumStr: string = ''
  2977. @State artistStr: string = ''
  2978. @State lyricConStr: string = ''
  2979. @State currentEditItem: string = ''
  2980. doUpdateData() {
  2981. setTimeout(() => {
  2982. if (this.modeType === 0) {
  2983. this.deleteCache(this.currentPath)
  2984. this.getSortedFiles(this.currentPath)
  2985. }
  2986. workerInstance.postMessage({ code: 2, data: this.context });
  2987. workerInstance.postMessage({ code: 3, data: this.context });
  2988. workerInstance.postMessage({ code: 4, data: this.context });
  2989. }, 999)
  2990. }
  2991. //编辑信息
  2992. doEdit() {
  2993. if (!this.currentSong) {
  2994. return
  2995. }
  2996. if (StrUtil.isEmpty(this.titleStr)) {
  2997. ToastUtil.showToast('标题不能为空')
  2998. return
  2999. }
  3000. this.table.updateMediaInfo(this.videoUrl, this.titleStr, this.artistStr, this.ablumStr,
  3001. (success: boolean, error?: string) => {
  3002. this.isShowEdit = false
  3003. if (success) {
  3004. console.log(" onecold 编辑信息成功,数据库已同步");
  3005. ToastUtil.showToast('保存成功')
  3006. this.isShowMoreView = false
  3007. this.name = this.titleStr
  3008. if (this.currentSong) {
  3009. this.currentSong.name = this.titleStr
  3010. this.currentSong.artist = this.artistStr
  3011. this.currentSong.album = this.ablumStr
  3012. }
  3013. this.doUpdateData()
  3014. } else {
  3015. ToastUtil.showToast('保存失败' + error?.toString())
  3016. console.error(" onecold 编辑信息数据库失败原因: " + error);
  3017. }
  3018. });
  3019. if (this.lyricConStr !== this.lyricContent) {
  3020. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  3021. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  3022. let isJiaMi = false;
  3023. let realLyricPath = lyricPath
  3024. if (FileUtil.accessSync(jiaMilyricPath)) {
  3025. isJiaMi = true
  3026. realLyricPath = jiaMilyricPath
  3027. console.info("onecold doEdit找到加密本地歌词 ");
  3028. } else {
  3029. isJiaMi = false
  3030. realLyricPath = lyricPath
  3031. console.info("onecold doEdit本地歌词 ");
  3032. }
  3033. this.saveDataToFile(this.lyricConStr, realLyricPath, isJiaMi)
  3034. }
  3035. }
  3036. @Builder
  3037. editSheet() {
  3038. Scroll() {
  3039. Column() {
  3040. this.editDetail()
  3041. }
  3042. }
  3043. .width('100%')
  3044. .height('100%')
  3045. }
  3046. @Builder
  3047. editDetail() {
  3048. Column() {
  3049. if (this.currentSong) {
  3050. Row() {
  3051. Stack() {
  3052. Image(StrUtil.isEmpty(this.currentSong.pixelMapPath) ? $r('app.media.music_red') :
  3053. this.currentSong.pixelMapPath)
  3054. .height(33)
  3055. .width(33)
  3056. .borderRadius('100%')
  3057. .clip(true)
  3058. .opacity(this.opacityItem)// 绑定透明度
  3059. .margin({ left: 20 })
  3060. }
  3061. .width('15%')
  3062. Row() {
  3063. Column() {
  3064. Text(this.currentSong.name)
  3065. .fontSize(14)
  3066. .maxLines(1)
  3067. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3068. .animation({
  3069. duration: 555,
  3070. curve: 'Linear',
  3071. })
  3072. .fontColor($r('app.color.title_bar_bg'))
  3073. .margin({ left: 10 })
  3074. Row() {
  3075. Text(this.currentSong.artist)
  3076. .fontSize(11)
  3077. .maxLines(1)
  3078. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3079. .padding({ top: 8 })
  3080. .fontColor($r('app.color.title_bar_bg'))
  3081. .margin({ left: 10 })
  3082. }
  3083. }
  3084. .height('100%')
  3085. .width(100)
  3086. .visibility(this.isDarkMode?Visibility.None:Visibility.Visible)
  3087. .justifyContent(FlexAlign.Center)
  3088. .alignItems(HorizontalAlign.Start)
  3089. Button('本地封面')
  3090. .fontColor(Color.White)
  3091. .fontSize(12)
  3092. .height(38)
  3093. .width(88)
  3094. .backgroundColor($r('app.color.title_bar_bg'))
  3095. .stateEffect(true)
  3096. .margin({ right: 5, left: 12 })
  3097. .onClick(async () => {
  3098. this.goSelectImage()
  3099. })
  3100. Button('获取封面')
  3101. .fontColor(Color.White)
  3102. .fontSize(12)
  3103. .height(38)
  3104. .width(88)
  3105. .backgroundColor($r('app.color.title_bar_bg'))
  3106. .stateEffect(true)
  3107. .margin({ right: 12, left: 5 })
  3108. .onClick(async () => {
  3109. this.doSearchCover()
  3110. })
  3111. }
  3112. .height('100%')
  3113. .justifyContent(FlexAlign.Start)
  3114. .layoutWeight(1)
  3115. }
  3116. .width('100%')
  3117. .height(58)
  3118. Row() {
  3119. Text('标题:')
  3120. .fontSize(14)
  3121. .fontColor($r('app.color.text_color'))
  3122. .margin({ left: 22 })
  3123. TextInput({ text: this.currentSong?.name ? this.currentSong.name : '' })
  3124. .height(40)
  3125. .maxLines(1)
  3126. .fontSize(14)
  3127. .layoutWeight(1)
  3128. .fontColor($r('app.color.text_color'))
  3129. .margin({ right: 20, left: 10 })
  3130. .onChange((val: string) => {
  3131. this.titleStr = val
  3132. })
  3133. }
  3134. .width('100%')
  3135. .margin({ top: 10, bottom: 10 })
  3136. .justifyContent(FlexAlign.Start)
  3137. Row() {
  3138. Text('艺术家:')
  3139. .fontSize(14)
  3140. .fontColor($r('app.color.text_color'))
  3141. .margin({ left: 22 })
  3142. TextInput({ text: this.currentSong?.artist ? this.currentSong.artist : '' })
  3143. .height(40)
  3144. .maxLines(1)
  3145. .fontSize(14)
  3146. .layoutWeight(1)
  3147. .fontColor($r('app.color.text_color'))
  3148. .margin({ right: 20, left: 10 })
  3149. .onChange((val: string) => {
  3150. this.artistStr = val
  3151. })
  3152. }
  3153. .width('100%')
  3154. .margin({ top: 10, bottom: 10 })
  3155. .justifyContent(FlexAlign.Start)
  3156. Row() {
  3157. Text('专辑名:')
  3158. .fontSize(14)
  3159. .fontColor($r('app.color.text_color'))
  3160. .margin({ left: 22 })
  3161. TextInput({ text: this.currentSong?.album ? this.currentSong.album : '' })
  3162. .height(40)
  3163. .maxLines(1)
  3164. .fontSize(14)
  3165. .layoutWeight(1)
  3166. .fontColor($r('app.color.text_color'))
  3167. .margin({ right: 20, left: 10 })
  3168. .onChange((val: string) => {
  3169. this.ablumStr = val
  3170. })
  3171. }
  3172. .width('100%')
  3173. .margin({ top: 10, bottom: 10 })
  3174. .justifyContent(FlexAlign.Start)
  3175. Row() {
  3176. Text('歌词:')
  3177. .fontSize(14)
  3178. .fontColor($r('app.color.text_color'))
  3179. .margin({ left: 22 })
  3180. TextArea({ text: this.lyricContent ? this.lyricContent : '' })
  3181. .type(TextAreaType.NORMAL)
  3182. .height(275)
  3183. .fontSize(14)
  3184. .layoutWeight(1)
  3185. .fontColor($r('app.color.text_color'))
  3186. .margin({ right: 20, left: 10 })
  3187. .onChange((val: string) => {
  3188. this.lyricConStr = val
  3189. })
  3190. }
  3191. .width('100%')
  3192. .margin({ top: 10, bottom: 10 })
  3193. .justifyContent(FlexAlign.Start)
  3194. Row() {
  3195. Button('保存')
  3196. .fontColor(Color.White)
  3197. .layoutWeight(1)
  3198. .height(50)
  3199. .width(100)
  3200. .backgroundColor($r('app.color.title_bar_bg'))
  3201. .stateEffect(true)
  3202. .margin({ right: 20, bottom: 20 })
  3203. .onClick(async () => {
  3204. this.doEdit()
  3205. })
  3206. Button('取消')
  3207. .fontColor(Color.White)
  3208. .layoutWeight(1)
  3209. .height(50)
  3210. .width(100)
  3211. .backgroundColor($r('app.color.title_bar_bg'))
  3212. .stateEffect(true)
  3213. .margin({ left: 20, bottom: 20 })
  3214. .onClick(async () => {
  3215. this.isShowEdit = false
  3216. })
  3217. }
  3218. .margin({
  3219. left: 38,
  3220. right: 38,
  3221. top: 10,
  3222. bottom: 10
  3223. })
  3224. .width(250)
  3225. .height(60)
  3226. }
  3227. }
  3228. .margin({ bottom: 20 })
  3229. }
  3230. @Builder
  3231. detailSheet() {
  3232. Scroll() {
  3233. Column() {
  3234. this.songDetail()
  3235. }
  3236. }
  3237. .width('100%')
  3238. .height('100%')
  3239. }
  3240. @Builder
  3241. songDetail() {
  3242. Column() {
  3243. if (this.currentSong) {
  3244. Row() {
  3245. Stack() {
  3246. Image(StrUtil.isEmpty(this.currentSong.pixelMapPath) ? $r('app.media.music_red') :
  3247. this.currentSong.pixelMapPath)
  3248. .height(33)
  3249. .width(33)
  3250. .borderRadius('100%')
  3251. .clip(true)
  3252. .opacity(this.opacityItem)// 绑定透明度
  3253. .margin({ left: 20 })
  3254. }
  3255. .width('15%')
  3256. Column() {
  3257. Column() {
  3258. Text(this.currentSong.name)
  3259. .fontSize(14)
  3260. .maxLines(1)
  3261. .animation({
  3262. duration: 555,
  3263. curve: 'Linear',
  3264. })
  3265. .fontColor($r('app.color.text_color'))
  3266. .margin({ left: 10 })
  3267. Row() {
  3268. Text(StrUtil.isEmpty(this.currentSong.artist) ? this.currentSong.cTime :
  3269. this.currentSong.artist + ' ' + this.currentSong?.album)
  3270. .fontSize(11)
  3271. .padding({ top: 8 })
  3272. .fontColor($r('app.color.text_color'))
  3273. .margin({ left: 10 })
  3274. }
  3275. }
  3276. .height('100%')
  3277. .width('100%')
  3278. .justifyContent(FlexAlign.Center)
  3279. .alignItems(HorizontalAlign.Start)
  3280. }
  3281. .height('100%')
  3282. }
  3283. .width('100%')
  3284. .height(58)
  3285. .justifyContent(FlexAlign.SpaceBetween)
  3286. Row() {
  3287. Text('歌手名:')
  3288. .fontSize(14)
  3289. .fontColor(Color.White)
  3290. .margin({ left: 22 })
  3291. Text(this.currentSong?.artist ? this.currentSong.artist : '未知歌手')
  3292. .fontSize(14)
  3293. .fontColor(Color.White)
  3294. .margin({ left: 10 })
  3295. .layoutWeight(1)
  3296. }
  3297. .width('100%')
  3298. .margin({ top: 10, bottom: 10 })
  3299. .justifyContent(FlexAlign.Start)
  3300. Row() {
  3301. Text('专辑名:')
  3302. .fontSize(14)
  3303. .fontColor(Color.White)
  3304. .margin({ left: 22 })
  3305. Text(this.currentSong?.album ? this.currentSong.album : '未知专辑')
  3306. .fontSize(14)
  3307. .margin({ left: 10 })
  3308. .fontColor(Color.White)
  3309. .layoutWeight(1)
  3310. }
  3311. .width('100%')
  3312. .margin({ top: 10, bottom: 10 })
  3313. .justifyContent(FlexAlign.Start)
  3314. Row() {
  3315. Text('文件大小:')
  3316. .fontSize(14)
  3317. .fontColor(Color.White)
  3318. .margin({ left: 22 })
  3319. Text(this.currentSong.size)
  3320. .fontSize(14)
  3321. .margin({ left: 10 })
  3322. .fontColor(Color.White)
  3323. .layoutWeight(1)
  3324. }
  3325. .width('100%')
  3326. .margin({ top: 10, bottom: 10 })
  3327. .justifyContent(FlexAlign.Start)
  3328. Row() {
  3329. Text('文件名:')
  3330. .fontSize(14)
  3331. .fontColor(Color.White)
  3332. .margin({ left: 22 })
  3333. Text(this.currentSong.fileName)
  3334. .fontSize(14)
  3335. .margin({ left: 10 })
  3336. .fontColor(Color.White)
  3337. .layoutWeight(1)
  3338. }
  3339. .width('100%')
  3340. .margin({ top: 10, bottom: 10 })
  3341. .justifyContent(FlexAlign.Start)
  3342. Row() {
  3343. Text('修改时间:')
  3344. .fontSize(14)
  3345. .fontColor(Color.White)
  3346. .margin({ left: 22 })
  3347. Text(this.currentSong.cTime)
  3348. .fontSize(14)
  3349. .margin({ left: 10 })
  3350. .fontColor(Color.White)
  3351. .layoutWeight(1)
  3352. }
  3353. .width('100%')
  3354. .margin({ top: 10, bottom: 10 })
  3355. .justifyContent(FlexAlign.Start)
  3356. Row() {
  3357. Text('存放目录:')
  3358. .fontSize(14)
  3359. .fontColor(Color.White)
  3360. .margin({ left: 22 })
  3361. Text(this.currentSong.filePath)
  3362. .fontSize(12)
  3363. .margin({ left: 10 })
  3364. .fontColor(Color.White)
  3365. .layoutWeight(1)
  3366. }
  3367. .margin({ top: 10, bottom: 10 })
  3368. .width('100%')
  3369. .justifyContent(FlexAlign.Start)
  3370. }
  3371. }
  3372. .margin({ bottom: 20 })
  3373. }
  3374. //定时关闭布局
  3375. @Builder
  3376. TimeCloseSheet() {
  3377. Scroll() {
  3378. Column() {
  3379. this.TimeClose()
  3380. }
  3381. }
  3382. .width('100%')
  3383. .height('100%')
  3384. }
  3385. //倒计时关闭音乐,退出App功能实现。
  3386. @State selectedMinutes: number = 0 // 0表示未开启
  3387. @State remainingSeconds: number = 0
  3388. @State isCustomSuccess: boolean = false //设置自定义成功
  3389. // 预设时间选项
  3390. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  3391. private formatTime(seconds: number): string {
  3392. const mins = Math.floor(seconds / 60)
  3393. const secs = seconds % 60
  3394. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  3395. }
  3396. // 开始倒计时
  3397. private handleTimeSelect(minutes: number) {
  3398. if (minutes === this.selectedMinutes) {
  3399. this.stopCountdown();
  3400. this.selectedMinutes = 0;
  3401. return;
  3402. }
  3403. this.selectedMinutes = minutes;
  3404. this.remainingSeconds = minutes * 60;
  3405. this.startCountdown(); // 新增调用
  3406. }
  3407. @Builder
  3408. TimeClose() {
  3409. Column() {
  3410. // 倒计时显示区域
  3411. Text(this.selectedMinutes > 0 ?
  3412. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  3413. "定时关闭未开启")
  3414. .fontSize(17)
  3415. .fontColor($r('app.color.text_color'))
  3416. .margin({ top: 2 });
  3417. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  3418. ForEach(this.presetTimes, (minutes: number) => {
  3419. // 单行时间选项容器
  3420. Row() {
  3421. // 文字描述区域
  3422. Text(this.getDisplayText(minutes))
  3423. .fontSize(15)
  3424. .fontColor(minutes === this.selectedMinutes ? $r('app.color.title_bar_bg') :
  3425. $r('app.color.text_color'))// 选中态颜色变化
  3426. .textAlign(TextAlign.Start)
  3427. .layoutWeight(1); // 占据剩余空间
  3428. // 复选框区域
  3429. Checkbox()
  3430. .select(minutes === this.selectedMinutes ? true : minutes === -1 ? this.isCustomSuccess : false)// 绑定选中状态
  3431. .selectedColor($r('app.color.title_bar_bg'))// 主题色
  3432. .shape(CheckBoxShape.CIRCLE)
  3433. .size({ width: 24, height: 24 })
  3434. .margin({ left: 20 })
  3435. }
  3436. .width('100%')
  3437. .padding(10)
  3438. .backgroundColor(minutes === this.selectedMinutes ?$r('app.color.timeColor_bg') :$r('app.color.bottom_control_background')) // 选中背景高亮
  3439. .borderRadius(12)
  3440. .margin({ bottom: 6 })
  3441. .onClick(() => this.handleSelect(minutes)); // 确保点击触发选择
  3442. });
  3443. }
  3444. .width('100%')
  3445. .padding(16)
  3446. }
  3447. // .width('100%')
  3448. // .height('100%')
  3449. }
  3450. // 获取显示文本
  3451. private getDisplayText(minutes: number): string {
  3452. if (minutes === -1) {
  3453. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  3454. }
  3455. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  3456. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  3457. }
  3458. // 处理选择事件
  3459. private handleSelect(minutes: number): void {
  3460. if (minutes === -1) { // 自定义
  3461. // 弹出自定义时间对话框
  3462. DialogHelper.showTextInputDialog({
  3463. title: '自定义时间',
  3464. maskColor: Color.Transparent,
  3465. inputType: InputType.Number,
  3466. text: '',
  3467. onChange: (text) => {
  3468. console.error("onChange: " + text);
  3469. },
  3470. onAction: (action, dialogId, content) => {
  3471. if (action == DialogAction.TWO) {
  3472. this.handleTimeSelect(Number(content)); // 改为调用统一方法
  3473. this.isCustomSuccess = true
  3474. ToastUtil.showToast("设置成功," + this.selectedMinutes + "分钟后定时关闭");
  3475. }
  3476. }
  3477. });
  3478. } else {
  3479. this.isCustomSuccess = false
  3480. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  3481. }
  3482. }
  3483. // 添加定时器引用
  3484. private timerId: number = -1;
  3485. // 启动/重置倒计时
  3486. private startCountdown() {
  3487. // 清除旧定时器
  3488. if (this.timerId !== -1) {
  3489. clearInterval(this.timerId);
  3490. }
  3491. // 创建新定时器
  3492. if (this.selectedMinutes > 0) {
  3493. this.timerId = setInterval(() => {
  3494. if (this.remainingSeconds === 15) {
  3495. this.showConfirmationDialog();
  3496. }
  3497. if (this.remainingSeconds > 0) {
  3498. this.remainingSeconds -= 1;
  3499. } else {
  3500. this.stopCountdown();
  3501. this.handleTimeout();
  3502. }
  3503. }, 1000);
  3504. }
  3505. }
  3506. // 15倒计时后再次提示显示确认是否关闭App对话框
  3507. private showConfirmationDialog() {
  3508. DialogHelper.showAlertDialog({
  3509. backgroundColor: $r('app.color.btn_green'),
  3510. title: '确认关闭',
  3511. maskColor: Color.Transparent,
  3512. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  3513. borderStyle: BorderStyle.Dashed,
  3514. primaryButton: '暂不关闭',
  3515. secondaryButton: '确定',
  3516. onAction: (action) => {
  3517. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  3518. this.stopCountdown();
  3519. this.selectedMinutes = 0
  3520. } else if (action == DialogAction.TWO) {
  3521. }
  3522. }
  3523. })
  3524. }
  3525. // 停止倒计时
  3526. private stopCountdown() {
  3527. if (this.timerId !== -1) {
  3528. clearInterval(this.timerId);
  3529. this.timerId = -1;
  3530. }
  3531. }
  3532. // 超时处理
  3533. private handleTimeout() {
  3534. // 执行播放器关闭逻辑
  3535. this.selectedMinutes = 0;
  3536. this.isCustomSuccess = false;
  3537. ToastUtil.showToast(" 定时关闭已完成");
  3538. this.stop(); // 假设存在的播放器实例
  3539. //退出APP
  3540. const mContext = getContext(this) as common.UIAbilityContext
  3541. mContext.terminateSelf();
  3542. AvSessionController.getInstance(true).unregisterSessionListener()
  3543. }
  3544. //倒计时关闭音乐,退出App功能实现结束。
  3545. //播放列表的拖动List 重新排序
  3546. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  3547. //左滑操作 移动文件 重命名 删除等操作
  3548. @Builder
  3549. sonButton(item: VideoItem, index: number, filePath: string) {
  3550. Row() {
  3551. //加入下一首播放
  3552. Button() {
  3553. Image($r('app.media.next_to_play'))
  3554. .fillColor(Color.White)
  3555. .width(20)
  3556. }
  3557. .width(40)
  3558. .height(40)
  3559. .type(ButtonType.Circle)
  3560. .backgroundColor($r('app.color.title_bar_bg'))
  3561. .margin(5)
  3562. .onClick(() => {
  3563. this.addToNextPlay(item);
  3564. })
  3565. Button() {
  3566. Image($r('app.media.ic_close'))
  3567. .fillColor(Color.White)
  3568. .width(13)
  3569. }
  3570. .width(40)
  3571. .height(40)
  3572. .type(ButtonType.Circle)
  3573. .backgroundColor($r('app.color.title_bar_bg'))
  3574. .margin(5)
  3575. .onClick(() => {
  3576. this.songList.splice(Number(index), 1)
  3577. this.sonDataSource.pushArrayData(this.songList)
  3578. })
  3579. Button() {
  3580. Image($r('app.media.share2'))
  3581. .fillColor(Color.White)
  3582. .width(20)
  3583. }
  3584. .width(40)
  3585. .height(40)
  3586. .type(ButtonType.Circle)
  3587. .backgroundColor($r('app.color.title_bar_bg'))
  3588. .margin(5)
  3589. .onClick(() => {
  3590. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  3591. })
  3592. }
  3593. }
  3594. itemMoveSon(index: number, newIndex: number): void {
  3595. if (newIndex < 0 || newIndex >= this.songList.length) {
  3596. return;
  3597. }
  3598. let tmp = this.songList.splice(index, 1);
  3599. this.songList.splice(newIndex, 0, tmp[0]);
  3600. this.sonDataSource.pushArrayData(this.songList)
  3601. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  3602. }
  3603. @Builder
  3604. PlayList() {
  3605. List() {
  3606. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  3607. ListItem() {
  3608. this.MusicItemSon(item, index)
  3609. }
  3610. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  3611. .animation({
  3612. duration: 666,
  3613. curve: 'ease-in-out' // 可选动画曲线
  3614. })
  3615. //拖动List关键代码开始
  3616. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  3617. .zIndex(this.dragItem === index ? 1 : 0)
  3618. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  3619. .gesture(
  3620. GestureGroup(GestureMode.Sequence,
  3621. LongPressGesture({ repeat: true })
  3622. .onAction((event?: GestureEvent) => {
  3623. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3624. this.scaleItem = index
  3625. })
  3626. })
  3627. .onActionEnd(() => {
  3628. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  3629. this.scaleItem = -1
  3630. })
  3631. }),
  3632. PanGesture({ fingers: 1, direction: null, distance: 0 })
  3633. .onActionStart(() => {
  3634. this.dragItem = index // 记录当前拖动项索引
  3635. this.dragRefOffset = 0 // 重置偏移基准
  3636. })
  3637. .onActionUpdate((event: GestureEvent) => {
  3638. this.offsetY = event.offsetY - this.dragRefOffset;
  3639. this.neighborItem = -1;
  3640. let indexA = this.songList.indexOf(item);
  3641. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  3642. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  3643. let value: number = 0;
  3644. if (this.offsetY < 0) {
  3645. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  3646. this.neighborItem = indexA - 1;
  3647. this.neighborScale = 1 - value / 20;
  3648. } else if (this.offsetY > 0) {
  3649. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  3650. this.neighborItem = indexA + 1;
  3651. this.neighborScale = 1 - value / 20;
  3652. }
  3653. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  3654. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3655. this.offsetY -= this.ITEM_INTV;
  3656. this.dragRefOffset += this.ITEM_INTV;
  3657. this.itemMoveSon(indexA, indexA + 1);
  3658. });
  3659. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  3660. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3661. this.offsetY += this.ITEM_INTV;
  3662. this.dragRefOffset -= this.ITEM_INTV;
  3663. this.itemMoveSon(indexA, indexA - 1);
  3664. });
  3665. }
  3666. })
  3667. .onActionEnd((event: GestureEvent) => {
  3668. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3669. this.dragItem = -1
  3670. this.neighborItem = -1
  3671. })
  3672. animateTo({
  3673. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  3674. }, () => {
  3675. this.scaleItem = -1
  3676. })
  3677. })
  3678. )
  3679. .onCancel(() => {
  3680. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  3681. this.dragItem = -1
  3682. this.neighborItem = -1
  3683. })
  3684. animateTo({
  3685. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  3686. }, () => {
  3687. this.scaleItem = -1
  3688. })
  3689. })
  3690. ) //拖动List关键代码结束
  3691. .onClick(() => {
  3692. this.doPlay(item, index, true)
  3693. })
  3694. }, (item: VideoItem) => item.filePath)
  3695. }
  3696. .width('100%')
  3697. .height('100%')
  3698. .cachedCount(10)
  3699. .padding({
  3700. bottom: 0
  3701. })
  3702. }
  3703. @Builder
  3704. private MusicItemSon(item: VideoItem, index?: number) {
  3705. Row() {
  3706. Stack() {
  3707. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  3708. .height(33)
  3709. .width(33)
  3710. .alt($r('app.media.music_red'))
  3711. .borderRadius('100%')
  3712. .clip(true)
  3713. .margin({ left: 20 })
  3714. }
  3715. .width('15%')
  3716. Column() {
  3717. Column() {
  3718. Text(item.name)
  3719. .fontSize(14)
  3720. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  3721. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  3722. .maxLines(1)
  3723. .margin({ left: 10 })
  3724. Row() {
  3725. Text(StrUtil.isEmpty(item.artist) ? item.cTime : item.artist + ' ' + item?.album)
  3726. .fontSize(11)
  3727. .padding({ top: 8 })
  3728. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  3729. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  3730. .margin({ left: 10 })
  3731. Blank()
  3732. Text(item.size)
  3733. .fontSize(11)
  3734. .padding({ top: 8 })
  3735. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  3736. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  3737. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  3738. .margin({ left: 10 })
  3739. }
  3740. }
  3741. .height('100%')
  3742. .width('100%')
  3743. .justifyContent(FlexAlign.Center)
  3744. .alignItems(HorizontalAlign.Start)
  3745. }
  3746. .height('100%')
  3747. .width('65%')
  3748. Column() {
  3749. ImageAnimator()
  3750. .images(this.imagesF)// 动画数组
  3751. .duration(1000)// 持续
  3752. .state(this.animationState)// 动画状态
  3753. .fillMode(FillMode.Forwards)
  3754. .width(18)
  3755. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  3756. Visibility.None)
  3757. .height(18)
  3758. .iterations(-1) // 播放次数
  3759. }
  3760. .width('20%')
  3761. }
  3762. .width('100%')
  3763. .height(58)
  3764. .justifyContent(FlexAlign.SpaceBetween)
  3765. .shadow(this.scaleItem === index ? {
  3766. radius: 70,
  3767. color: '#15000000',
  3768. offsetX: 0,
  3769. offsetY: 0
  3770. } :
  3771. {
  3772. radius: 0,
  3773. color: '#15000000',
  3774. offsetX: 0,
  3775. offsetY: 0
  3776. })
  3777. .animation({ curve: Curve.Sharp, duration: 300 })
  3778. }
  3779. @Builder
  3780. MusicPlayBuilder() {
  3781. Column() {
  3782. this.IjkMusicPlayerView()
  3783. }
  3784. .height('100%')
  3785. .width('100%')
  3786. .onDisAppear(() => {
  3787. this.translateY = 0;
  3788. })
  3789. .translate({ y: this.translateY })
  3790. .gesture(
  3791. PanGesture(this.panOption)
  3792. .onActionUpdate((event?: GestureEvent) => {
  3793. if (event) {
  3794. this.translateY = event.offsetY;
  3795. if (this.translateY < 0) {
  3796. this.translateY = 0;
  3797. return;
  3798. }
  3799. }
  3800. })
  3801. .onActionEnd(() => {
  3802. if (this.translateY > this.windowHeight / 2) {
  3803. this.isShowPlay = false;
  3804. } else {
  3805. this.getUIContext().animateTo({
  3806. duration: 300,
  3807. curve: Curve.Smooth
  3808. }, () => {
  3809. this.translateY = 0;
  3810. })
  3811. }
  3812. })
  3813. )
  3814. }
  3815. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  3816. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  3817. HeightBreakpoint.HEIGHT_LG;
  3818. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  3819. @State topBarHeight: number = 50
  3820. @State barOpacity: number = 1
  3821. private hideDone: boolean = false;
  3822. @State currentYOffset: number = 0;
  3823. @State bottomBarHeight: number = 55;
  3824. private isHiding: boolean = false;
  3825. //是否是Pura X外屏,或者小屏幕
  3826. isPuraWP() {
  3827. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  3828. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  3829. }
  3830. //是否是Pura X外屏,或者小屏幕,手机横屏
  3831. isCoverOpacity() {
  3832. if (this.isPuraWP()) {
  3833. return true
  3834. }
  3835. if (this.isPhoneLan()) {
  3836. return true
  3837. }
  3838. if (deviceInfo.marketName.includes('Pura X')
  3839. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  3840. return true
  3841. }
  3842. return false
  3843. }
  3844. //是不是手机横屏
  3845. isPhoneLan() {
  3846. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  3847. && this.currentBreakpoint !== BreakpointTypeEnum.SM) {
  3848. if (DisplayUtil.getFoldStatus() === 0 || DisplayUtil.getFoldStatus() === 2) {
  3849. return true
  3850. }
  3851. }
  3852. return false
  3853. }
  3854. @Builder
  3855. IjkMusicPlayerView() {
  3856. Column() {
  3857. // Stack({ alignContent: Alignment.Center }) {
  3858. //
  3859. //
  3860. //
  3861. // Image($r('app.media.icon_load'))
  3862. // .objectFit(ImageFit.Auto)
  3863. // .width('120px')
  3864. // .height('120px')
  3865. // .visibility(this.loadingVisible)
  3866. // .border({ width: 0 })
  3867. // .borderStyle(BorderStyle.Dashed)
  3868. //
  3869. //
  3870. // }
  3871. Column() {
  3872. Column() {
  3873. //播放标题
  3874. Column() {
  3875. this.PlayTitle()
  3876. }
  3877. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  3878. .width('100%')
  3879. .margin({ top: 0 })
  3880. .height(PlayConstants.HEIGHT)
  3881. .visibility(DeviceUtil.getDeviceType()==resourceManager.DeviceType.DEVICE_TYPE_2IN1?
  3882. Visibility.Visible:Visibility.None)
  3883. // .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM
  3884. // ?Visibility.Visible:Visibility.Visible)
  3885. Swiper() {
  3886. this.CoverInfo()
  3887. this.PlayerLyrics()
  3888. }
  3889. .indicator(false)
  3890. // .indicator(this.currentBreakpoint === BreakpointTypeEnum.SM ?
  3891. // new DotIndicator()
  3892. // .top(this.isCoverOpacity()?0:10)
  3893. //
  3894. // .selectedColor($r('app.color.select_swiper'))
  3895. // .color($r('app.color.slider_track')):false
  3896. // )
  3897. .displayCount(new BreakpointType({
  3898. sm: 1,
  3899. md: 2,
  3900. lg: 2,
  3901. xl: 2,
  3902. xxl: 2
  3903. }).getValue(this.currentBreakpoint))
  3904. .clip(false)
  3905. .loop(false)
  3906. .autoPlay(false)
  3907. // .interval(8000)
  3908. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  3909. .height('100%')
  3910. .hitTestBehavior(HitTestMode.Transparent)
  3911. Image($r('app.media.icon_replay'))
  3912. .objectFit(ImageFit.Auto)
  3913. .width('120px')
  3914. .height('120px')
  3915. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  3916. .border({ width: 0 })
  3917. .visibility(Visibility.None)
  3918. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  3919. .onClick(() => {
  3920. this.startPlayOrResumePlay();
  3921. })
  3922. }
  3923. .width(CommonConstants.FULL_PERCENT)
  3924. .height(CommonConstants.FULL_PERCENT)
  3925. .justifyContent(FlexAlign.End)
  3926. }
  3927. .justifyContent(FlexAlign.End)
  3928. .margin({ bottom: 8 })
  3929. }
  3930. // .backgroundImage(this.imageLabelBg)
  3931. .backgroundImage(this.isPuraWP()?(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover):this.imageLabelBg)
  3932. .backgroundImageSize(this.isPuraWP()?{ width: '100%' }:{ height: '150%', width: '100%' })
  3933. // .backgroundImagePosition(Alignment.Center)
  3934. // .backgroundColor(this.imageColor)
  3935. .backgroundBlurStyle(this.isPuraWP()?BlurStyle.NONE:BlurStyle.BACKGROUND_ULTRA_THICK)
  3936. .hitTestBehavior(HitTestMode.Transparent)
  3937. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  3938. }
  3939. @State progressValue: number = 0;
  3940. @State currentTime: string = "00:00";
  3941. @State totalTime: string = "00:00";
  3942. @State loadingVisible: Visibility = Visibility.None;
  3943. @State replayVisible: Visibility = Visibility.None;
  3944. @State slideEnable: boolean = false;
  3945. @State aspRatio: number = 0.5;
  3946. @State mContext: object | undefined = undefined;
  3947. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  3948. @State mFirst: boolean = true;
  3949. @State mDestroyPage: boolean = false;
  3950. @State playSpeed: number = 1;
  3951. @State oldSeconds: number = 0;
  3952. @State isSeekTo: boolean = false;
  3953. @State isCurrentTime: boolean = false;
  3954. @State videoWidth: string = '100%';
  3955. @State videoHeight: string = '100%';
  3956. @State initAspectRatio: number = 1;
  3957. @State videoAspectRatio: number = this.initAspectRatio;
  3958. private videoUrl: string = '';
  3959. private last: number = 0;
  3960. @State videoParentAspectRatio: number = this.initAspectRatio;
  3961. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  3962. @State CONTROL_PlayStatus: number = PlayStatus.INIT;
  3963. @State PROGRESS_MAX_VALUE: number = 100;
  3964. @State updateProgressTimer: number = 0;
  3965. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  3966. @State name: string = '';
  3967. // @State loop: boolean = false;
  3968. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  3969. @State isLandscape: boolean = false;
  3970. @State multiple: string = '1.0X';
  3971. xcomponentController: XComponentController = new XComponentController()
  3972. private panOptionBright: PanGestureOptions =
  3973. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  3974. private panOptionVolume: PanGestureOptions =
  3975. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  3976. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  3977. //手势的音量控制和亮度控制
  3978. private positionX: number = PlayConstants.POSITION_X;
  3979. private positionY: number = PlayConstants.POSITION_Y;
  3980. private windowClass: window.Window = globalThis.windowClass
  3981. @State volume: number = 0.5;
  3982. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  3983. @State bright: number = PlayConstants.BRIGHT;
  3984. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  3985. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  3986. @State screenWidth: number = 0
  3987. @State screenHeight: number = 0
  3988. @State statusBarHeight: number = 0
  3989. @State isYesFull: boolean = false
  3990. private seekValue: number = 0
  3991. @State isVideoLock: boolean = false; // Whether the video playback is locked
  3992. eventHub = getContext().eventHub;
  3993. //投播组件
  3994. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  3995. private castController: avSession.AVCastController | undefined = undefined;
  3996. @State isCastPlaying: boolean = false;
  3997. @State currentTime2: number = 0;
  3998. @State currentStringTime: string = '00:00';
  3999. @State duration: number = 0;
  4000. @State isReady: boolean = false;
  4001. @State durationTime: number = 0;
  4002. @State durationStringTime: string = '00:00';
  4003. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  4004. // @State isPlaying: boolean = false;
  4005. private castSeek: boolean = false;
  4006. private castItem: avSession.AVQueueItem | undefined = undefined;
  4007. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  4008. @State imageLabel: PixelMap | Resource = CommonConstants.musicBgList[0];
  4009. @State imageLabelBg: PixelMap | Resource = CommonConstants.musicBgList[0];
  4010. @State rotateAngle2: number = 0
  4011. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  4012. @State cover: string | undefined = '';
  4013. @State artist: string | undefined = ''
  4014. // 1.初始化controller
  4015. private lyricController: LyricController = new LyricController()
  4016. private parser = new LyricParser()
  4017. @State randomColor: string = 'rgb(0,0,0)'
  4018. @State randomShakenX: number = 0
  4019. @State randomShakenY: number = 0
  4020. @State lyricTextSize: number = 24
  4021. @State lyricContent: string = ''
  4022. @State isDebug: boolean = DEBUG
  4023. /**
  4024. * 初始化歌词加载与展示逻辑
  4025. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  4026. * @param isToast 是否弹出Toast提示(可选)获取在线歌词为true
  4027. * @param isApi2 是否使用API2获取歌词(可选)
  4028. *
  4029. * 主要流程:
  4030. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  4031. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  4032. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  4033. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  4034. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  4035. * 6. 解析失败或读取失败时,清空歌词显示。
  4036. *
  4037. * 注意事项:
  4038. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  4039. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  4040. * - 歌词内容解析后通过lyricController驱动UI渲染。
  4041. */
  4042. async initLyric(lyricPath: string, isToast?: boolean, isApi2?: boolean) {
  4043. if (StrUtil.isEmpty(lyricPath)) {
  4044. return
  4045. }
  4046. this.lyricContent = ''
  4047. this.lyricController
  4048. .setTextSize(this.currentLyricSize)
  4049. .setCacheSize(4)
  4050. .setTextColor("#DDDDDD")
  4051. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  4052. .setEmptyHint("")
  4053. .setAnimationDuration(1000)
  4054. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  4055. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 2)
  4056. this.setBlurDegree(this.blurDegree)
  4057. this.setLyricAlignMode(this.currentLyricAlignMode)
  4058. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18))
  4059. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23))
  4060. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 52))
  4061. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'))
  4062. this.showSingleLyric = false
  4063. this.timeOffset = 0
  4064. this.lyricController.setLyric(null)
  4065. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  4066. LogUtil.debug("onecold lyricPath =" + lyricPath)
  4067. const neiqianLrc = LrcParser.getLyrics(this.videoUrl); //获取内嵌歌词
  4068. if (StrUtil.isNotEmpty(neiqianLrc) && !isToast) {
  4069. LogUtil.debug("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  4070. //赋值给this.lyricContent,播控中心才可以显示歌词
  4071. this.lyricContent = neiqianLrc
  4072. // 将文件内容按行分割成字符串数组
  4073. let lines = neiqianLrc.split('\n').map(line => line.trim());
  4074. // 3.解析歌词
  4075. let lyric = this.parser.parse(lines);
  4076. // 4.设置歌词
  4077. this.lyricController.setLyric(lyric);
  4078. return
  4079. }
  4080. if (isToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  4081. && !Utility.isVideoByExtension(this.videoUrl))) {
  4082. if (this.currentSong !== undefined) {
  4083. // ToastUtil.showShort('正在为你搜索在线歌词!')
  4084. //判断是不是赞助会员,是会员的话才开启歌词功能
  4085. // if (!this.isDebug) {
  4086. // if (!Utility.isNoble()) {
  4087. // LogUtil.debug("onecold 不是赞助会员")
  4088. // return
  4089. // }
  4090. // if(!Utility.isPassInstallTime(33)){
  4091. // LogUtil.debug("onecold not pass time")
  4092. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  4093. // return
  4094. // }
  4095. // }
  4096. let artist = this.currentSong?.artist
  4097. if (artist === undefined) {
  4098. artist = ''
  4099. }
  4100. if (isApi2 === undefined) {
  4101. isApi2 = false
  4102. }
  4103. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  4104. // LogUtil.debug("onecold res =" + res)
  4105. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  4106. if (StrUtil.isNotEmpty(res)) {
  4107. this.lyricContent = res
  4108. let lines = res.split('\n').map(line => line.trim());
  4109. // 3.解析歌词
  4110. let lyric = this.parser.parse(lines);
  4111. // 4.设置歌词
  4112. this.lyricController.setLyric(lyric);
  4113. this.showSingleLyric = true
  4114. // 4.保存歌词文件lyric到本地
  4115. this.saveDataToFile(res, jiaMilyricPath, true)
  4116. } else {
  4117. this.lyricController.setLyric(null)
  4118. if (isToast) {
  4119. ToastUtil.showShort('未获取到歌词!')
  4120. }
  4121. }
  4122. } else {
  4123. this.lyricController.setLyric(null)
  4124. if (isToast) {
  4125. ToastUtil.showShort('未获取到歌词!')
  4126. }
  4127. }
  4128. })
  4129. } else {
  4130. this.lyricController.setLyric(null)
  4131. if (isToast) {
  4132. ToastUtil.showShort('未获取到歌词!')
  4133. }
  4134. }
  4135. return
  4136. }
  4137. try {
  4138. let isJiaMi = false;
  4139. let realLyricPath = lyricPath
  4140. if (FileUtil.accessSync(jiaMilyricPath)) {
  4141. isJiaMi = true
  4142. realLyricPath = jiaMilyricPath
  4143. console.info("onecold 找到加密本地歌词 ");
  4144. } else {
  4145. isJiaMi = false
  4146. realLyricPath = lyricPath
  4147. console.info("onecold 找到本地歌词 ");
  4148. }
  4149. // 3.读取文件内容并指定编码为 UTF-8
  4150. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_WRITE);
  4151. let arrayBuffer = new ArrayBuffer(4096);
  4152. fs.read(file.fd, arrayBuffer)
  4153. .then((readLen: number) => {
  4154. console.info("read file data succeed");
  4155. // let buf = buffer.from(arrayBuffer, 0, readLen);
  4156. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  4157. // 检查 buf 是否为空
  4158. if (buf.length === 0) {
  4159. throw new Error("Buffer is empty after reading the file");
  4160. }
  4161. try {
  4162. // 检测文件编码
  4163. let detectedEncoding = chardet.detect(buf);
  4164. console.info("Detected encoding: " + detectedEncoding);
  4165. // 使用检测到的编码解码,解决中文乱码问题
  4166. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  4167. let fileContent = textDecoder.decode(buf);
  4168. console.info(`onecold The content of file1: ${fileContent}`);
  4169. //解密
  4170. if (isJiaMi) {
  4171. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  4172. }
  4173. console.info(`onecold The content of file2: ${fileContent}`);
  4174. this.lyricContent = fileContent
  4175. // 将文件内容按行分割成字符串数组
  4176. let lines = fileContent.split('\n').map(line => line.trim());
  4177. console.info(`onecold The content of file: ${fileContent}`);
  4178. // 3.解析歌词
  4179. let lyric = this.parser.parse(lines);
  4180. // 4.设置歌词
  4181. this.lyricController.setLyric(lyric);
  4182. this.showSingleLyric = true
  4183. console.info(`The content of file: ${fileContent}`);
  4184. } catch (chardetError) {
  4185. console.error("chardet.detect failed with error: " + chardetError.message);
  4186. this.lyricController.setLyric(null);
  4187. }
  4188. })
  4189. .catch((err: BusinessError) => {
  4190. this.lyricController.setLyric(null)
  4191. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  4192. })
  4193. .catch((err: Error) => {
  4194. this.lyricController.setLyric(null)
  4195. console.error("read file 2 data failed with error message: " + err.message);
  4196. })
  4197. .finally(() => {
  4198. fs.closeSync(file);
  4199. });
  4200. } catch (error) {
  4201. this.lyricController.setLyric(null)
  4202. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  4203. }
  4204. }
  4205. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  4206. if (StrUtil.isEmpty(filePath)) {
  4207. return
  4208. }
  4209. try {
  4210. //将content进行加密
  4211. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  4212. let lyricContent = ''
  4213. if (isJiaMi) {
  4214. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  4215. } else {
  4216. lyricContent = content
  4217. }
  4218. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  4219. // 清空文件内容
  4220. await fileIo.truncate(file.fd, 0);
  4221. await fileIo.write(file.fd, lyricContent);
  4222. await fileIo.close(file);
  4223. console.log('onecold lyric file Data saved successfully.');
  4224. } catch (error) {
  4225. console.error('onecold lyric file Failed to save data:', error);
  4226. }
  4227. }
  4228. /**
  4229. * Get largest proportion color of an image.
  4230. */
  4231. getImageColor() {
  4232. if (!this.context) {
  4233. return;
  4234. }
  4235. let bg = Utility.getMusisBg()
  4236. this.imageLabel = bg
  4237. ColorConversion.setSysBarLightBackground(true);
  4238. this.context.resourceManager.getMediaContent(bg)
  4239. .then((value: Uint8Array) => {
  4240. let buffer = value.buffer as ArrayBuffer;
  4241. image.createImageSource(buffer).createPixelMap().then((pixelMap) => {
  4242. effectKit.createColorPicker(pixelMap, (error, colorPicker) => {
  4243. if (error) {
  4244. Logger.error('Failed to create color picker.');
  4245. } else {
  4246. let color = colorPicker.getLargestProportionColor();
  4247. let colorArr = ColorConversion.dealColor(color.red, color.green, color.blue);
  4248. this.imageColor = `rgba(${colorArr[0]}, ${colorArr[1]}, ${colorArr[2]}, 1)`;
  4249. }
  4250. })
  4251. let headFilter = effectKit.createEffect(pixelMap);
  4252. if (headFilter !== null) {
  4253. headFilter.blur(15);
  4254. headFilter.getEffectPixelMap().then((value) => {
  4255. this.imageLabelBg = value;
  4256. })
  4257. }
  4258. })
  4259. .catch((error: BusinessError) => {
  4260. Logger.error(`${error.code} + ${error.message}`)
  4261. })
  4262. })
  4263. .catch((error: BusinessError) => {
  4264. Logger.error(`${error.code} + ${error.message}`)
  4265. })
  4266. }
  4267. setImageColor(cover: string) {
  4268. if (!this.context) {
  4269. return;
  4270. }
  4271. if (cover === undefined) {
  4272. return;
  4273. }
  4274. ImageUtil.imagePathToPixelMap(cover).then((value) => {
  4275. let headFilter = effectKit.createEffect(value);
  4276. if (headFilter !== null) {
  4277. headFilter.blur(15);
  4278. headFilter.getEffectPixelMap().then((value) => {
  4279. this.imageLabelBg = value;
  4280. })
  4281. }
  4282. }).catch((error: BusinessError) => {
  4283. Logger.error(`${error.code} + ${error.message}`)
  4284. })
  4285. }
  4286. setImageColor2(cover: string) {
  4287. if (!this.context) {
  4288. return;
  4289. }
  4290. if (cover === undefined) {
  4291. return;
  4292. }
  4293. LogUtils.getInstance().LOGI("setImageColor2--> cover ==" + cover);
  4294. ImageUtils.getImageDealData(getContext(this), cover, this.videoUrl).then((data) => {
  4295. this.imageColor = data.imageColor;
  4296. if (data.blurPixelMap) {
  4297. this.imageLabelBg = data.blurPixelMap;
  4298. }
  4299. })
  4300. }
  4301. // 定义开始旋转的方法
  4302. // 定时器用于一百毫秒执行一次旋转角度
  4303. @State timer: number = 0
  4304. @State rotateAngle: number = 0
  4305. //封面旋转动画
  4306. animationRoFun() {
  4307. if (this.isPlaying && !this.isCoverRectangle) {
  4308. this.timer = setInterval(() => {
  4309. this.rotateAngle += 1
  4310. }, 100)
  4311. this.startRotation()
  4312. } else {
  4313. clearInterval(this.timer)
  4314. this.stopRotation()
  4315. }
  4316. }
  4317. // 定义开始旋转的方法
  4318. startRotation() {
  4319. if (this.isPlaying) {
  4320. animateTo({
  4321. duration: 777,
  4322. iterations: 1,
  4323. curve: Curve.Linear
  4324. }, () => {
  4325. this.rotateAngle2 = 0
  4326. })
  4327. }
  4328. }
  4329. // 回调,暂停和播放按钮回调,下一首和上一首
  4330. playChange() {
  4331. // if(this.isCoverRectangle){
  4332. // return
  4333. // }
  4334. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  4335. this.setIsPlaying(true)
  4336. this.animationState = AnimationStatus.Running
  4337. } else {
  4338. this.setIsPlaying(false)
  4339. this.animationState = AnimationStatus.Paused
  4340. }
  4341. }
  4342. // 定义停止旋转的方法
  4343. stopRotation() {
  4344. if (this.isCoverRectangle) {
  4345. this.rotateAngle = 0
  4346. } else {
  4347. //唱针以左上角为点选择逆时针40度
  4348. animateTo({
  4349. duration: 1000,
  4350. curve: Curve.Linear,
  4351. iterations: 1,
  4352. }, () => {
  4353. this.rotateAngle2 = -40;
  4354. });
  4355. }
  4356. }
  4357. @Builder
  4358. private LyricsTopItem() {
  4359. Row() {
  4360. Stack() {
  4361. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  4362. .height(39)
  4363. .width(39)
  4364. .alt(this.imageLabel)
  4365. .borderRadius(8)
  4366. .margin({ left: this.currentLyricAlignMode === 0 ? 25 : -15 })
  4367. }
  4368. .width('15%')
  4369. Column() {
  4370. Column() {
  4371. Text(this.name)
  4372. .fontSize(14)
  4373. .maxLines(1)
  4374. .fontWeight(FontWeight.Bolder)
  4375. .fontColor(this.currentLyricColor)
  4376. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  4377. Row() {
  4378. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  4379. .fontSize(10)
  4380. .fontWeight(FontWeight.Bold)
  4381. .padding({ top: 8 })
  4382. .fontColor(this.currentLyricColor)
  4383. .margin({ left: this.currentLyricAlignMode === 0 ? 18 : 0 })
  4384. Blank()
  4385. }
  4386. }
  4387. .height('100%')
  4388. .width('100%')
  4389. .justifyContent(FlexAlign.Center)
  4390. .alignItems(HorizontalAlign.Start)
  4391. }
  4392. .height('100%')
  4393. .width('65%')
  4394. Column() {
  4395. Image($r('app.media.lyric'))
  4396. .width(25)
  4397. .aspectRatio(CommonConstants.ASPECT_RATIO)
  4398. .margin({ right: 30 })
  4399. .onClick(() => {
  4400. this.isLyricSetting = !this.isLyricSetting;
  4401. })
  4402. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(), {
  4403. height: this.isCoverOpacity() ? '95%' : '78%',
  4404. dragBar: true,
  4405. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  4406. showClose: true,
  4407. blurStyle: BlurStyle.Thin,
  4408. backgroundColor: Color.Transparent,
  4409. // title: { title: $r('app.string.lyric_setting') }
  4410. })
  4411. }
  4412. .width('18%')
  4413. }
  4414. .width(this.isLandscape ? '50%' : '82%')
  4415. .height(58)
  4416. .justifyContent(FlexAlign.SpaceBetween)
  4417. }
  4418. //歌词显示
  4419. @Builder
  4420. PlayerLyrics() {
  4421. Column() {
  4422. Column() {
  4423. this.LyricsTopItem()
  4424. }
  4425. .height(this.isPuraWP() ? 15 : 58)
  4426. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  4427. Visibility.None : Visibility.Visible)
  4428. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  4429. .width("100%")
  4430. Column() {
  4431. LyricView2({
  4432. controller: this.lyricController,
  4433. enableSeek: true,
  4434. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  4435. seekLineColor: "#80ffffff", // 滑动定位线颜色
  4436. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  4437. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  4438. this.isSeekTo = true;
  4439. this.mDestroyPage = false;
  4440. this.showLoadIng();
  4441. // LogUtils.getInstance().LOGI("onecold-->seekValue start:" + position);
  4442. this.seekTo(position + "");
  4443. this.isSeekTo = false;
  4444. return true
  4445. }
  4446. })
  4447. .width("100%")
  4448. .layoutWeight(1)
  4449. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: 10 })
  4450. }
  4451. .position({
  4452. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  4453. (this.isPuraWP() ? 58 : 99)
  4454. })
  4455. .justifyContent(FlexAlign.Center)
  4456. .height(this.isCoverOpacity() ? '95%' : '80%')
  4457. }
  4458. }
  4459. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  4460. @Builder
  4461. BottomControl() {
  4462. Column() {
  4463. //播放 暂停,下一首,上一首
  4464. Row() {
  4465. Row({ space: 33 }) {
  4466. //更多功能
  4467. Image($r('app.media.menu'))
  4468. .width(24)
  4469. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  4470. height: this.isCoverOpacity() ? '95%' : '93%',
  4471. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  4472. dragBar: true,
  4473. showClose: true,
  4474. blurStyle: BlurStyle.Thin,
  4475. backgroundColor: Color.Transparent,
  4476. })
  4477. .onClick(() => {
  4478. this.isShowMoreView = !this.isShowMoreView;
  4479. })
  4480. Image($r('app.media.ic_previous'))
  4481. .width(33)
  4482. .aspectRatio(CommonConstants.ASPECT_RATIO)
  4483. .onClick(async () => {
  4484. this.playPrevious()
  4485. })
  4486. }
  4487. .margin({ left: 33 })
  4488. Column() {
  4489. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  4490. $r('app.media.ic_public_play') : $r('app.media.ic_public_pause'))
  4491. .width(60)
  4492. .aspectRatio(CommonConstants.ASPECT_RATIO)
  4493. .onClick(async () => {
  4494. this.playOrPause()
  4495. })
  4496. }
  4497. .layoutWeight(1)
  4498. .margin({ left: 20, right: 20 })
  4499. Row({ space: 33 }) {
  4500. Image($r('app.media.ic_next'))
  4501. .width(33)
  4502. .aspectRatio(CommonConstants.ASPECT_RATIO)
  4503. .onClick(() => {
  4504. this.playNext();
  4505. })
  4506. //添加或取消收藏
  4507. Image(Utility.getIsFav(this.favList,this.currentSong)?$r('app.media.add_fac_light'):$r('app.media.add_fac'))
  4508. .width(24)
  4509. .aspectRatio(CommonConstants.ASPECT_RATIO)
  4510. .onClick(async () => {
  4511. if(this.currentSong){
  4512. this.doFav(this.currentSong)
  4513. }
  4514. })
  4515. }
  4516. .margin({ right: 33 })
  4517. }
  4518. .width('100%')
  4519. .margin(10)
  4520. //播放进度条
  4521. Row() {
  4522. Column() {
  4523. if (this.playType === 0) {
  4524. Image($r('app.media.loop'))
  4525. .width($r('app.float.control_image_width'))
  4526. .margin(10)
  4527. .aspectRatio(CommonConstants.ASPECT_RATIO)
  4528. } else if (this.playType === 1) {
  4529. Image($r('app.media.single'))
  4530. .width($r('app.float.control_image_width'))
  4531. .margin(10)
  4532. .aspectRatio(CommonConstants.ASPECT_RATIO)
  4533. } else if (this.playType === 2) {
  4534. Image($r('app.media.normal_play'))
  4535. .width($r('app.float.control_image_width'))
  4536. .margin(10)
  4537. .aspectRatio(CommonConstants.ASPECT_RATIO)
  4538. } else if (this.playType === 3) {
  4539. Image($r('app.media.random'))
  4540. .width($r('app.float.control_image_width'))
  4541. .margin(10)
  4542. .aspectRatio(CommonConstants.ASPECT_RATIO)
  4543. }
  4544. }
  4545. .onClick(async () => {
  4546. this.setLoopMode()
  4547. })
  4548. Text(this.currentTime)
  4549. .fontSize($r('app.float.slider_font_size'))
  4550. .fontColor(Color.White)
  4551. .margin(3)
  4552. Slider({
  4553. value: this.progressValue,
  4554. min: 0,
  4555. max: this.PROGRESS_MAX_VALUE,
  4556. step: 1,
  4557. style: SliderStyle.OutSet
  4558. })
  4559. .width('600px')
  4560. .blockColor(Color.White)
  4561. .trackColor($r('app.color.track_color'))
  4562. .selectedColor(Color.White)
  4563. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  4564. .layoutWeight(1)
  4565. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  4566. .showSteps(true)
  4567. .showTips(true)
  4568. .enabled(this.slideEnable)
  4569. .onChange((value: number, mode: SliderChangeMode) => {
  4570. // if (mode == 2) {
  4571. this.isSeekTo = true;
  4572. this.mDestroyPage = false;
  4573. this.showLoadIng();
  4574. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  4575. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  4576. this.seekTo(seekValue + "");
  4577. // this.setProgress()
  4578. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  4579. this.isSeekTo = false;
  4580. // }
  4581. })
  4582. Text(this.totalTime)
  4583. .fontSize($r('app.float.slider_font_size'))
  4584. .fontColor(Color.White)
  4585. .margin(3)
  4586. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  4587. //播放列表
  4588. Image($r('app.media.playlist'))
  4589. .width($r('app.float.control_image_width'))
  4590. .margin({ right: 10, left: 20 })
  4591. .aspectRatio(CommonConstants.ASPECT_RATIO)
  4592. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  4593. height: '95%',
  4594. dragBar: true,
  4595. showClose: true,
  4596. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  4597. blurStyle: BlurStyle.Thin,
  4598. backgroundColor: Color.Transparent,
  4599. title: {
  4600. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  4601. + `(${this.songList.length}首)`
  4602. }
  4603. })
  4604. .onClick(() => {
  4605. this.isShowSheetView = !this.isShowSheetView;
  4606. this.isFrontWhite = true
  4607. })
  4608. }
  4609. .width(PlayConstants.PROGRESS_ROW_WIDTH)
  4610. // .visibility(this.isHide?Visibility.Hidden:Visibility.Visible)
  4611. }
  4612. .position({ bottom:this.isCoverOpacity()?55: 80 }) // 将 固定在底部
  4613. }
  4614. @State isCoverRectangle: boolean = false
  4615. @Builder
  4616. CoverInfo() {
  4617. Column() {
  4618. // 第一个
  4619. Column({ space: 8 }) {
  4620. Text(this.name)
  4621. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22)
  4622. .fontWeight(FontWeight.Bold)
  4623. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4624. .maxLines(1)
  4625. .fontColor(Color.White)
  4626. Text(this.artist + ' ' + this.currentSong?.album)
  4627. .fontSize(this.isCoverOpacity() ? 12 : 15)
  4628. .fontColor(Color.White)
  4629. }
  4630. .margin({ top: this.isCoverOpacity() ? 20 : 66 })
  4631. .justifyContent(FlexAlign.Center)
  4632. .zIndex(1)
  4633. .visibility(this.isCoverOpacity() ? Visibility.None : Visibility.Visible)
  4634. Stack() {
  4635. // 唱片旋转效果
  4636. Image($r('app.media.ic_music_disc'))
  4637. .width(250)
  4638. .height(250)
  4639. .margin({ right: 30, left: 30, top: this.isCoverOpacity() || this.isCoverRectangle ? 0 : 10 })
  4640. .aspectRatio(1)
  4641. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  4642. .borderRadius('100%')
  4643. .align(Alignment.Center)
  4644. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  4645. .rotate({
  4646. angle: this.rotateAngle,
  4647. centerX: "50%",
  4648. centerY: "50%",
  4649. })
  4650. .animation({
  4651. duration: 100,
  4652. curve: Curve.Linear
  4653. })
  4654. .shadow({
  4655. radius: 30,
  4656. color: this.randomColor
  4657. })
  4658. Image(StrUtil.isEmpty(this.cover) ? this.imageLabel : this.cover)
  4659. .height(this.isCoverOpacity() ? 152 : this.isCoverRectangle ? 300 : 162)
  4660. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  4661. .alt(this.imageLabel)
  4662. .margin({ right: 30, left: 30, top: this.isCoverOpacity() || this.isCoverRectangle ? 0 : 10 })
  4663. .aspectRatio(1)
  4664. .visibility(this.isPuraWP()?Visibility.None:Visibility.Visible)
  4665. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  4666. .align(Alignment.Center)// .opacity(this.isCoverOpacity()||this.isCoverRectangle?0:1)
  4667. .clip(true)
  4668. .rotate({
  4669. x: 0,
  4670. y: 0,
  4671. z: 1,
  4672. angle: this.rotateAngle
  4673. })
  4674. .onClick(() => {
  4675. this.getImageColor()
  4676. })
  4677. // 唱针以左上角为点选择逆时针40度
  4678. Image($r('app.media.ic_music_cover_hand'))
  4679. .height(130)
  4680. .margin({ bottom: 220, top: 0 })
  4681. .align(Alignment.Top)
  4682. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  4683. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  4684. Column({ space: 8 }) {
  4685. Text(this.name)
  4686. .fontSize(this.isPuraWP()?30:(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  4687. .fontWeight(FontWeight.Bold)
  4688. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4689. .maxLines(1)
  4690. .fontColor(Color.White)
  4691. Text(this.artist)
  4692. .fontSize(this.isPuraWP()?22:(this.isCoverOpacity() ? 12 : 15))
  4693. .fontColor(Color.White)
  4694. .fontWeight(FontWeight.Bold)
  4695. }
  4696. .justifyContent(FlexAlign.Start)
  4697. .zIndex(1)
  4698. // .margin({bottom:180})
  4699. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  4700. }
  4701. .margin({
  4702. bottom: this.isCoverOpacity() || this.isCoverRectangle ? 160 : 0,
  4703. top: this.isCoverOpacity() ? 0 : this.isCoverRectangle ? 40 : 30
  4704. })
  4705. this.BottomControl()
  4706. }
  4707. .width(CommonConstants.FULL_PERCENT)
  4708. .clip(true)
  4709. }
  4710. @Builder
  4711. private PlayTitle() {
  4712. Row() {
  4713. Row() {
  4714. Image($r('app.media.ic_back_down'))
  4715. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  4716. .hitTestBehavior(HitTestMode.Transparent)
  4717. // .visibility(this.isLandscape?Visibility.None:Visibility.Visible)
  4718. Text(this.name + ' ' + this.artist)
  4719. .fontColor(Color.White)
  4720. .fontSize($r('app.float.title_font_size'))
  4721. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4722. .maxLines(1)
  4723. .visibility(Visibility.None)
  4724. .margin({ left: 2, right: 30 })
  4725. }
  4726. .layoutWeight(1)
  4727. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  4728. .onClick(() => {
  4729. this.isShowPlay = false;
  4730. })
  4731. Column() {
  4732. AVCastPicker({
  4733. normalColor: Color.White,
  4734. onStateChange: this.onStateVastChange
  4735. })
  4736. .width(24)
  4737. .height(24)
  4738. }
  4739. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  4740. //更多功能
  4741. // Image( $r('app.media.two_point') )
  4742. // .width(24)
  4743. // .visibility(this.isHide?Visibility.None:Visibility.Visible)
  4744. // .margin({left:13})
  4745. // .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  4746. // height:this.isCoverOpacity()?'95%':'85%',
  4747. // dragBar: true,
  4748. // showClose: true,
  4749. // blurStyle:BlurStyle.Thin,
  4750. // backgroundColor:Color.Transparent,
  4751. // })
  4752. // .onClick(() => {
  4753. // this.isShowMoreView = !this.isShowMoreView;
  4754. // })
  4755. }
  4756. .width(PlayConstants.ROW_WIDTH)
  4757. }
  4758. @Builder
  4759. lyricSettingSheet() {
  4760. Scroll() {
  4761. this.lyricSetting()
  4762. }
  4763. .width('100%')
  4764. .height('100%')
  4765. }
  4766. @Builder
  4767. lyricSetting() {
  4768. Column() {
  4769. // 时间调节模块
  4770. this.BuildTimeControls()
  4771. // 字号控制模块
  4772. this.BuildFontControls()
  4773. }
  4774. }
  4775. // 歌词时间偏移状态
  4776. @State timeOffset: number = 0.0
  4777. @State currentLyricColor: string = '#FFFFFF'
  4778. // 歌词字号状态
  4779. @State currentLyricSize: number = 20
  4780. // 高亮歌词放大倍数
  4781. @State currentHightLyricSize: number = 1.2
  4782. @State currentLyricLineSpace: number = 52 //{
  4783. @State currentLyricAlignMode: number = 1
  4784. @State blurDegree: number = 2
  4785. // 构建字号控制器
  4786. @Builder
  4787. BuildFontControls() {
  4788. Column() {
  4789. Row() {
  4790. Text(`歌词居中:`)
  4791. .fontSize(14)
  4792. .fontColor(Color.White)
  4793. .margin({ right: 8 })
  4794. Row() {
  4795. ForEach(['居中', '居左'], (size: string, index: number) => {
  4796. Button(size)
  4797. .width(60)
  4798. .height(28)
  4799. .fontSize(12)
  4800. .fontColor(this.currentLyricAlignMode === index ? '#FFFFFF' : '#007DFF')
  4801. .backgroundColor(this.currentLyricAlignMode === index ? '#007DFF' : '#FFFFFF')
  4802. .border({
  4803. color: this.currentLyricAlignMode === index ? '#007DFF' : '#DDDDDD',
  4804. width: 1
  4805. })
  4806. .onClick(() => {
  4807. this.setLyricAlignMode(index)
  4808. })
  4809. .margin({ left: 8, right: 8 })
  4810. })
  4811. }
  4812. .layoutWeight(1)
  4813. Blank()
  4814. }
  4815. .justifyContent(FlexAlign.Start)
  4816. .margin({ top:10,bottom:10,right:20,left:35})
  4817. Row() {
  4818. Text(`歌词颜色:`)
  4819. .fontSize(14)
  4820. .fontColor(Color.White)
  4821. Row({space: 10}) {
  4822. HSBColorPicker({
  4823. color: '#FFFFFF',
  4824. radius: 8,
  4825. layout: HSBColorPickerLayout.COLUMN,
  4826. onChange:(value: string) =>this.changeLyricColor(value)
  4827. })
  4828. .height(88)
  4829. .layoutWeight(1)
  4830. .padding({left:15,right:35})
  4831. }
  4832. }
  4833. .width('76%')
  4834. .margin({ top:10,bottom:10,right:45,left:20})
  4835. Row() {
  4836. Text(`歌词字号:`)
  4837. .fontSize(14)
  4838. .fontColor(Color.White)
  4839. Slider({
  4840. value: this.currentLyricSize,
  4841. min: 12,
  4842. max: 30,
  4843. step: 0.1,
  4844. style: SliderStyle.OutSet
  4845. })
  4846. .blockColor(Color.Red)
  4847. .trackColor($r('app.color.speed_text_color'))
  4848. .selectedColor(Color.White)
  4849. .trackThickness(6)
  4850. .onChange((value: number) => {
  4851. ;
  4852. this.setLyricTextSize(value)
  4853. })
  4854. .width('76%')
  4855. }
  4856. .margin({
  4857. left: 20,
  4858. right: 15,
  4859. top: 5,
  4860. bottom: 5
  4861. })
  4862. Row() {
  4863. Text(`高亮倍数:`)
  4864. .fontSize(14)
  4865. .fontColor(Color.White)
  4866. Slider({
  4867. value: this.currentHightLyricSize,
  4868. min: 1,
  4869. max: 2,
  4870. step: 0.1,
  4871. style: SliderStyle.OutSet
  4872. })
  4873. .blockColor(Color.Red)
  4874. .trackColor($r('app.color.speed_text_color'))
  4875. .selectedColor(Color.White)
  4876. .trackThickness(6)
  4877. .onChange((value: number) => {
  4878. ;
  4879. this.setHighLyricTextSize(value)
  4880. })
  4881. .width('76%')
  4882. }
  4883. .margin({
  4884. left: 20,
  4885. right: 15,
  4886. top: 5,
  4887. bottom: 5
  4888. })
  4889. Row() {
  4890. Text(`歌词间隙:`)
  4891. .fontSize(14)
  4892. .fontColor(Color.White)
  4893. Slider({
  4894. value: this.currentLyricLineSpace,
  4895. min: 15,
  4896. max: 120,
  4897. step: 0.1,
  4898. style: SliderStyle.OutSet
  4899. })
  4900. .blockColor(Color.Red)
  4901. .trackColor($r('app.color.speed_text_color'))
  4902. .selectedColor(Color.White)
  4903. .trackThickness(6)
  4904. .onChange((value: number) => {
  4905. ;
  4906. this.setLyricLineSpace(value)
  4907. })
  4908. .width('76%')
  4909. }
  4910. .margin({
  4911. left: 20,
  4912. right: 15,
  4913. top: 5,
  4914. bottom: 5
  4915. })
  4916. Row() {
  4917. Text(`歌词模糊:`)
  4918. .fontSize(14)
  4919. .fontColor(Color.White)
  4920. Slider({
  4921. value: this.blurDegree,
  4922. min: 0,
  4923. max: 10,
  4924. step: 0.1,
  4925. style: SliderStyle.OutSet
  4926. })
  4927. .blockColor(Color.Red)
  4928. .trackColor($r('app.color.speed_text_color'))
  4929. .selectedColor(Color.White)
  4930. .trackThickness(6)
  4931. .onChange((value: number) => {
  4932. ;
  4933. this.setBlurDegree(value)
  4934. })
  4935. .width('76%')
  4936. }
  4937. .margin({
  4938. left: 20,
  4939. right: 15,
  4940. top: 5,
  4941. bottom: 15
  4942. })
  4943. Row() {
  4944. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  4945. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  4946. // this.pushLyricButton($r('app.media.white_search'), 2, '获取歌词')
  4947. }
  4948. .justifyContent(FlexAlign.Center)
  4949. .margin({ top: 3, bottom: 10 })
  4950. }
  4951. }
  4952. private setBlurDegree(index: number) {
  4953. this.blurDegree = index
  4954. this.lyricController.setBlurDegree(this.blurDegree)
  4955. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  4956. }
  4957. private setLyricAlignMode(index: number) {
  4958. this.currentLyricAlignMode = index
  4959. // LogUtil.info('onecold this.currentLyricSize = '+this.currentLyricAlignMode)
  4960. if (this.currentLyricAlignMode === 1) {
  4961. this.lyricController.setAlignMode("left")
  4962. } else {
  4963. this.lyricController.setAlignMode("center")
  4964. }
  4965. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  4966. }
  4967. private setLyricTextSize(index: number) {
  4968. this.currentLyricSize = index
  4969. this.lyricController.setTextSize(this.currentLyricSize)
  4970. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  4971. }
  4972. private setHighLyricTextSize(scale: number) {
  4973. this.currentHightLyricSize = scale
  4974. // LogUtil.info('onecold this.currentHightLyricSize = '+this.currentHightLyricSize)
  4975. this.lyricController
  4976. .setHighlightScale(this.currentHightLyricSize)
  4977. PreferencesUtil.putSync('HighLyricTextSize', scale)
  4978. }
  4979. private setLyricLineSpace(index: number) {
  4980. this.currentLyricLineSpace = index
  4981. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  4982. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  4983. }
  4984. private changeLyricColor(color: string) {
  4985. this.currentLyricColor = color
  4986. this.lyricController
  4987. .setTextColor(this.currentLyricColor)
  4988. .setHighlightColor(this.currentLyricColor)
  4989. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  4990. }
  4991. // 构建时间控制器
  4992. @Builder
  4993. BuildTimeControls() {
  4994. Column() {
  4995. // 时间显示
  4996. Text(this.getTimeText())
  4997. .fontSize(18)
  4998. .fontColor(Color.White)
  4999. .margin({ bottom: 10 })
  5000. Row() {
  5001. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  5002. this.PrecisionTimeButton($r('app.media.loop'), 0, 'RESET')
  5003. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  5004. }
  5005. .justifyContent(FlexAlign.Center)
  5006. }
  5007. .margin({ top: 12, bottom: 8 })
  5008. }
  5009. // 精度按钮组件
  5010. @Builder
  5011. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  5012. Column() {
  5013. Image(icon)
  5014. .width(28)
  5015. .margin({ bottom: 5 })
  5016. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  5017. Text(label)
  5018. .fontSize(12)
  5019. .fontColor('#FFFFFF')
  5020. }
  5021. .enabled(!this.isButtonDisabled(step))
  5022. .onClick(() => this.handlePrecisionAdjust(step))
  5023. .padding(5)
  5024. .width(60)
  5025. .height(60)
  5026. .margin({ left: 18, right: 18 })
  5027. .border({
  5028. color: '#FFFFFF',
  5029. radius: 20,
  5030. width: 1.8
  5031. })
  5032. }
  5033. private handlePrecisionAdjust(step: number) {
  5034. if (step === 0) {
  5035. this.timeOffset = 0
  5036. return
  5037. }
  5038. // 精度处理:保留1位小数
  5039. const newOffset = Number((this.timeOffset + step).toFixed(5))
  5040. // 边界保护(±15.0秒)
  5041. if (newOffset < -30.0 || newOffset > 30.0) {
  5042. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  5043. return
  5044. }
  5045. // 状态更新
  5046. this.timeOffset = newOffset
  5047. }
  5048. // 按钮禁用逻辑
  5049. private isButtonDisabled(step: number): boolean {
  5050. const futureOffset = this.timeOffset + step
  5051. return (futureOffset < -30.0) || (futureOffset > 30.0)
  5052. }
  5053. // 时间显示文本升级
  5054. private getTimeText(): string {
  5055. const absValue = Math.abs(this.timeOffset)
  5056. return this.timeOffset === 0
  5057. ? '歌词时间已重置'
  5058. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  5059. }
  5060. // 导入 本地歌词 搜索歌词
  5061. @Builder
  5062. pushLyricButton(icon: Resource, step: number, label: string) {
  5063. Row() {
  5064. Image(icon)
  5065. .width(14)
  5066. .margin({ left: 13 })
  5067. Text(label)
  5068. .fontSize(12)
  5069. .margin({ left: 6 })
  5070. .fontColor('#FFFFFF')
  5071. }
  5072. .visibility(step === 1 ? (Utility.isNoble() ? Visibility.Visible : Visibility.None) : Visibility.Visible)
  5073. .onClick(() => {
  5074. switch (step) {
  5075. case 0:
  5076. this.callFilePickerSelectFileForLyric()
  5077. break;
  5078. case 1:
  5079. //判断是不是赞助会员
  5080. if(PreferencesUtil.getStringSync('LRC_API','')===''){
  5081. ToastUtil.showToast('请到设置界面配置歌词服务器地址')
  5082. return
  5083. }
  5084. if (StrUtil.isNotEmpty(this.videoUrl)) {
  5085. ToastUtil.showToast('正在获取')
  5086. this.isLyricSetting = false
  5087. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  5088. this.initLyric(lyricPath, true);
  5089. }
  5090. break;
  5091. case 2:
  5092. //判断是不是赞助会员
  5093. // if(Utility.isNoble()){
  5094. if (StrUtil.isNotEmpty(this.videoUrl)) {
  5095. ToastUtil.showToast('正在获取')
  5096. this.isLyricSetting = false
  5097. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  5098. this.initLyric(lyricPath, true, true);
  5099. }
  5100. // }else{
  5101. // this.isLyricSetting = false
  5102. // this.showVipDialog()
  5103. // }
  5104. break;
  5105. }
  5106. })
  5107. .padding(5)
  5108. .width(110)
  5109. .height(40)
  5110. .margin({ left: 6, right: 6 })
  5111. .border({
  5112. color: '#FFFFFF',
  5113. radius: 20,
  5114. width: 1.8
  5115. })
  5116. }
  5117. showVipDialog() {
  5118. DialogHelper.showCustomContentDialog({
  5119. dialogId: 'vip',
  5120. title: "友情提示",
  5121. autoCancel: false, //点击遮障层时,不关闭弹窗
  5122. backCancel: true, //点击返回键,不关闭弹窗
  5123. contentBuilder: () => {
  5124. this.customVipBuilder("该功能需开通赞助功能,非常感谢您的支持!")
  5125. },
  5126. buttons: [],
  5127. })
  5128. }
  5129. //去赞助的自定义内容
  5130. @Builder
  5131. customVipBuilder(content: string) {
  5132. Column() {
  5133. Text(content)
  5134. .fontColor(Color.Gray)
  5135. .fontSize(16)
  5136. .alignSelf(ItemAlign.Start)
  5137. .margin({ bottom: 15 })
  5138. .fontSize(16)
  5139. Row() {
  5140. Button('取消')
  5141. .fontColor(Color.White)
  5142. .backgroundColor($r('app.color.title_bar_bg'))//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  5143. .height(50)
  5144. .layoutWeight(1)
  5145. .stateEffect(true)
  5146. .margin({ right: 6 })
  5147. .onClick(() => {
  5148. DialogHelper.closeDialog('vip'); //关闭弹框
  5149. })
  5150. Button('开通')
  5151. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  5152. .layoutWeight(1)
  5153. .height(50)
  5154. .backgroundColor($r('app.color.title_bar_bg'))
  5155. .stateEffect(true)
  5156. .margin({ left: 6 })
  5157. .onClick(() => {
  5158. DialogHelper.closeDialog('vip'); //关闭弹框
  5159. this.isShowPlay = false
  5160. router.pushUrl({
  5161. url: 'pages/VipPage'
  5162. }, router.RouterMode.Single);
  5163. })
  5164. }
  5165. }
  5166. .width("100%")
  5167. .padding(10)
  5168. }
  5169. @Builder
  5170. PlayMoreSheet() {
  5171. Column() {
  5172. this.MoreList()
  5173. }
  5174. .width('100%')
  5175. .height('100%')
  5176. }
  5177. @Builder
  5178. MoreList() {
  5179. Scroll() {
  5180. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  5181. ForEach(this.moreItems, (more: MoreItem) => {
  5182. Row() {
  5183. if (more.id === 3) {
  5184. Image(more.image)
  5185. .width(24)
  5186. .height(24)
  5187. .margin({ left: 10, right: 10 })
  5188. .onClick(() => {
  5189. this.isShowDetailMore = !this.isShowDetailMore;
  5190. })
  5191. Text(more.title)
  5192. .fontSize(16)
  5193. .fontColor(Color.White)
  5194. .onClick(() => {
  5195. this.doMore(more.id)
  5196. })
  5197. .bindSheet($$this.isShowDetailMore, this.detailSheet(), {
  5198. height: this.isCoverOpacity() ? '95%' : '65%',
  5199. dragBar: true,
  5200. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  5201. showClose: true,
  5202. blurStyle: BlurStyle.Thin,
  5203. backgroundColor: Color.Transparent,
  5204. title: { title: '歌曲信息' }
  5205. })
  5206. .onClick(() => {
  5207. this.isShowDetailMore = !this.isShowDetailMore;
  5208. })
  5209. } else if (more.id === 15) { //编辑信息
  5210. Image(more.image)
  5211. .width(24)
  5212. .height(24)
  5213. .margin({ left: 10, right: 10 })
  5214. .onClick(() => {
  5215. this.isShowEdit = !this.isShowEdit;
  5216. })
  5217. Text(more.title)
  5218. .fontSize(16)
  5219. .fontColor(Color.White)
  5220. .onClick(() => {
  5221. this.doMore(more.id)
  5222. })
  5223. .bindSheet($$this.isShowEdit, this.editSheet(), {
  5224. height: this.isCoverOpacity() ? '95%' : '93%',
  5225. dragBar: true,
  5226. showClose: true,
  5227. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  5228. // blurStyle:BlurStyle.Thin,
  5229. // backgroundColor:Color.Transparent,
  5230. title: { title: '编辑信息' }
  5231. })
  5232. .onClick(() => {
  5233. this.isShowEdit = !this.isShowEdit;
  5234. })
  5235. } else if (more.id === 5) { //定时关闭
  5236. Image(more.image)
  5237. .width(24)
  5238. .height(24)
  5239. .margin({ left: 10, right: 10 })
  5240. .onClick(() => {
  5241. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  5242. })
  5243. Text(more.title)
  5244. .fontSize(16)
  5245. .fontColor(Color.White)
  5246. .onClick(() => {
  5247. this.doMore(more.id)
  5248. })
  5249. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  5250. height: this.isCoverOpacity() ? '95%' : '78%',
  5251. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  5252. dragBar: true,
  5253. showClose: true,
  5254. title: { title: $r('app.string.time_close') }
  5255. })
  5256. .onClick(() => {
  5257. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  5258. })
  5259. } else if (more.id === 2) { //歌词设置
  5260. Image(more.image)
  5261. .width(24)
  5262. .height(24)
  5263. .margin({ left: 10, right: 10 })
  5264. .onClick(() => {
  5265. this.isLyricSetting = !this.isLyricSetting;
  5266. this.isShowMoreView = false
  5267. })
  5268. Text(more.title)
  5269. .fontSize(16)
  5270. .fontColor(Color.White)
  5271. .onClick(() => {
  5272. this.isLyricSetting = !this.isLyricSetting;
  5273. this.isShowMoreView = false
  5274. })
  5275. } else if (more.id === 11) { //跳过头尾
  5276. Image(more.image)
  5277. .width(24)
  5278. .height(24)
  5279. .margin({ left: 10, right: 10 })
  5280. .onClick(() => {
  5281. this.isJumpSetting = !this.isJumpSetting;
  5282. })
  5283. Text(more.title)
  5284. .fontSize(16)
  5285. .fontColor(Color.White)
  5286. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  5287. height: this.isCoverOpacity() ? '95%' : '60%',
  5288. dragBar: true,
  5289. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  5290. showClose: true,
  5291. blurStyle: BlurStyle.Thin,
  5292. backgroundColor: Color.Transparent,
  5293. title: { title: '跳过头尾' }
  5294. })
  5295. .onClick(() => {
  5296. this.isJumpSetting = !this.isJumpSetting;
  5297. })
  5298. } else if (more.id === 12) { //投播
  5299. AVCastPicker({
  5300. customPicker: (): void => this.TPImageBuilder(more),
  5301. onStateChange: (state) => {
  5302. if (state == AVCastPickerState.STATE_APPEARING) {
  5303. console.log(' The picker starts showing.');
  5304. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  5305. console.log(' The picker finishes presenting.');
  5306. }
  5307. },
  5308. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  5309. sessionType: 'video'
  5310. })
  5311. .id('AVCastPicker')
  5312. .width(46)
  5313. } else {
  5314. Image(more.image)
  5315. .width(24)
  5316. .height(24)
  5317. .margin({ left: 10, right: 10 })
  5318. .onClick(() => {
  5319. this.doMore(more.id)
  5320. })
  5321. Text(more.title)
  5322. .fontSize(16)
  5323. .fontColor(Color.White)
  5324. .onClick(() => {
  5325. this.doMore(more.id)
  5326. })
  5327. Select([//倍速
  5328. { value: '0.25x' },
  5329. { value: '0.5x' },
  5330. { value: '0.75x' },
  5331. { value: '1x' },
  5332. { value: '1.25x' },
  5333. { value: '1.5x' },
  5334. { value: '1.75x' },
  5335. { value: '2x' },
  5336. { value: '3x' }])
  5337. .font({ size: 16, weight: FontWeight.Medium })
  5338. .fontColor($r('sys.color.white'))
  5339. .margin({ left: 25 })
  5340. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  5341. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  5342. .value(Utility.optimizedFormat(this.playSpeed))
  5343. .onSelect(async (_index: number, text?: string | undefined) => {
  5344. let speed = parseFloat(text?.replace('x', '') || '1');
  5345. if (!CommonConstants.video_speed_list.includes(speed)) {
  5346. speed = 1;
  5347. }
  5348. this.playSpeed = speed
  5349. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  5350. })
  5351. Slider({
  5352. value: this.volume,
  5353. min: 0,
  5354. max: 1,
  5355. step: 0.1,
  5356. style: SliderStyle.OutSet
  5357. })
  5358. .margin({ left: 18, right: 8 })
  5359. .blockColor(Color.Red)
  5360. .trackColor($r('app.color.speed_text_color'))
  5361. .selectedColor(Color.White)
  5362. .trackThickness(9)
  5363. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  5364. .onChange((value: number) => {
  5365. this.volume = value;
  5366. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  5367. })
  5368. .layoutWeight(1)
  5369. Blank()
  5370. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  5371. .selectedColor($r('app.color.title_bar_bg'))
  5372. .switchPointColor(Color.White)
  5373. .margin({ right: 15 })
  5374. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  5375. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  5376. if (more.id == 6) {
  5377. this.isMusicMemoryPlay = checked;
  5378. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  5379. if (this.isMusicMemoryPlay) {
  5380. ToastUtil.showToast('记忆播放已开启')
  5381. } else {
  5382. ToastUtil.showToast('记忆播放已关闭')
  5383. }
  5384. }
  5385. })
  5386. .width(48)
  5387. .height(24);
  5388. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  5389. .selectedColor($r('app.color.title_bar_bg'))
  5390. .switchPointColor(Color.White)
  5391. .margin({ right: 15 })
  5392. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  5393. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  5394. if (more.id == 7) {
  5395. this.isMusicBGCover = checked;
  5396. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  5397. if (this.isMusicBGCover) {
  5398. ToastUtil.showToast('播放背景随音乐封面已开启')
  5399. } else {
  5400. ToastUtil.showToast('播放背景随音乐封面已关闭')
  5401. }
  5402. }
  5403. })
  5404. .width(48)
  5405. .height(24);
  5406. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  5407. .selectedColor($r('app.color.title_bar_bg'))
  5408. .switchPointColor(Color.White)
  5409. .margin({ right: 15 })
  5410. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  5411. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  5412. if (more.id == 8) {
  5413. this.isSavePlayMode = checked;
  5414. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  5415. if (this.isSavePlayMode) {
  5416. ToastUtil.showToast('保存播放模式已开启')
  5417. } else {
  5418. ToastUtil.showToast('保存播放模式已关闭')
  5419. }
  5420. }
  5421. })
  5422. .width(48)
  5423. .height(24);
  5424. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  5425. .selectedColor($r('app.color.title_bar_bg'))
  5426. .switchPointColor(Color.White)
  5427. .margin({ right: 15 })
  5428. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  5429. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  5430. if (more.id == 13) {
  5431. this.isCoverRectangle = checked;
  5432. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  5433. if (this.isCoverRectangle) {
  5434. ToastUtil.showToast('封面方形已开启')
  5435. this.animationRoFun()
  5436. } else {
  5437. ToastUtil.showToast('封面圆形已开启')
  5438. this.animationRoFun()
  5439. }
  5440. }
  5441. })
  5442. .width(48)
  5443. .height(24);
  5444. }
  5445. }
  5446. .width('100%')
  5447. .height(45)
  5448. .padding(15)
  5449. .backgroundColor(Color.Transparent) // 选中背景高亮
  5450. .borderRadius(12)
  5451. .margin({ bottom: 6 })
  5452. });
  5453. }
  5454. .width('100%')
  5455. .padding(16)
  5456. }.margin({ bottom: 18 })
  5457. }
  5458. @Builder
  5459. TPImageBuilder(more: MoreItem): void {
  5460. Row() {
  5461. Image($r('app.media.tuoping'))
  5462. .width(22)
  5463. .height(22)
  5464. .margin({ left: 10, right: 10 })
  5465. Text(more.title)
  5466. .fontSize(16)
  5467. .fontColor(Color.White)
  5468. }
  5469. }
  5470. private moreItems: MoreItem[] = [
  5471. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  5472. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  5473. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  5474. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  5475. { id: 4, image: $r('app.media.share2'), title: '分享' },
  5476. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  5477. { id: 15, image: $r('app.media.rename2'), title: '编辑信息' },
  5478. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  5479. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  5480. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  5481. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  5482. { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  5483. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  5484. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  5485. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  5486. ];
  5487. @State isShowMoreView: boolean = false;
  5488. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  5489. @State isShowTimeCloseMore: boolean = false
  5490. @State isShowDetailMore: boolean = false
  5491. @State isMusicBGCover: boolean = true
  5492. @State isSavePlayMode: boolean = true
  5493. @State isLyricSetting: boolean = false
  5494. @State isJumpSetting: boolean = false
  5495. @State isShowEdit: boolean = false
  5496. async setRingTone() {
  5497. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  5498. return
  5499. }
  5500. // 确定后的逻辑
  5501. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  5502. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  5503. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  5504. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  5505. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  5506. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  5507. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  5508. , this.videoUrl, this.name).then(res => {
  5509. LogUtil.info('onecold setFlag :' + res);
  5510. });
  5511. }
  5512. doMore(moreId: number) {
  5513. switch (moreId) {
  5514. case 10: //设为铃声
  5515. this.setRingTone()
  5516. this.isShowMoreView = false
  5517. break;
  5518. case 4: //分享
  5519. if (this.currentSong !== undefined) {
  5520. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  5521. }
  5522. this.isShowMoreView = false
  5523. break;
  5524. case 14: //搜索封面
  5525. this.doSearchCover()
  5526. this.isShowMoreView = false
  5527. break;
  5528. }
  5529. }
  5530. doSearchCover(){
  5531. if(PreferencesUtil.getStringSync('COVER_API','')===''){
  5532. ToastUtil.showToast('请到设置界面配置封面服务器地址')
  5533. return
  5534. }
  5535. if (this.currentSong !== undefined) {
  5536. let artist = this.currentSong?.artist
  5537. if (StrUtil.isEmpty(artist) || artist === undefined) {
  5538. artist = ''
  5539. }
  5540. this.searchCover(this.name, artist)
  5541. }
  5542. }
  5543. searchCover(title: string, artist: string) {
  5544. NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API','')).then(async (res) => {
  5545. LogUtil.debug("onecold res =" + res)
  5546. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  5547. this.cover = res
  5548. if (this.currentSong) {
  5549. this.currentSong.pixelMapPath = res
  5550. }
  5551. this.table.updatePixelMapPath(this.videoUrl, this.cover, (success: boolean, error?: string) => {
  5552. if (success) {
  5553. this.doUpdateData()
  5554. console.log(" onecold 更新音乐封面成功,数据库已同步");
  5555. } else {
  5556. console.error(" onecold 更新音乐封面数据库失败原因: " + error);
  5557. }
  5558. });
  5559. LogUtil.debug("onecold this.cover =" + this.cover)
  5560. }
  5561. })
  5562. }
  5563. @State jumpTopTime: number = 0
  5564. @State jumpEndTime: number = 0
  5565. @State isOpenJump: boolean = false
  5566. @Builder
  5567. JumpTopEndSheet() {
  5568. Scroll() {
  5569. Column() {
  5570. Column() {
  5571. Text('仅对本播放列表有效')
  5572. .fontSize(16)
  5573. .fontColor($r('app.color.text_color'))
  5574. // 跳过头尾
  5575. Column() {
  5576. Row() {
  5577. Text('跳过片头:')
  5578. .fontSize(16)
  5579. .fontColor($r('app.color.text_color'))
  5580. Text(this.jumpTopTime + 's')
  5581. .fontSize(16)
  5582. .fontColor($r('app.color.text_color'))
  5583. }
  5584. .margin({ bottom: 5 })
  5585. Row() {
  5586. Slider({
  5587. value: this.jumpTopTime,
  5588. min: 0,
  5589. max: 120,
  5590. step: 1,
  5591. style: SliderStyle.OutSet
  5592. })
  5593. .blockColor(Color.Red)
  5594. .trackColor($r('app.color.speed_text_color'))
  5595. .selectedColor(Color.White)
  5596. .trackThickness(8)
  5597. .onChange((value: number) => {
  5598. this.jumpTopTime = value;
  5599. })
  5600. .width('85%')
  5601. }
  5602. .alignItems(VerticalAlign.Top)
  5603. }
  5604. .margin({ top: 10, bottom: 10 })
  5605. // 跳过头尾
  5606. Column() {
  5607. Row() {
  5608. Text('跳过片尾:')
  5609. .fontSize(16)
  5610. .fontColor($r('app.color.text_color'))
  5611. Text(this.jumpEndTime + 's')
  5612. .fontSize(16)
  5613. .fontColor($r('app.color.text_color'))
  5614. }
  5615. .margin({ bottom: 5 })
  5616. Row() {
  5617. Slider({
  5618. value: this.jumpEndTime,
  5619. min: 0,
  5620. max: 120,
  5621. step: 1,
  5622. style: SliderStyle.OutSet
  5623. })
  5624. .blockColor(Color.Red)
  5625. .trackColor($r('app.color.speed_text_color'))
  5626. .selectedColor(Color.White)
  5627. .trackThickness(8)
  5628. .onChange((value: number) => {
  5629. this.jumpEndTime = value;
  5630. })
  5631. .width('85%')
  5632. }
  5633. .alignItems(VerticalAlign.Top)
  5634. }
  5635. .margin({ top: 10, bottom: 10 })
  5636. Row() {
  5637. Button('保存设置')
  5638. .fontColor(Color.White)
  5639. .layoutWeight(1)
  5640. .height(40)
  5641. .width(80)
  5642. .backgroundColor($r('app.color.title_bar_bg'))
  5643. .stateEffect(true)
  5644. .margin({ left: 0, bottom: 20 })
  5645. .onClick(async () => {
  5646. if (!Utility.isNoble()) {
  5647. this.isJumpSetting = false
  5648. this.isShowMoreView = false
  5649. this.showVipDialog()
  5650. return
  5651. }
  5652. if (this.currentSong === undefined) {
  5653. return
  5654. }
  5655. if (this.modeType === 0) {
  5656. let parentPath = FileUtil.getParentPath(this.videoUrl)
  5657. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  5658. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  5659. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  5660. } else if (this.modeType === 1) { //媒体库
  5661. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  5662. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  5663. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  5664. } else if (this.modeType === 2) { //艺术家
  5665. if (this.currentSong?.artist) {
  5666. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  5667. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  5668. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  5669. }
  5670. } else if (this.modeType === 3) { //专辑
  5671. if (this.currentSong?.album) {
  5672. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  5673. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  5674. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  5675. }
  5676. }
  5677. ToastUtil.showShort("保存成功")
  5678. this.isJumpSetting = false
  5679. })
  5680. }
  5681. .margin({
  5682. left: 38,
  5683. right: 38,
  5684. top: 10,
  5685. bottom: 10
  5686. })
  5687. .width(120)
  5688. .height(50)
  5689. }
  5690. }
  5691. }
  5692. .width('100%')
  5693. .height('100%')
  5694. }
  5695. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  5696. private onStateVastChange(state: AVCastPickerState) {
  5697. if (state == AVCastPickerState.STATE_APPEARING) {
  5698. console.log('The picker starts showing.');
  5699. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  5700. console.log('The picker finishes presenting.');
  5701. }
  5702. }
  5703. private showSelectLyric() {
  5704. DialogHelper.showActionSheetDialog({
  5705. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  5706. // sheets: ["本地歌词", "搜索歌词"],
  5707. sheets:[
  5708. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  5709. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  5710. ],
  5711. maskColor: Color.Transparent,
  5712. backgroundColor: $r('app.color.bg_card'),
  5713. transition: AnimationHelper.transitionInDown(666),
  5714. onAction: (index) => {
  5715. switch (index) {
  5716. case 0:
  5717. this.callFilePickerSelectFileForLyric()
  5718. break;
  5719. case 1:
  5720. if (StrUtil.isNotEmpty(this.videoUrl)) {
  5721. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  5722. this.initLyric(lyricPath);
  5723. }
  5724. break;
  5725. }
  5726. }
  5727. })
  5728. }
  5729. // 拉起picker选择文件管理器
  5730. async callFilePickerSelectFileForLyric(): Promise<void> {
  5731. try {
  5732. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  5733. DocumentSelectOptions.maxSelectNumber = 1
  5734. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  5735. let documentPicker = new picker.DocumentViewPicker();
  5736. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  5737. Logger.info(TAG,
  5738. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  5739. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  5740. this.saveVideoDatasLyric(DocumentSelectResult)
  5741. }
  5742. }).catch((err: BusinessError) => {
  5743. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  5744. });
  5745. } catch (err) {
  5746. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  5747. }
  5748. }
  5749. async saveVideoDatasLyric(uris: string[]) {
  5750. if (ArrayUtil.isEmpty(uris)) {
  5751. return
  5752. }
  5753. let newUris: string[] = [];
  5754. for (let i = 0; i < uris.length; i++) {
  5755. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  5756. Logger.info(TAG, 'filePath uri: ' + filePath);
  5757. newUris.push(filePath)
  5758. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  5759. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  5760. fileIo.copyFileSync(file.fd, file2.fd)
  5761. fileIo.closeSync(file);
  5762. fileIo.closeSync(file2);
  5763. this.initLyric(filePath)
  5764. }
  5765. }
  5766. private initDelayPlay(context: object) {
  5767. this.mContext = context;
  5768. }
  5769. private startPlayOrResumePlay() {
  5770. this.mDestroyPage = false;
  5771. this.animationState = AnimationStatus.Running
  5772. LogUtils.getInstance().LOGI("startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  5773. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  5774. this.stopProgressTask();
  5775. this.startProgressTask();
  5776. this.play(this.videoUrl.toString());
  5777. }
  5778. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  5779. this.mIjkMediaPlayer.start();
  5780. this.setProgress()
  5781. this.CONTROL_PlayStatus = PlayStatus.PLAY
  5782. }
  5783. this.setIsPlaying(true)
  5784. this.updateSessionPlayState(true)
  5785. this.watchStatus();
  5786. }
  5787. private completionNum(num: number): string | number {
  5788. if (num < 10) {
  5789. return '0' + num;
  5790. } else {
  5791. return num;
  5792. }
  5793. }
  5794. private stringForTime(timeMs: number): string {
  5795. let totalSeconds: number | string = (timeMs / 1000);
  5796. let newSeconds: number | string = totalSeconds % 60;
  5797. let minutes: number | string = (totalSeconds / 60) % 60;
  5798. let hours: number | string = totalSeconds / 3600;
  5799. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  5800. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  5801. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  5802. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  5803. if (this.isCurrentTime) {
  5804. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  5805. this.oldSeconds = newSeconds
  5806. } else {
  5807. newSeconds = this.oldSeconds
  5808. }
  5809. }
  5810. newSeconds = this.completionNum(newSeconds);
  5811. if (hours > 0) {
  5812. return hours + ":" + minutes + ":" + newSeconds;
  5813. } else {
  5814. return minutes + ":" + newSeconds;
  5815. }
  5816. }
  5817. private setProgress() {
  5818. let position = this.mIjkMediaPlayer.getCurrentPosition();
  5819. let duration = this.mIjkMediaPlayer.getDuration();
  5820. let pos = 0;
  5821. if (duration > 0) {
  5822. this.slideEnable = true;
  5823. let curPercent = position / duration;
  5824. pos = curPercent * 100;
  5825. if (pos > this.PROGRESS_MAX_VALUE) {
  5826. this.progressValue = this.PROGRESS_MAX_VALUE
  5827. } else {
  5828. this.progressValue = pos;
  5829. }
  5830. }
  5831. // LogUtils.getInstance()
  5832. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  5833. this.totalTime = this.stringForTime(duration);
  5834. if (position > duration) {
  5835. position = duration;
  5836. }
  5837. this.isCurrentTime = true;
  5838. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  5839. this.currentTime = this.stringForTime(position);
  5840. this.isCurrentTime = false
  5841. if (this.mIjkMediaPlayer.isPlaying()) {
  5842. this.randomColor =
  5843. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  5844. // 判断是否播放到结束时间
  5845. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  5846. if (position >= duration - this.jumpEndTime * 1000) {
  5847. this.playNext()
  5848. }
  5849. }
  5850. } else {
  5851. this.randomColor = 'rbg(0,0,0)'
  5852. }
  5853. }
  5854. private startProgressTask() {
  5855. let that = this;
  5856. this.updateProgressTimer = setInterval(() => {
  5857. //LogUtils.getInstance().LOGI("startProgressTask");
  5858. if (!that.mDestroyPage) {
  5859. that.setProgress();
  5860. }
  5861. }, 300);
  5862. }
  5863. private stopProgressTask() {
  5864. LogUtils.getInstance().LOGI("stopProgressTask");
  5865. clearInterval(this.updateProgressTimer);
  5866. }
  5867. private showLoadIng() {
  5868. this.loadingVisible = Visibility.Visible;
  5869. this.replayVisible = Visibility.None;
  5870. }
  5871. private hideLoadIng() {
  5872. this.loadingVisible = Visibility.None;
  5873. this.replayVisible = Visibility.None;
  5874. }
  5875. private showRePlay() {
  5876. this.loadingVisible = Visibility.None;
  5877. this.replayVisible = Visibility.Visible;
  5878. }
  5879. private async play(url: string) {
  5880. let that = this;
  5881. that.showLoadIng();
  5882. //设置XComponent回调的context
  5883. if (!!this.mContext) {
  5884. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  5885. }
  5886. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  5887. this.mIjkMediaPlayer.reset();
  5888. }
  5889. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  5890. //设置debug模式
  5891. this.mIjkMediaPlayer.setDebug(false);
  5892. //初始化配置
  5893. this.mIjkMediaPlayer.native_setup();
  5894. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0
  5895. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  5896. //设置视频源
  5897. this.mIjkMediaPlayer.setDataSource(url);
  5898. //设置视频源http请求头
  5899. let headers = new Map([
  5900. ["user_agent", "Mozilla/5.0 BiliDroid/7.30.0 (bbcallen@gmail.com)"],
  5901. ["referer", "https://www.bilibili.com"]
  5902. ]);
  5903. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  5904. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  5905. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  5906. // }
  5907. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  5908. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  5909. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  5910. const fileSize = await this.getFileSize(this.videoUrl);
  5911. let bufferSize = 1 * 1024 * 1024; // 默认缓冲区大小为2MB
  5912. if (fileSize > 3 * 1024 * 1024 * 1024) { // 文件大于3GB
  5913. bufferSize = 25 * 1024 * 1024; // 设置缓冲区大小为25MB
  5914. }
  5915. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  5916. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  5917. //停止预读的最小帧数
  5918. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  5919. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  5920. // 设置其他缓冲相关选项
  5921. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  5922. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  5923. //启动预加载
  5924. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  5925. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  5926. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  5927. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  5928. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  5929. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  5930. // 因此需要播放器丢包,才不会累积延时
  5931. // 这个和第三个参数packet-buffering无关。
  5932. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  5933. // 无限制收流
  5934. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  5935. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  5936. // 屏幕常亮
  5937. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  5938. // 设置超时
  5939. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  5940. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  5941. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  5942. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  5943. // 变速播放
  5944. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  5945. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  5946. let Speed = this.mIjkMediaPlayer.getSpeed()
  5947. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  5948. //是否开启循环播放
  5949. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  5950. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  5951. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  5952. if (height === 0) {
  5953. return;
  5954. }
  5955. const va = width / height;
  5956. const vpa = that.videoParentAspectRatio;
  5957. if (vpa > va) {
  5958. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  5959. } else {
  5960. that.videoWidth = '100%';
  5961. }
  5962. if (width && height) {
  5963. that.videoAspectRatio = width / height;
  5964. }
  5965. LogUtils.getInstance()
  5966. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  5967. that.hideLoadIng();
  5968. }
  5969. }
  5970. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  5971. let mOnPreparedListener: OnPreparedListener = {
  5972. onPrepared: async () => {
  5973. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  5974. try {
  5975. this.cover = this.songList[this.curIndex].pixelMapPath
  5976. this.artist = this.songList[this.curIndex].artist
  5977. this.videoUrl = this.songList[this.curIndex].filePath
  5978. let isBgCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  5979. if (isBgCover && this.cover !== undefined && StrUtil.isNotEmpty(this.cover)) {
  5980. this.setImageColor2(this.cover)
  5981. } else {
  5982. this.getImageColor();
  5983. }
  5984. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  5985. await this.initLyric(lyricPath);
  5986. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  5987. this.avSessionController.initAvSession(false);
  5988. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  5989. this.setAvSessionListener();
  5990. this.updateSessionPlayState(true)
  5991. this.setCurrentPlayMode()
  5992. this.addItemToHistory(this.songList[this.curIndex])
  5993. }, 500)
  5994. let timeoutPlay = 0
  5995. if (StrUtil.isNotEmpty(this.videoUrl) &&
  5996. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  5997. timeoutPlay = 1000
  5998. }
  5999. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  6000. if (this.modeType === 0) { //文件夹
  6001. let parentPath = FileUtil.getParentPath(this.videoUrl)
  6002. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  6003. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  6004. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  6005. } else if (this.modeType === 1) { //媒体库
  6006. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  6007. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  6008. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  6009. } else if (this.modeType === 2) { //艺术家
  6010. if (this.currentSong?.artist) {
  6011. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  6012. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  6013. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  6014. }
  6015. } else if (this.modeType === 3) { //专辑
  6016. if (this.currentSong?.album) {
  6017. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  6018. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  6019. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  6020. }
  6021. }
  6022. this.duration = this.mIjkMediaPlayer.getDuration()
  6023. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  6024. if (this.mIjkMediaPlayer != null) {
  6025. if (this.jumpTopTime * 1000 <= this.duration) {
  6026. // 调用 seekTo 方法,跳到指定时间
  6027. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  6028. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  6029. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  6030. }
  6031. }, timeoutPlay)
  6032. } else {
  6033. // 提示用户无法跳过
  6034. ToastUtil.showToast('跳过时间超过视频时长');
  6035. }
  6036. }
  6037. } else {
  6038. this.jumpTopTime = 0
  6039. this.jumpEndTime = 0
  6040. //记忆播放
  6041. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  6042. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  6043. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  6044. this.restorePlaybackPosition() //读取播放记忆功能
  6045. }
  6046. }, timeoutPlay)
  6047. }
  6048. }
  6049. this.saveLastPlayList()
  6050. } catch (error) {
  6051. let err: BusinessError = error as BusinessError;
  6052. console.error('onecold failed with err: ' + JSON.stringify(err));
  6053. }
  6054. }
  6055. }
  6056. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  6057. let mOnTimedTextListener: OnTimedTextListener = {
  6058. onTimedText: () => {
  6059. }
  6060. }
  6061. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  6062. let mOnCompletionListener: OnCompletionListener = {
  6063. onCompletion: () => {
  6064. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  6065. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  6066. this.playNext()
  6067. } else if (this.playType == 1) { //1:单片重复播放
  6068. this.CONTROL_PlayStatus = PlayStatus.INIT
  6069. that.startPlayOrResumePlay();
  6070. } else if (this.playType == 2) { //2:正常播放,单曲播完
  6071. that.showRePlay();
  6072. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  6073. that.progressValue = this.PROGRESS_MAX_VALUE;
  6074. that.slideEnable = false;
  6075. that.stop();
  6076. // ToastUtil.showToast('开始重新播放')
  6077. } else if (this.playType == 3) { //3:随机播放
  6078. this.randomPlay()
  6079. }
  6080. }
  6081. }
  6082. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  6083. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  6084. onBufferingUpdate: (percent: number) => {
  6085. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  6086. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  6087. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  6088. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  6089. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  6090. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  6091. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  6092. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  6093. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  6094. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  6095. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  6096. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  6097. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  6098. let Looping = this.mIjkMediaPlayer.isLooping()
  6099. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  6100. }
  6101. }
  6102. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  6103. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  6104. onSeekComplete: () => {
  6105. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  6106. that.startPlayOrResumePlay();
  6107. }
  6108. }
  6109. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  6110. let mOnInfoListener: OnInfoListener = {
  6111. onInfo: (what: number, extra: number) => {
  6112. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  6113. that.hideLoadIng();
  6114. }
  6115. }
  6116. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  6117. let mOnErrorListener: OnErrorListener = {
  6118. onError: (what: number, extra: number) => {
  6119. this.stopProgressTask();
  6120. LogUtils.getInstance().LOGI("OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  6121. that.hideLoadIng();
  6122. if (StrUtil.isNotEmpty(this.videoUrl) && !FileUtil.accessSync(this.videoUrl)) {
  6123. ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
  6124. } else {
  6125. ToastUtil.showToast(getContext()
  6126. .resourceManager
  6127. .getStringByNameSync("Honey_the_video_is_playing_errant_The_system_is_wandering"))
  6128. }
  6129. }
  6130. }
  6131. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  6132. this.mIjkMediaPlayer.setMessageListener();
  6133. this.mIjkMediaPlayer.prepareAsync();
  6134. this.mIjkMediaPlayer.start();
  6135. }
  6136. //保存最后播放的那首歌和已经对应的播放列表
  6137. saveLastPlayList() {
  6138. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  6139. PreferencesUtil.putSync('LastMusicList', this.songList)
  6140. }
  6141. //添加播放历史记录
  6142. async addItemToHistory(vItem: VideoItem) {
  6143. if (vItem.type === CommonConstants.TYPE_LOCK) {
  6144. return
  6145. }
  6146. // 检查是否已存在记录
  6147. const existingIndex = this.historyList.findIndex(item => item.filePath === vItem.filePath);
  6148. if (existingIndex !== -1) {
  6149. // 更新现有记录的播放时间
  6150. this.historyList[existingIndex].lastPlayed = new Date();
  6151. } else {
  6152. // 添加新的播放记录
  6153. let newItem: VideoItem = new VideoItem(vItem.name, '', vItem.filePath, vItem.type,
  6154. vItem.videoSize, vItem.cTime, vItem.pixelMap, vItem.size, vItem.pixelMapPath, vItem.artist, vItem.album
  6155. , vItem.fileName, new Date())
  6156. this.historyList.push(newItem);
  6157. }
  6158. // 保持播放记录不超过50条
  6159. if (this.historyList.length > 50) {
  6160. this.historyList = this.historyList.slice(0, 50);
  6161. }
  6162. // 按播放时间降序排序
  6163. this.historyList.sort((a, b) => {
  6164. let timeA = a.lastPlayed ? a.lastPlayed.getTime() : 0;
  6165. let timeB = b.lastPlayed ? b.lastPlayed.getTime() : 0;
  6166. return timeB - timeA;
  6167. });
  6168. // 缓存结果
  6169. PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  6170. if (this.isHistory) {
  6171. this.updateListData(this.historyList)
  6172. }
  6173. }
  6174. // 删除播放记录
  6175. removeVideoFromHistory(path: string) {
  6176. this.historyList = this.historyList.filter(item => item.filePath !== path);
  6177. }
  6178. // 清空播放记录
  6179. clearVideoHistory() {
  6180. this.historyList = [];
  6181. this.updateListData(this.historyList)
  6182. PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  6183. ToastUtil.showToast('清空播放记录成功')
  6184. }
  6185. public async setAvSessionListener() {
  6186. if (!this.avSessionController) {
  6187. return;
  6188. }
  6189. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  6190. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  6191. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  6192. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  6193. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  6194. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  6195. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  6196. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  6197. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  6198. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  6199. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  6200. }
  6201. setLoopMode() {
  6202. let itype = this.playType + 1
  6203. if (itype >= 4) {
  6204. this.playType = 0
  6205. ToastUtil.showToast('连续播放')
  6206. } else if (itype === 1) {
  6207. this.playType = 1
  6208. ToastUtil.showToast('单曲循环')
  6209. } else if (itype === 2) {
  6210. this.playType = 2
  6211. ToastUtil.showToast('单曲播完')
  6212. } else if (itype === 3) {
  6213. this.playType = 3
  6214. ToastUtil.showToast('随机播放')
  6215. } else if (itype === 0) {
  6216. this.playType = 0
  6217. ToastUtil.showToast('连续播放')
  6218. }
  6219. PreferencesUtil.putSync('musicPlayType', this.playType)
  6220. this.setCurrentPlayMode()
  6221. }
  6222. private sessionSetLoopModeCallback = (mode: number) => {
  6223. if (this.mIjkMediaPlayer != null) {
  6224. ToastUtil.showToast('当前播放模式:' + mode)
  6225. Logger.info('onecold 当前播放模式= ' + mode)
  6226. let hmPlayMode = mode + 1
  6227. if (hmPlayMode >= 4) {
  6228. hmPlayMode = 0
  6229. }
  6230. if (hmPlayMode === 1) {
  6231. this.playType = 1
  6232. ToastUtil.showToast('单曲循环')
  6233. } else if (hmPlayMode === 0) {
  6234. this.playType = 2
  6235. ToastUtil.showToast('单曲播完')
  6236. } else if (hmPlayMode === 3) {
  6237. this.playType = 3
  6238. ToastUtil.showToast('随机播放')
  6239. } else if (hmPlayMode === 2) {
  6240. this.playType = 0
  6241. ToastUtil.showToast('连续播放')
  6242. }
  6243. PreferencesUtil.putSync('musicPlayType', this.playType)
  6244. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  6245. let playBackState: avSession.AVPlaybackState = {
  6246. loopMode: hmPlayMode,
  6247. };
  6248. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  6249. console.info(`set setLoopMode AVPlaybackState successfully`);
  6250. }).catch((err: BusinessError) => {
  6251. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  6252. });
  6253. }
  6254. }
  6255. setCurrentPlayMode() {
  6256. if (!this.avSessionController) {
  6257. return;
  6258. }
  6259. let mLoopMode = 0
  6260. switch (this.playType) {
  6261. case 0:
  6262. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  6263. break;
  6264. case 1:
  6265. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  6266. break;
  6267. case 2:
  6268. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  6269. break;
  6270. case 3:
  6271. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  6272. break;
  6273. }
  6274. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  6275. let playBState: avSession.AVPlaybackState = {
  6276. loopMode: mLoopMode,
  6277. isFavorite:Utility.getIsFav(this.favList,this.currentSong),
  6278. };
  6279. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  6280. console.info(`set setLoopMode AVPlaybackState successfully`);
  6281. }).catch((err: BusinessError) => {
  6282. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  6283. });
  6284. }
  6285. private sessionToggleFavoriteCallback = (assetId: string) => {
  6286. if (this.mIjkMediaPlayer != null && this.currentSong) {
  6287. console.info(`on toggleFavorite `);
  6288. // 应用收到收藏命令,进行收藏处理。
  6289. this.isFac = Utility.getIsFav(this.favList,this.currentSong)
  6290. this.doFav(this.currentSong)
  6291. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  6292. let playbackState: avSession.AVPlaybackState = {
  6293. isFavorite:!this.isFac,
  6294. };
  6295. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  6296. console.info(`SetAVPlaybackState successfully`);
  6297. }).catch((err: BusinessError) => {
  6298. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  6299. });
  6300. }
  6301. }
  6302. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  6303. device: avSession.OutputDeviceInfo) => {
  6304. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  6305. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  6306. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  6307. await this.startCasting();
  6308. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  6309. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  6310. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  6311. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  6312. if (device) {
  6313. this.endCasting();
  6314. }
  6315. }
  6316. };
  6317. private async startCasting() {
  6318. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  6319. this.setPlaybackStateChangeListener();
  6320. this.pause();
  6321. this.initQueueItem();
  6322. this.prepare();
  6323. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  6324. refToIsCasting?.set(true);
  6325. this.castSeek = true;
  6326. this.isCastPlaying = true;
  6327. }
  6328. async changeCasting() {
  6329. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  6330. this.initQueueItem();
  6331. this.prepare();
  6332. this.setPlaybackStateChangeListener();
  6333. this.isCastPlaying = true;
  6334. this.castSeek = true;
  6335. }
  6336. public endCasting() {
  6337. this.avSessionController.getAvSession()?.stopCasting();
  6338. this.stopCast();
  6339. this.isCastPlaying = false;
  6340. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  6341. refToIsCasting?.set(false);
  6342. this.pause();
  6343. this.setIsPlaying(false);
  6344. // if (this.curIndex === this.curSource.index) {
  6345. // this.play
  6346. // this.seek(this.currentTime * 1000);
  6347. // this.setIsPlaying(true);
  6348. // } else {
  6349. // this.pauseVideo();
  6350. // this.setIsPlaying(false);
  6351. // }
  6352. }
  6353. public setIsPlaying(isPlayer: boolean) {
  6354. this.isPlaying = isPlayer;
  6355. }
  6356. private setPlaybackStateChangeListener(): void {
  6357. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  6358. this.castController?.on('endOfStream', this.reloadCasting);
  6359. this.castController?.on('playNext', this.playNextCallback);
  6360. this.castController?.on('playPrevious', this.playPreviousCallback);
  6361. }
  6362. private updateSessionPlayState(isPlay: boolean): void {
  6363. // if(!this.isBgPlayOpen)
  6364. // return
  6365. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  6366. this.setAVSessionPlayState({
  6367. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  6368. position: {
  6369. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  6370. updateTime: new Date().getTime()
  6371. }
  6372. });
  6373. }
  6374. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  6375. this.avSessionController.setAvSessionPlayState(playbackState)
  6376. }
  6377. private positionChange(position: number) {
  6378. this.currentTime2 = position / 1000;
  6379. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  6380. }
  6381. private playDurationChange(duration: number) {
  6382. this.duration = duration;
  6383. this.durationTime = Math.floor(this.duration / 1000);
  6384. this.durationStringTime = secondToTime((this.durationTime));
  6385. }
  6386. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  6387. const duration = playbackState?.extras?.duration;
  6388. if (typeof duration === 'number') {
  6389. this.playDurationChange(duration as number);
  6390. }
  6391. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  6392. this.positionChange(playbackState?.position?.elapsedTime);
  6393. }
  6394. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  6395. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  6396. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  6397. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  6398. this.isCastPlaying = false;
  6399. }
  6400. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  6401. this.isCastPlaying = true;
  6402. }
  6403. };
  6404. private reloadCasting = async () => {
  6405. let item = this.songList[this.curIndex];
  6406. let uri = fileUri.getUriFromPath(item.filePath);
  6407. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  6408. // description.startPosition = 0;
  6409. this.castItem = {
  6410. itemId: this.curIndex,
  6411. description: {
  6412. assetId: item.filePath,
  6413. title: item.name,
  6414. artist: '',
  6415. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  6416. // mediaUri: item.filePath,
  6417. fdSrc: {
  6418. fd: file.fd
  6419. },
  6420. // 该字段大写,音频'AUDIO',视频'VIDEO'
  6421. mediaType: 'VIDEO',
  6422. mediaSize: item.videoSize,
  6423. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  6424. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  6425. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  6426. duration: this.duration,
  6427. // albumCoverUri: 'https://www.example.jpeg',
  6428. // albumTitle: '《ExampleAlbum》',
  6429. appName: this.appName,
  6430. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  6431. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  6432. }
  6433. };
  6434. this.prepare();
  6435. this.isCastPlaying = true;
  6436. };
  6437. public playNextCallback = (): void => {
  6438. this.playNext()
  6439. };
  6440. public playPreviousCallback = (): void => {
  6441. this.playPrevious()
  6442. };
  6443. async prepare() {
  6444. await this.castController?.prepare(this.castItem);
  6445. await this.castController?.start(this.castItem);
  6446. }
  6447. public initQueueItem() {
  6448. let item = this.songList[this.curIndex];
  6449. let time = this.currentTime;
  6450. let uri = fileUri.getUriFromPath(item.filePath);
  6451. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  6452. this.castItem = {
  6453. itemId: this.curIndex,
  6454. description: {
  6455. assetId: item.filePath,
  6456. title: item.name,
  6457. artist: '',
  6458. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  6459. fdSrc: {
  6460. fd: file.fd
  6461. },
  6462. // 该字段大写,音频'AUDIO',视频'VIDEO'
  6463. mediaType: 'AUDIO',
  6464. mediaSize: item.videoSize,
  6465. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  6466. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  6467. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  6468. duration: this.duration,
  6469. // albumCoverUri: 'https://www.example.jpeg',
  6470. // albumTitle: '《ExampleAlbum》',
  6471. appName: this.appName,
  6472. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  6473. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  6474. }
  6475. };
  6476. }
  6477. async stopCast() {
  6478. try {
  6479. this.castController?.off('playbackStateChange');
  6480. this.castController?.off('endOfStream');
  6481. this.castController?.off('playNext');
  6482. this.castController?.off('playPrevious');
  6483. this.castController?.off('error');
  6484. } catch (error) {
  6485. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  6486. }
  6487. }
  6488. private sessionPlayCallback = (): void => {
  6489. this.playOrPause()
  6490. };
  6491. private sessionPauseCallback = (): void => {
  6492. this.playOrPause()
  6493. };
  6494. private playOrPause() {
  6495. if (!this.debounce()) {
  6496. return;
  6497. }
  6498. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  6499. this.pause();
  6500. } else {
  6501. this.startPlayOrResumePlay();
  6502. this.playChange()
  6503. }
  6504. }
  6505. private sessionPlayNextCallback = (): void => {
  6506. this.playNext()
  6507. };
  6508. private sessionPlayPreviousCallback = (): void => {
  6509. this.playPrevious()
  6510. };
  6511. private sessionStopCallback = (): void => {
  6512. this.stop()
  6513. };
  6514. private sessionFastForwardCallback = (time?: number) => {
  6515. if (!time) {
  6516. return;
  6517. }
  6518. if (this.mIjkMediaPlayer != null) {
  6519. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  6520. let seeTime = curPosition + time * 1000;
  6521. // 限制 seekValue 在合法范围内
  6522. if (seeTime < 0) {
  6523. seeTime = 0;
  6524. } else if (seeTime > this.duration) {
  6525. seeTime = this.duration;
  6526. }
  6527. Logger.info('onecold seeTime= ' + seeTime)
  6528. this.setSeekToActionProgress(seeTime)
  6529. this.seekTo(seeTime + "")
  6530. }
  6531. };
  6532. /**
  6533. * Gesture method onActionUpdate.
  6534. *
  6535. * @param event Gesture event.手势拖动设置快进和后退
  6536. */
  6537. private setSeekToActionProgress(position: number) {
  6538. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  6539. let duration = this.mIjkMediaPlayer.getDuration();
  6540. let pos = 0;
  6541. if (duration > 0) {
  6542. this.slideEnable = true;
  6543. let curPercent = position / duration;
  6544. pos = curPercent * 100;
  6545. if (pos > this.PROGRESS_MAX_VALUE) {
  6546. this.progressValue = this.PROGRESS_MAX_VALUE
  6547. } else {
  6548. this.progressValue = pos;
  6549. }
  6550. }
  6551. // LogUtils.getInstance()
  6552. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  6553. this.totalTime = this.stringForTime(duration);
  6554. if (position > duration) {
  6555. position = duration;
  6556. }
  6557. this.isCurrentTime = true;
  6558. this.currentTime = this.stringForTime(position);
  6559. this.isCurrentTime = false
  6560. }
  6561. private sessionRewindCallback = (time?: number) => {
  6562. if (!time) {
  6563. return;
  6564. }
  6565. if (this.mIjkMediaPlayer != null) {
  6566. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  6567. let seeTime = curPosition - time * 1000;
  6568. // 限制 seekValue 在合法范围内
  6569. if (seeTime < 0) {
  6570. seeTime = 0;
  6571. } else if (seeTime > this.duration) {
  6572. seeTime = this.duration;
  6573. }
  6574. Logger.info('onecold seeTime= ' + seeTime)
  6575. this.setSeekToActionProgress(seeTime)
  6576. this.seekTo(seeTime + "")
  6577. }
  6578. };
  6579. private sessionSeekCallback = (seekTime: number) => {
  6580. if (this.mIjkMediaPlayer != null) {
  6581. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  6582. this.seekTo(seekTime + "")
  6583. }
  6584. };
  6585. private async getFileSize(filePath: string): Promise<number> {
  6586. try {
  6587. const stat = await fs.stat(filePath);
  6588. return stat.size;
  6589. } catch (err) {
  6590. console.error('Failed to get file size: ' + err.message);
  6591. return 0;
  6592. }
  6593. }
  6594. private pause() {
  6595. if (this.mIjkMediaPlayer.isPlaying()) {
  6596. this.savePlaybackPosition();
  6597. this.mIjkMediaPlayer.pause();
  6598. this.setProgress();
  6599. this.mDestroyPage = true;
  6600. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  6601. this.updateSessionPlayState(false)
  6602. this.playChange()
  6603. }
  6604. }
  6605. private stop() {
  6606. this.savePlaybackPosition();
  6607. this.CONTROL_PlayStatus = PlayStatus.INIT;
  6608. this.mIjkMediaPlayer.stop();
  6609. this.mIjkMediaPlayer.release();
  6610. this.stopProgressTask();
  6611. this.updateSessionPlayState(false)
  6612. this.playChange()
  6613. this.watchStatus();
  6614. }
  6615. //保持记忆播放功能
  6616. private savePlaybackPosition() {
  6617. if (this.mIjkMediaPlayer != null) {
  6618. const position = this.mIjkMediaPlayer.getCurrentPosition();
  6619. // ToastUtil.showToast('保存记忆播放 = ' + position)
  6620. const duration = this.mIjkMediaPlayer.getDuration();
  6621. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  6622. // 如果播放位置接近视频末尾,则保存 position 为 0
  6623. const playbackPosition = (duration - position < threshold) ? 0 : position;
  6624. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  6625. }
  6626. }
  6627. //获取记忆播放功能
  6628. private restorePlaybackPosition() {
  6629. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  6630. // ToastUtil.showToast('position = ' + position)
  6631. if (this.mIjkMediaPlayer != null && position > 0) {
  6632. // ToastUtil.showToast('seekTo = ' + position)
  6633. this.seekTo(position + "");
  6634. }
  6635. }
  6636. private seekTo(value: string) {
  6637. // this.stopProgressTask();
  6638. if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  6639. ToastUtil.showToast('wma格式不支持拖动快进。')
  6640. return
  6641. }
  6642. this.mIjkMediaPlayer.seekTo(value);
  6643. // this.startPlayOrResumePlay()
  6644. // 在这里恢复计时器状态
  6645. this.setProgress()
  6646. // this.startProgressTask();
  6647. }
  6648. // 添加到下一首播放
  6649. private addToNextPlay(song: VideoItem) {
  6650. if (!this.debounce()) {
  6651. return;
  6652. }
  6653. if (this.currentSong) {
  6654. if (this.currentSong === song) {
  6655. ToastUtil.showToast('当前已经在播放这首歌了!')
  6656. return
  6657. }
  6658. }
  6659. // 如果未开始播放或队列为空
  6660. if (this.curIndex === -1 || this.songList.length === 0) {
  6661. this.songList = [song];
  6662. this.curIndex = 0;
  6663. this.doPlay(song)
  6664. return;
  6665. }
  6666. // 插入到当前索引+1的位置
  6667. const insertPos = this.curIndex + 1;
  6668. this.songList.splice(insertPos, 0, song);
  6669. this.songList = [...this.songList]; // 触发状态更新
  6670. this.sonDataSource.pushArrayData(this.songList)
  6671. ToastUtil.showToast('已添加至下一首播放')
  6672. }
  6673. //下一个
  6674. private playNext() {
  6675. if (!this.debounce()) {
  6676. return;
  6677. }
  6678. if (this.playType == 3) { //3:随机播放
  6679. this.randomPlay()
  6680. return;
  6681. }
  6682. if (ArrayUtil.isNotEmpty(this.songList)) {
  6683. if (this.curIndex == this.songList.length - 1) {
  6684. this.curIndex = 0;
  6685. } else {
  6686. this.curIndex++;
  6687. }
  6688. this.CONTROL_PlayStatus = PlayStatus.INIT;
  6689. this.stop();
  6690. this.currentSong = this.songList[this.curIndex]
  6691. this.videoUrl = this.songList[this.curIndex].filePath;
  6692. this.name = this.songList[this.curIndex].name
  6693. this.startPlayOrResumePlay()
  6694. }
  6695. }
  6696. // 存储已播放的歌曲索引
  6697. private playedIndices: Set<number> = new Set();
  6698. //随机播放
  6699. private randomPlay() {
  6700. // if (!this.debounce()) {
  6701. // return;
  6702. // }
  6703. if (ArrayUtil.isNotEmpty(this.songList)) {
  6704. if (this.songList.length > 3) {
  6705. // 如果所有歌曲都播放过一次,清空已播放索引集合
  6706. if (this.playedIndices.size === this.songList.length) {
  6707. this.playedIndices.clear();
  6708. }
  6709. // 随机选择一个未播放的歌曲索引
  6710. let newIndex: number;
  6711. do {
  6712. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  6713. } while (this.playedIndices.has(newIndex));
  6714. this.curIndex = newIndex;
  6715. this.playedIndices.add(newIndex);
  6716. } else {
  6717. // 当歌曲数量小于或等于3时,直接播放下一首
  6718. if (this.curIndex == this.songList.length - 1) {
  6719. this.curIndex = 0;
  6720. } else {
  6721. this.curIndex++;
  6722. }
  6723. }
  6724. this.CONTROL_PlayStatus = PlayStatus.INIT;
  6725. this.stop();
  6726. this.currentSong = this.songList[this.curIndex];
  6727. this.videoUrl = this.songList[this.curIndex].filePath;
  6728. this.name = this.songList[this.curIndex].name;
  6729. this.startPlayOrResumePlay();
  6730. }
  6731. }
  6732. private playIndex(index: number) {
  6733. if (!this.debounce()) {
  6734. return;
  6735. }
  6736. if (ArrayUtil.isNotEmpty(this.songList)) {
  6737. this.CONTROL_PlayStatus = PlayStatus.INIT;
  6738. this.stop();
  6739. this.currentSong = this.songList[this.curIndex]
  6740. this.videoUrl = this.songList[index].filePath;
  6741. this.name = this.songList[index].name
  6742. this.curIndex = index;
  6743. this.startPlayOrResumePlay()
  6744. }
  6745. }
  6746. //上一个
  6747. private playPrevious() {
  6748. if (!this.debounce()) {
  6749. return;
  6750. }
  6751. if (this.playType == 3) { //3:随机播放
  6752. this.randomPlay()
  6753. return;
  6754. }
  6755. if (this.curIndex == 0) {
  6756. this.curIndex = this.songList.length - 1;
  6757. } else {
  6758. this.curIndex--;
  6759. }
  6760. this.CONTROL_PlayStatus = PlayStatus.INIT;
  6761. this.stop();
  6762. this.currentSong = this.songList[this.curIndex]
  6763. this.videoUrl = this.songList[this.curIndex].filePath;
  6764. this.name = this.songList[this.curIndex].name
  6765. this.startPlayOrResumePlay()
  6766. }
  6767. debounce() {
  6768. const delay = 600;
  6769. let cur = new Date().getTime();
  6770. if (cur - this.last > delay) {
  6771. this.last = cur;
  6772. return true;
  6773. }
  6774. return false;
  6775. }
  6776. /**
  6777. * Sets whether the screen is a constant based on the playback status.
  6778. */
  6779. watchStatus() {
  6780. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  6781. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  6782. this.windowClass.setWindowKeepScreenOn(true);
  6783. } else {
  6784. this.windowClass.setWindowKeepScreenOn(false);
  6785. }
  6786. }
  6787. /**
  6788. * Volume gesture method onActionStart.
  6789. *
  6790. * @param event Gesture event.
  6791. */
  6792. private customDialogComponentIdMM: number = 0
  6793. @Builder
  6794. customDialogComponentMM() {
  6795. Column() {
  6796. Row() {
  6797. Blank()
  6798. Text('验证密码')
  6799. .fontSize(22)
  6800. .fontColor($r('app.color.pri_bg'))
  6801. .margin({ top: 18 })
  6802. Blank()
  6803. Image($r('app.media.close'))
  6804. .fillColor(Color.White)
  6805. .margin({ top: 18, right: 18 })
  6806. .width(20)
  6807. .onClick(() => {
  6808. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  6809. })
  6810. }
  6811. .width('100%') // 使Row占据整个宽度
  6812. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  6813. Verify({
  6814. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  6815. });
  6816. }.height('60%')
  6817. .backgroundColor($r('app.color.index_background'))
  6818. .justifyContent(FlexAlign.SpaceBetween)
  6819. }
  6820. private handleVerifyCompleted(isSuccess: boolean) {
  6821. if (isSuccess) {
  6822. console.log('验证成功');
  6823. // 在这里处理验证成功后的逻辑
  6824. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  6825. this.currentPath = this.lockPath
  6826. this.getSortedFiles(this.currentPath)
  6827. } else {
  6828. // console.log('验证失败');
  6829. ToastUtil.showToast('验证失败')
  6830. }
  6831. }
  6832. private showVerifyDialog() {
  6833. promptAction.openCustomDialog({
  6834. transition: TransitionEffect.asymmetric(
  6835. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  6836. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  6837. ,
  6838. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  6839. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  6840. ),
  6841. builder: () => {
  6842. this.customDialogComponentMM()
  6843. },
  6844. isModal: true,
  6845. autoCancel: true,
  6846. maskColor: Color.Transparent,
  6847. alignment: DialogAlignment.Bottom,
  6848. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  6849. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  6850. console.log("dialog onWillDismiss")
  6851. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  6852. dismissDialogAction.dismiss()
  6853. }
  6854. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  6855. dismissDialogAction.dismiss()
  6856. }
  6857. }
  6858. }).then((dialogId: number) => {
  6859. this.customDialogComponentIdMM = dialogId
  6860. })
  6861. }
  6862. //左滑操作 移动文件 重命名 删除等操作
  6863. @Builder
  6864. DeleteButton(item: VideoItem, index: number, filePath: string) {
  6865. Row() {
  6866. //加入收藏
  6867. Button() {
  6868. Image(Utility.getIsFav(this.favList,item)?$r('app.media.add_fac_light2'):$r('app.media.add_fac'))
  6869. .fillColor(Color.White)
  6870. .width(20)
  6871. }
  6872. .width(40)
  6873. .height(40)
  6874. .type(ButtonType.Circle)
  6875. .backgroundColor($r('app.color.title_bar_bg'))
  6876. .margin(5)
  6877. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6878. .onClick(() => {
  6879. if(item){
  6880. this.doFav(item)
  6881. }
  6882. })
  6883. //加入下一首播放
  6884. Button() {
  6885. Image($r('app.media.next_to_play'))
  6886. .fillColor(Color.White)
  6887. .width(20)
  6888. }
  6889. .width(40)
  6890. .height(40)
  6891. .type(ButtonType.Circle)
  6892. .backgroundColor($r('app.color.title_bar_bg'))
  6893. .margin(5)
  6894. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6895. .onClick(() => {
  6896. this.addToNextPlay(item);
  6897. })
  6898. //复制文件
  6899. Button() {
  6900. Image($r('app.media.copy'))
  6901. .fillColor(Color.White)
  6902. .width(20)
  6903. }
  6904. .width(40)
  6905. .height(40)
  6906. .type(ButtonType.Circle)
  6907. .backgroundColor($r('app.color.title_bar_bg'))
  6908. .margin(5)
  6909. .id(filePath + 'copy')
  6910. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6911. .onClick(() => {
  6912. this.showCopyDialog(false, item, index, filePath + 'copy');
  6913. })
  6914. //移动文件
  6915. Button() {
  6916. Image($r('app.media.cut'))
  6917. .fillColor(Color.White)
  6918. .width(20)
  6919. }
  6920. .width(40)
  6921. .height(40)
  6922. .type(ButtonType.Circle)
  6923. .backgroundColor($r('app.color.title_bar_bg'))
  6924. .margin(5)
  6925. .id(filePath)
  6926. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6927. .onClick(() => {
  6928. this.showCutDialog(false, item, index, filePath);
  6929. })
  6930. Button() {
  6931. Image($r('app.media.cut_current'))
  6932. .fillColor(Color.White)
  6933. .width(20)
  6934. }
  6935. .width(40)
  6936. .height(40)
  6937. .type(ButtonType.Circle)
  6938. .backgroundColor($r('app.color.title_bar_bg'))
  6939. .margin(5)
  6940. .id(filePath + 'current')
  6941. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  6942. (this.isHasDir ? Visibility.Visible : Visibility.None))
  6943. .onClick(() => {
  6944. this.showCutDialog(true, item, index, filePath + 'current');
  6945. })
  6946. //重命名
  6947. Button() {
  6948. Image($r('app.media.rename2'))
  6949. .fillColor(Color.White)
  6950. .width(20)
  6951. }
  6952. .width(40)
  6953. .height(40)
  6954. .type(ButtonType.Circle)
  6955. .backgroundColor($r('app.color.title_bar_bg'))
  6956. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  6957. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  6958. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  6959. .margin(5)
  6960. .onClick(() => {
  6961. this.showReNameDialog(item, index + '', filePath)
  6962. })
  6963. Button() {
  6964. Image($r('app.media.delete2'))
  6965. .fillColor(Color.White)
  6966. .width(20)
  6967. }
  6968. .width(40)
  6969. .height(40)
  6970. .type(ButtonType.Circle)
  6971. .backgroundColor($r('app.color.title_bar_bg'))
  6972. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  6973. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  6974. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  6975. .margin(5)
  6976. .onClick(() => {
  6977. this.showWarnIsDeleteFile(item, index + '', filePath)
  6978. })
  6979. Button() {
  6980. Image($r('app.media.share2'))
  6981. .fillColor(Color.White)
  6982. .width(20)
  6983. }
  6984. .width(40)
  6985. .height(40)
  6986. .type(ButtonType.Circle)
  6987. .backgroundColor($r('app.color.title_bar_bg'))
  6988. .margin(5)
  6989. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6990. .onClick(() => {
  6991. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  6992. })
  6993. }
  6994. }
  6995. /**
  6996. * 穿山甲banner广告
  6997. */
  6998. private declare bannerAd: CSJNativeExpressAd;
  6999. @State private status: string = "未加载"
  7000. @State private isShowAd: boolean = false
  7001. private declare mAdSlot: AdSlot;
  7002. private mBiddingAdm = '' //服务端bidding才需要设置
  7003. private expressLoadAdListener: NativeExpressAdListener = {
  7004. /**
  7005. * 加载失败的回调
  7006. *
  7007. * @param code
  7008. * @param message
  7009. */
  7010. onError: (code: number, message: string) => {
  7011. console.error("加载广告失败,code=" + code + ",message=" + message);
  7012. this.status = "加载广告失败,code=" + code + ",message=" + message;
  7013. },
  7014. /**
  7015. * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  7016. *
  7017. * @param ads 返回的广告列表
  7018. */
  7019. onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  7020. console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  7021. if (ads && ads.length > 0) {
  7022. ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  7023. ad.setExpressInteractionListener({
  7024. /**
  7025. *广告的点击回调
  7026. * @param type 广告的交互类型
  7027. */
  7028. onAdClicked: (type: number) => {
  7029. console.log("BannerExpressAdPage==onAdClicked......");
  7030. },
  7031. /**
  7032. * 广告的展示回调 每个广告仅回调一次
  7033. * @param type 广告的交互类型
  7034. */
  7035. onAdShow: (type: number) => {
  7036. console.log("BannerExpressAdPage==onAdShow......");
  7037. },
  7038. /**
  7039. * 模板渲染失败
  7040. */
  7041. onRenderFail: (code: number, msg: string) => {
  7042. console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  7043. },
  7044. /**
  7045. * 模板渲染成功
  7046. * @param width 返回view的宽 单位 vp
  7047. * @param height 返回view的高 单位 vp
  7048. */
  7049. onRenderSuccess: (width: number, height: number) => {
  7050. console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  7051. this.bannerAd = ad;
  7052. this.status = "广告加载完成待展示";
  7053. this.showBannerAd()
  7054. }
  7055. })
  7056. //渲染广告
  7057. ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  7058. this.setDislikeCallback(ad); //设置dislike
  7059. ad.render(this.getUIContext())
  7060. this.status = "广告加载中...";
  7061. });
  7062. }
  7063. }
  7064. }
  7065. private setDislikeCallback(ad: CSJNativeExpressAd) {
  7066. ad.setDislikeCallback({
  7067. /**
  7068. * dislike show
  7069. */
  7070. onShow: () => {
  7071. console.log("BannerExpressAdPage==dislike......show");
  7072. },
  7073. /**
  7074. * @param position 选择的位置
  7075. * @param value 选择的内容
  7076. * @param enforceRemove 是否强制关闭广告
  7077. */
  7078. onSelected: (position: number, value: string, enforceRemove: boolean) => {
  7079. this.isShowAd = false;
  7080. console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  7081. ",enforce=" + enforceRemove);
  7082. },
  7083. /**
  7084. * 点击取消
  7085. */
  7086. onCancel: () => {
  7087. console.log("BannerExpressAdPage==dislike......onCancel");
  7088. }
  7089. })
  7090. }
  7091. /**
  7092. * 加载Banner广告
  7093. */
  7094. loadBannerAd(rit: string) {
  7095. if (Utility.isNoble()) {
  7096. return
  7097. }
  7098. if (!Utility.isPassInstallTime(2)) {
  7099. return
  7100. }
  7101. this.isShowAd = false;
  7102. let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  7103. this.mAdSlot = new AdSlotBuilder()
  7104. .setCodeId(rit)
  7105. .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  7106. .setAdCount(1)
  7107. .setBidAdm(this.mBiddingAdm)
  7108. .build()
  7109. PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  7110. adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  7111. this.status = "广告加载中..."
  7112. }
  7113. /**
  7114. * 展示Banner广告
  7115. */
  7116. showBannerAd() {
  7117. if (!this.bannerAd) {
  7118. return
  7119. }
  7120. this.isShowAd = true
  7121. this.status = "已展示"
  7122. }
  7123. /**
  7124. * 穿山甲广告代码结束
  7125. */
  7126. }
  7127. //视频气泡窗口的布局
  7128. @Builder
  7129. function customPopupBuilder(dataBu: BubbleBean) {
  7130. List() {
  7131. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  7132. ListItem() {
  7133. Row() {
  7134. Column() {
  7135. Image(dataBu.imageRes[index])
  7136. .height(28)
  7137. .alignSelf(ItemAlign.Center)
  7138. }
  7139. .width(32)
  7140. Text(item)
  7141. .padding({
  7142. top: 10,
  7143. bottom: 10,
  7144. right: 10,
  7145. left: 10
  7146. })
  7147. .textAlign(TextAlign.Start)
  7148. .width("100%")
  7149. }
  7150. .margin({ top: 6, bottom: 6 })
  7151. }.onClick(() => {
  7152. dataBu.onItemClick?.(index)
  7153. })
  7154. })
  7155. }
  7156. .width(120)
  7157. .divider({
  7158. strokeWidth: 1,
  7159. color: "#22FFFFFF"
  7160. })
  7161. }
  7162. // Function to calculate a hash for the file list
  7163. function simpleHash(fileList: string[]): string {
  7164. let hash = 0;
  7165. const str = fileList.join(',');
  7166. for (let i = 0; i < str.length; i++) {
  7167. const char = str.charCodeAt(i);
  7168. hash = (hash << 5) - hash + char;
  7169. hash |= 0; // Convert to 32bit integer
  7170. }
  7171. return hash.toString();
  7172. }
  7173. interface MoreItem {
  7174. id: number;
  7175. image: Resource;
  7176. title: string;
  7177. }
  7178. //视频气泡窗口的布局
  7179. @Builder
  7180. function cutPopupBuilder(dataBu: BubbleBean) {
  7181. Column() {
  7182. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  7183. .padding({
  7184. top: 10,
  7185. bottom: 10,
  7186. right: 10,
  7187. left: 10
  7188. })
  7189. .textAlign(TextAlign.Start)
  7190. .width(160)
  7191. .fontWeight(666)
  7192. .fontSize(16)
  7193. List() {
  7194. ForEach(dataBu.data, (item: string, index: number) => {
  7195. ListItem() {
  7196. Row() {
  7197. Column() {
  7198. Image($r('app.media.music_group'))
  7199. .height(28)
  7200. .alignSelf(ItemAlign.Center)
  7201. }
  7202. .width(32)
  7203. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  7204. .padding({
  7205. top: 10,
  7206. bottom: 10,
  7207. right: 10,
  7208. left: 10
  7209. })
  7210. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  7211. .fontSize(15)
  7212. }
  7213. .margin({ top: 7, bottom: 7 })
  7214. }.onClick(() => {
  7215. dataBu.onItemClick?.(index)
  7216. })
  7217. })
  7218. }
  7219. .width(150)
  7220. .divider({
  7221. strokeWidth: 1,
  7222. color: "#22FFFFFF"
  7223. })
  7224. }
  7225. .height(300)
  7226. .padding({
  7227. bottom:30
  7228. })
  7229. }