LocalMusic.ets 254 KB

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