Utility.ets 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002
  1. import { BusinessError, pasteboard } from '@kit.BasicServicesKit';
  2. import {
  3. AppUtil,
  4. ArrayUtil,
  5. Base64Util,
  6. DateUtil, FileUtil, ImageUtil, LogUtil,
  7. MD5,
  8. PreferencesUtil,
  9. RandomUtil, StrUtil } from '@pura/harmony-utils';
  10. import { media } from '@kit.MediaKit';
  11. import fs, { ReadTextOptions } from '@ohos.file.fs';
  12. import { image } from '@kit.ImageKit';
  13. import fileIo from '@ohos.file.fs';
  14. import { VideoItem } from '../../viewmodel/VideoItem';
  15. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  16. import { dataSharePredicates, uniformTypeDescriptor } from '@kit.ArkData';
  17. import { systemShare } from '@kit.ShareKit';
  18. import { fileUri, picker } from '@kit.CoreFileKit';
  19. import { common, UIAbility, Want } from '@kit.AbilityKit';
  20. import { CommonConstants, STR_LOCK_VIDEO, VIP_FILEPATH } from '../constants/CommonConstants';
  21. import { window } from '@kit.ArkUI';
  22. import { bundleManager } from '@kit.AbilityKit'
  23. import { pinyin4js } from '@ohos/pinyin4js';
  24. import { VipData } from '../../viewmodel/VipData';
  25. import { VipPage } from '../../pages/VipPage';
  26. import { FFmpeg, FFProgressMessageParser } from '@sj/ffmpeg';
  27. import ImageUtils from './ImageUtils';
  28. export interface FFMpegTags {
  29. album?: string;
  30. ALBUM?: string;
  31. artist?: string;
  32. ARTIST?: string;
  33. TITLE?: string;
  34. title?: string;
  35. track?: string;
  36. TRACK?: string;
  37. TYER?: string;
  38. year?: string;
  39. genre?:string;
  40. GENRE?:string;
  41. date?: string;
  42. DATE?: string;
  43. LYRICS?: string;
  44. lyrics?: string; // 小写变体
  45. USLT?: string; // ID3v2同步歌词
  46. UNSYNCEDLYRICS?: string; // ID3v2非同步歌词
  47. // Add any other tag properties you expect
  48. ALBUMARTIST?:string//专辑艺术家
  49. COMPOSER?:string//作曲家
  50. LYRICIST?:string//作词家
  51. COMMENT?:string//注释
  52. albumartist?:string//专辑艺术家
  53. album_artist?:string//专辑艺术家
  54. TPE2?:string//专辑艺术家
  55. composer?:string//作曲家
  56. lyricist?:string//作词家
  57. TEXT?:string//作词家
  58. comment?:string//注释
  59. COMM?:string//注释
  60. comm?:string//注释
  61. disc?:string//音碟号
  62. }
  63. interface FFprobeFormat {
  64. filename: string;
  65. nb_streams: number;
  66. nb_programs: number;
  67. format_name: string;
  68. format_long_name: string;
  69. duration: string;
  70. size: string;
  71. bit_rate: string;
  72. probe_score: number;
  73. tags?: FFMpegTags;
  74. }
  75. interface FFprobeStream {
  76. // Define stream properties as needed
  77. codec_type?: string; // 流类型,如"audio"、"video"
  78. sample_rate?: string; // 采样率
  79. bit_rate?: string; // 比特率
  80. disposition?: StreamDisposition; // 添加disposition属性
  81. bits_per_raw_sample?: string; // 位深
  82. channels?: string; // 声道数
  83. channel_layout?: string; // 声道布局
  84. start_time?: string; // 起始播放
  85. }
  86. interface StreamDisposition {
  87. default?: number;
  88. dub?: number;
  89. original?: number;
  90. comment?: number;
  91. lyrics?: number;
  92. karaoke?: number;
  93. forced?: number;
  94. hearing_impaired?: number;
  95. visual_impaired?: number;
  96. clean_effects?: number;
  97. attached_pic?: number; // 添加封面图片标识
  98. timed_thumbnails?: number;
  99. captions?: number;
  100. descriptions?: number;
  101. metadata?: number;
  102. dependent?: number;
  103. still_image?: number;
  104. }
  105. interface FFprobeMetadata {
  106. streams: FFprobeStream[];
  107. format: FFprobeFormat;
  108. }
  109. export class Utility {
  110. private constructor() {}
  111. static isOpenTime():boolean{
  112. const currentDate = new Date();
  113. const targetDate = new Date(CommonConstants.OPEN_DATE);
  114. if (currentDate > targetDate) {
  115. return true
  116. }
  117. return false
  118. }
  119. static readonly FOREVER_DATE: string = 'forever';
  120. /**
  121. * 是否会员(只看线上会员状态)
  122. */
  123. static isNoble(): boolean {
  124. // 只判断线上会员状态
  125. return PreferencesUtil.getBooleanSync('hasActiveSubscription', false);
  126. }
  127. static isForever(): boolean {
  128. // 判断是不是永久会员
  129. return PreferencesUtil.getBooleanSync('isForever', false);
  130. }
  131. /**
  132. * 旧版客户端判断会员状态
  133. * @returns
  134. */
  135. static isNobleForOld():boolean{
  136. if(!Utility.isOpenTime())//提交审核的审核,刚刚开始可以全部是赞助用户。
  137. return true
  138. return PreferencesUtil.getBooleanSync('isNoble',false)
  139. }
  140. /**
  141. * setNoble方法废弃,保留兼容但不做任何操作
  142. */
  143. static setNoble(expireDate:string){
  144. let isNoble = false
  145. if(StrUtil.isNotEmpty(expireDate)){
  146. if(expireDate===VipPage.FOREVER_DATE){
  147. isNoble = true
  148. }else{
  149. const currentDate = new Date();
  150. const targetDate = DateUtil.getFormatDate(expireDate)
  151. if (currentDate > targetDate) {
  152. isNoble = false
  153. }else{
  154. isNoble = true
  155. }
  156. }
  157. }
  158. PreferencesUtil.putSync('isNoble',isNoble)
  159. }
  160. /**
  161. * 判断用户安装app是否超过2天,超过2天(2800分钟)才展示广告 显示广告 24*60=1440 1440*2=2800
  162. * @param day
  163. * @returns
  164. */
  165. static isPassInstallTime(day:number):boolean{
  166. //获取当前时间
  167. let currentTime = new Date().getTime();
  168. // 尝试从存储中获取安装时间
  169. let installTime = getInstallTime();
  170. if (installTime===0||installTime === null|| installTime===undefined) {
  171. // 如果没有存储安装时间,则存储当前时间为安装时间
  172. setInstallTime(currentTime);
  173. return false
  174. } else {
  175. // 计算时间差(以分钟为单位)
  176. const timeDifference = (currentTime - installTime) / (1000 * 60);
  177. LogUtil.debug("onecold timeDifference=" + timeDifference)
  178. // 如果超过5分钟,显示广告 24*60=1440 1440*2=2800
  179. if (timeDifference > 24*60*day) {
  180. return true
  181. }else{
  182. return false
  183. }
  184. }
  185. }
  186. // 定义一个函数来获取当前的时间段
  187. static getTimePeriod(): string {
  188. const now = new Date();
  189. const hours = now.getHours();
  190. if (hours >= 5 && hours < 12) {
  191. return "早上好";
  192. } else if (hours >= 12 && hours < 18) {
  193. return "下午好";
  194. } else if (hours >= 18 && hours < 22) {
  195. return "晚上好";
  196. } else {
  197. return "夜深了";
  198. }
  199. }
  200. static optimizedFormat(speed: number): string {
  201. if (speed) {
  202. const str = speed.toFixed(2);
  203. let end = str.length;
  204. while (end > 0 && (str[end - 1] === '0' || str[end - 1] === '.')) {
  205. end--;
  206. if (str[end] === '.') {
  207. break;
  208. }
  209. }
  210. return str.slice(0, end || 1) + 'x';
  211. } else {
  212. return '1x'
  213. }
  214. }
  215. static isHaoOpenTime():boolean{
  216. const currentDate = new Date();
  217. const targetDate = new Date('2025-04-20');
  218. if (currentDate < targetDate) {
  219. return true
  220. }
  221. return false
  222. }
  223. static addDays(date: Date, days: number): Date {
  224. const result = new Date(date);
  225. result.setDate(result.getDate() + days);
  226. return result;
  227. }
  228. static convertToKHz(sampleRateHz: string|undefined): string {
  229. if(StrUtil.isEmpty(sampleRateHz)||sampleRateHz ===undefined)
  230. return '0KHz'
  231. const sampleRateKHz = Number(sampleRateHz) / 1000;
  232. return `${sampleRateKHz} KHz`;
  233. }
  234. /**
  235. * 格式化媒体格式类型显示
  236. * @param mimeType 媒体格式类型字符串
  237. * @return 格式化后的显示字符串
  238. */
  239. static formatMimeType(mimeType: string | undefined): string {
  240. if (StrUtil.isEmpty(mimeType) || mimeType === undefined) {
  241. return 'unknown';
  242. }
  243. // 从MIME类型中提取格式部分,例如 "audio/mp3" -> "MP3"
  244. try {
  245. const parts = mimeType.split('/');
  246. if (parts.length > 1) {
  247. return parts[1].toUpperCase();
  248. } else {
  249. return mimeType.toUpperCase();
  250. }
  251. } catch (err) {
  252. console.error(`格式化媒体类型出错: ${err}`);
  253. return 'unknown';
  254. }
  255. }
  256. //根据字节获取大小
  257. static formatFileSize(bytes:number) {
  258. const units = ['Bytes', 'Kbps', 'Mbps'];
  259. let size = bytes;
  260. let unitIndex = 0;
  261. while (size >= 1024 && unitIndex < units.length - 1) {
  262. size /= 1024;
  263. unitIndex++;
  264. }
  265. if(size > 1024&&unitIndex==2){
  266. size = size*0.1
  267. }
  268. if(size > 1024&&unitIndex==2){
  269. size = size*0.1
  270. }
  271. if(size > 480&&unitIndex==2){
  272. size = size*0.5
  273. }
  274. // 保留两位小数, 四舍五入
  275. size = Math.round(size * 10) / 10;
  276. return size + units[unitIndex]
  277. }
  278. //根据字节获取大小无单位
  279. static formatFileSizeWithout(bytes:number) {
  280. const units = ['Bytes', 'Kbps', 'Mbps'];
  281. let size = bytes;
  282. let unitIndex = 0;
  283. while (size >= 1024 && unitIndex < units.length - 1) {
  284. size /= 1024;
  285. unitIndex++;
  286. }
  287. if(size > 1024&&unitIndex==2){
  288. size = size*0.1
  289. }
  290. if(size > 1024&&unitIndex==2){
  291. size = size*0.1
  292. }
  293. if(size > 480&&unitIndex==2){
  294. size = size*0.5
  295. }
  296. // 保留两位小数, 四舍五入
  297. size = Math.round(size * 10) / 10;
  298. return size
  299. }
  300. static copyText(text:string):boolean{
  301. const pasteboardData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN,text)
  302. const systemPasteboard = pasteboard.getSystemPasteboard()
  303. systemPasteboard.setData(pasteboardData)
  304. systemPasteboard.getData().then((data)=>{
  305. return data
  306. })
  307. return false
  308. }
  309. static getDbm(rssi:number):number{
  310. return Math.round((rssi / 2) + 100)
  311. }
  312. //根据数字形式的IP地址获取字符串形式的IP地址
  313. static getIpAddrFromNum(ipNum: number): string {
  314. return (ipNum >>> 24) + '.' + (ipNum >> 16 & 0xFF) + '.' + (ipNum >> 8 & 0xFF) + '.' + (ipNum & 0xFF);
  315. }
  316. static resolveIP(ip:number) {
  317. let address: string = ip.toString()
  318. if (address === '0') {
  319. return '00:00:000:000'
  320. }
  321. address.substring(0, 2)
  322. return `${address.substring(0, 2)}:${address.substring(2, 4)}:${address.substring(4, 7)}:${address.substring(7, 10)}`
  323. }
  324. static isFreeTime():boolean{
  325. if(DateUtil.isWeekend()){
  326. return true
  327. }
  328. let str = DateUtil.getFormatDateStr(new Date(), 'HH')
  329. let a = Number(str);
  330. if(isNaN(a))
  331. return false
  332. // ToastUtil.showToast('a='+a)
  333. if (a >= 7 && a <13) {//白天
  334. return false;
  335. }
  336. if (a >= 13 && a <20) {//白天
  337. return false;
  338. }
  339. if (a >= 0 && a < 7) {//凌晨
  340. return true;
  341. }
  342. if (a >= 20 && a <= 24) {//晚上
  343. return true;
  344. }
  345. return false
  346. }
  347. //判断是否是音乐文件
  348. static isMusicByExtension(filename:string) {
  349. const extensions = CommonConstants.REAL_MUSIC_FORMAT
  350. const lastIndex = filename.lastIndexOf('.');
  351. if (lastIndex!== -1) {
  352. const fileExtension = filename.slice(lastIndex).toLowerCase();
  353. return extensions.includes(fileExtension);
  354. }
  355. return false;
  356. }
  357. //判断是否是媒体文件 音乐和视频都可以
  358. static isMediaByExtension(filename:string) {
  359. const extensions = CommonConstants.MEDIA_FORMAT
  360. const lastIndex = filename.lastIndexOf('.');
  361. if (lastIndex!== -1) {
  362. const fileExtension = filename.slice(lastIndex).toLowerCase();
  363. return extensions.includes(fileExtension);
  364. }
  365. return false;
  366. }
  367. //判断是否是视频文件
  368. static isVideoByExtension(filename:string) {
  369. const extensions = CommonConstants.VIDEO_FORMAT
  370. const lastIndex = filename.lastIndexOf('.');
  371. if (lastIndex!== -1) {
  372. const fileExtension = filename.slice(lastIndex).toLowerCase();
  373. return extensions.includes(fileExtension);
  374. }
  375. return false;
  376. }
  377. // 获取缩略图
  378. static async getFetchFrameByTime(filePath: string,time?:number) {
  379. if(Utility.isMusicByExtension(filePath)){
  380. return undefined
  381. }
  382. let pixelMap:image.PixelMap|undefined =undefined;
  383. try{
  384. // 创建AVImageGenerator对象
  385. let avImageGenerator: media.AVImageGenerator = await media.createAVImageGenerator()
  386. let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
  387. let avFileDescriptor: media.AVFileDescriptor = { fd: file.fd };
  388. avImageGenerator.fdSrc = avFileDescriptor;
  389. // 初始化入参
  390. let timeUs = 0
  391. console.info('onecold time='+time)
  392. if(time){
  393. timeUs = (time > 0) ? time*60 : 0
  394. }
  395. let queryOption = media.AVImageQueryOptions.AV_IMAGE_QUERY_NEXT_SYNC
  396. let param: media.PixelMapParams = {
  397. width : 300,
  398. height : 400,
  399. }
  400. // 获取缩略图(promise模式)
  401. pixelMap = await avImageGenerator.fetchFrameByTime(timeUs, queryOption, param)
  402. // 释放资源(promise模式)
  403. avImageGenerator.release()
  404. console.info(`release success.`)
  405. fs.closeSync(file);
  406. }catch (error) {
  407. console.error('uriGetAssets failed with err: ' + JSON.stringify(error));
  408. }
  409. return pixelMap
  410. }
  411. // 获取fd文件路径
  412. static async getFdDir(path:string){
  413. let fdPath = 'fd://';
  414. let file = await fileIo.open(path)
  415. fdPath = fdPath + '' + file.fd;
  416. return fdPath
  417. }
  418. // 根据uri获取文件名称
  419. static getMediaNameByUri(myUri: string) {
  420. let myFileName = (myUri.split('/').pop()) as string;
  421. return decodeURIComponent(myFileName)
  422. }
  423. static msToStandardTime(ms:string):string{
  424. let date = new Date(ms);
  425. let hours = date.getHours();
  426. let minutes = date.getMinutes();
  427. let seconds = date.getSeconds();
  428. return hours + ':' + minutes + ':' + seconds;
  429. }
  430. static getTimestampFromDateStr(dateStr: string, format: string = 'yyyy-MM-dd HH:mm'): number {
  431. // 定义正则表达式以匹配日期字符串中的各部分
  432. const regex = format
  433. .replace('yyyy', '(\\d{4})')
  434. .replace('MM', '(\\d{2})')
  435. .replace('dd', '(\\d{2})')
  436. .replace('HH', '(\\d{2})')
  437. .replace('mm', '(\\d{2})');
  438. const match = new RegExp(regex).exec(dateStr);
  439. if (!match) {
  440. throw new Error('Invalid date string or format');
  441. }
  442. // 解析匹配结果
  443. const year = Number(match[1]);
  444. const month = Number(match[2]);
  445. const day = Number(match[3]);
  446. const hours = Number(match[4]);
  447. const minutes = Number(match[5]);
  448. // 创建 Date 对象
  449. const dateObj = new Date(year, month - 1, day, hours, minutes);
  450. // 返回时间戳(以秒为单位)
  451. return Math.floor(dateObj.getTime() / 1000);
  452. }
  453. static getFormatDateStr(date: number | string | Date, format: string = 'yyyy-MM-dd HH:mm:ss'): string {
  454. // 将输入转换为 Date 对象
  455. let dateObj: Date;
  456. if (typeof date === 'number') {
  457. // 如果是十位时间戳,转换为毫秒数
  458. dateObj = new Date(date.toString().length === 10 ? date * 1000 : date);
  459. } else if (typeof date === 'string') {
  460. // 如果是字符串,尝试解析为 Date 对象
  461. dateObj = new Date(date);
  462. } else {
  463. // 如果是 Date 对象,直接使用
  464. dateObj = date;
  465. }
  466. // 定义替换规则
  467. const replacements = new Map<string, string>([
  468. ['yyyy', String(dateObj.getFullYear())],
  469. ['MM', String(dateObj.getMonth() + 1).padStart(2, '0')],
  470. ['dd', String(dateObj.getDate()).padStart(2, '0')],
  471. ['HH', String(dateObj.getHours()).padStart(2, '0')],
  472. ['mm', String(dateObj.getMinutes()).padStart(2, '0')],
  473. ['ss', String(dateObj.getSeconds()).padStart(2, '0')]
  474. ]);
  475. // 替换格式字符串中的占位符
  476. replacements.forEach((value, key) => {
  477. format = format.replace(new RegExp(key, 'g'), value);
  478. });
  479. return format;
  480. }
  481. static async getFilePixelMapBig(uri:string){
  482. let pixelMap:image.PixelMap|undefined = undefined
  483. if(Utility.isMusicByExtension(uri)){
  484. pixelMap = await Utility.getFetchMetadataFromFdSrcByPromise(uri)
  485. }else{
  486. pixelMap = await Utility.getFetchFrameByTime(uri)
  487. }
  488. return ImageUtils.pixelMapToBase64StrBig(pixelMap)
  489. }
  490. static async getFilePixelMap(uri:string){
  491. let pixelMap:image.PixelMap|undefined = undefined
  492. if(Utility.isMusicByExtension(uri)){
  493. pixelMap = await Utility.getFetchMetadataFromFdSrcByPromise(uri)
  494. }else{
  495. pixelMap = await Utility.getFetchFrameByTime(uri)
  496. }
  497. return ImageUtil.pixelMapToBase64Str(pixelMap)
  498. }
  499. //根据filePathe获取对应的播放Index
  500. static getIndexFromList(localList:Array<VideoItem>,filePath:string){
  501. let list: Array<string> = [];
  502. for(let i=0;i<localList.length;i++){
  503. if(localList[i].filePath === filePath){
  504. return i
  505. }
  506. }
  507. return 0
  508. }
  509. // 在以下demo中,使用资源管理接口获取打包在HAP内的媒体资源文件,通过设置fdSrc属性,获取音频元数据并打印,
  510. // 获取音频专辑封面并通过Image控件显示在屏幕上。该demo以Promise形式进行异步接口调用
  511. static async getFetchMetadataFromFdSrcByPromise(uri: string): Promise<image.PixelMap | undefined> {
  512. let cover: image.PixelMap | undefined = undefined;
  513. if (canIUse("SystemCapability.Multimedia.Media.AVMetadataExtractor")) {
  514. try {
  515. // 创建AVMetadataExtractor对象
  516. const avMetadataExtractor: media.AVMetadataExtractor = await media.createAVMetadataExtractor();
  517. // 设置fdSrc
  518. const fd = await fs.openSync(uri, fs.OpenMode.READ_ONLY);
  519. avMetadataExtractor.fdSrc = fd;
  520. // 获取元数据(promise模式)
  521. const metadata = await avMetadataExtractor.fetchMetadata();
  522. metadata.author
  523. console.info(`get meta data, hasAudio: ${metadata.hasAudio}`);
  524. // 获取专辑封面(promise模式)
  525. cover = await avMetadataExtractor.fetchAlbumCover();
  526. // 释放资源(promise模式)
  527. await avMetadataExtractor.release();
  528. console.info('release success.');
  529. } catch (error) {
  530. console.error('Error during metadata extraction:', error);
  531. }
  532. } else {
  533. console.warn('AVMetadataExtractor capability is not supported.');
  534. }
  535. return cover;
  536. }
  537. static formatTimestamp(timestamp: number): string {
  538. // 将时间戳转换为 Date 对象
  539. const date = new Date(timestamp);
  540. // 获取各个部分
  541. const year = date.getFullYear();
  542. const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需要加1
  543. const day = String(date.getDate()).padStart(2, '0');
  544. const hours = String(date.getHours()).padStart(2, '0');
  545. const minutes = String(date.getMinutes()).padStart(2, '0');
  546. const seconds = String(date.getSeconds()).padStart(2, '0');
  547. // 拼接成所需的格式
  548. return `${year}-${month}-${day} ${hours}:${minutes}`;
  549. }
  550. //获取音乐资源的属性值,
  551. static async uriGetMusicAssetsFromFile(context:Context,uri:string,type:number,isLoadPixelMap?:boolean): Promise<VideoItem> {
  552. return Utility.readMetaInfoFFmpeg(context,uri,type)
  553. //华为官方不支持的格式 不支持内嵌歌词Dsf,aif,aiff,wav 不支持内嵌封面dsf,aif,aiff
  554. if(StrUtil.isNotEmpty(uri)){
  555. if(uri.toLowerCase().endsWith('.dsf')
  556. ||uri.toLowerCase().endsWith('.aif')
  557. // ||uri.toLowerCase().endsWith('.wav')
  558. ||uri.toLowerCase().endsWith('.aiff')){
  559. return Utility.readMetaInfoFFmpeg(context,uri,type)
  560. }
  561. }
  562. let item:VideoItem = new VideoItem('',uri,uri,type,0,'')
  563. try {
  564. console.info('asset file.uri: ', uri);
  565. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY | fs.OpenMode.CREATE)
  566. console.info("file.fd " + file.fd);
  567. let fdfd = 'fd://' + file.fd
  568. //3、通过fs.stat方法获取stat对象
  569. console.info('asset file.name: ', file.name);
  570. console.info('asset file.uri: ', uri);
  571. console.info('asset file.fd: ', file.fd);
  572. console.info('asset file.path: ', file.path);
  573. item = new VideoItem(file.name,uri,uri,type,0,'')
  574. await fs.stat(file.fd).then(async (stat: fs.Stat) => {
  575. console.info("get file info succeed, the size of file is " + stat.size);
  576. let videoSize = stat.size
  577. // let videoTime = stat.ctime
  578. let fileSize = Utility.formatFSize(videoSize)
  579. //按照添加时间
  580. let addTime = Utility.getFormatDateStr(new Date(),'yyyy-MM-dd HH:mm');
  581. // console.info('onecold asset addTime: ', addTime);
  582. // let cTime = Utility.getFormatDateStr(stat.mtime,'yyyy-MM-dd HH:mm')
  583. // console.info('asset stat.ctime: ', stat.ctime);
  584. let musicName:string | undefined = file.name
  585. let artist:string | undefined = ''
  586. let album:string | undefined = ''
  587. let pixelMap:image.PixelMap|undefined|null = undefined
  588. let imagePath = ''
  589. let duration:string | undefined = ''
  590. let mimeType:string | undefined = ''
  591. let trackCount:string | undefined = ''//轨道数量
  592. let sampleRate:string | undefined = ''//音频的采样率单位为Hz
  593. if (canIUse("SystemCapability.Multimedia.Media.AVMetadataExtractor")) {
  594. try {
  595. // 创建AVMetadataExtractor对象
  596. const avMetadataExtractor: media.AVMetadataExtractor = await media.createAVMetadataExtractor();
  597. // 设置fdSrc
  598. const fd = await fs.openSync(uri, fs.OpenMode.READ_ONLY);
  599. avMetadataExtractor.fdSrc = fd;
  600. // 获取元数据(promise模式)
  601. const metadata = await avMetadataExtractor.fetchMetadata();
  602. if(StrUtil.isNotEmpty(metadata.title)){
  603. musicName = metadata.title
  604. }else{
  605. //自动解析像这样的获取不到元数据的 周杰伦-七里香.mp3文件
  606. console.log(`onecold musicName为空:${file.name}`);
  607. const musicData = parseMusicFileName(file.name);
  608. if (musicData.isValid) {
  609. // console.log(`onecold 艺术家:${musicData.artist}`); // 输出:周杰伦
  610. // console.log(`onecold 歌曲名:${musicData.title}`); // 输出:七里香
  611. musicName = musicData.title
  612. if(artist==''||artist==undefined)
  613. artist = musicData.artist
  614. } else {
  615. musicName = file.name
  616. // console.log("onecold 文件名格式不符合要求");
  617. }
  618. }
  619. if(StrUtil.isNotEmpty(metadata.artist)){
  620. artist = metadata.artist
  621. }
  622. if(artist==undefined)
  623. artist = ''
  624. if(StrUtil.isNotEmpty(metadata.album)){
  625. album = metadata.album
  626. }else{
  627. album = ''
  628. }
  629. if(StrUtil.isNotEmpty(metadata.duration)){
  630. if(metadata.duration)
  631. duration = convertSecondsToTime(metadata.duration.toString())
  632. }
  633. if(StrUtil.isNotEmpty(metadata.mimeType)){
  634. mimeType = metadata.mimeType
  635. }
  636. if(StrUtil.isNotEmpty(metadata.trackCount)){
  637. trackCount = metadata.trackCount
  638. }
  639. if(StrUtil.isNotEmpty(metadata.sampleRate)){
  640. sampleRate = metadata.sampleRate
  641. }
  642. let name = await MD5.digestSync(uri)
  643. if(isLoadPixelMap){
  644. // 获取专辑封面(promise模式)
  645. // pixelMap = await avMetadataExtractor.fetchAlbumCover();
  646. // // 释放资源(promise模式)
  647. // await avMetadataExtractor.release();
  648. pixelMap = await fetchAlbumCover(avMetadataExtractor)
  649. // console.info('onecold release success. name= '+musicName);
  650. if(pixelMap!==undefined&&pixelMap!==null){
  651. // console.info('onecold pixelMap is not empty= '+musicName);
  652. imagePath = await ImageUtil.savePixelMap(pixelMap,context.filesDir,name)
  653. imagePath = fileUri.getUriFromPath(imagePath)
  654. }else{
  655. // console.info('onecold pixelMap is empty= '+musicName);
  656. imagePath = ''
  657. // if(StrUtil.isNotEmpty(artist))
  658. // imagePath = await NetAxiosUtil.getLyricCover(musicName,artist)
  659. }
  660. }else{
  661. imagePath = context.filesDir + FileUtil.separator + name
  662. imagePath = fileUri.getUriFromPath(imagePath)
  663. }
  664. console.info('onecold release success. imagePath= '+imagePath);
  665. } catch (error) {
  666. console.error('Error during metadata extraction:', error);
  667. }
  668. } else {
  669. console.warn('AVMetadataExtractor capability is not supported.');
  670. }
  671. if(musicName==undefined)
  672. musicName = file.name
  673. item = new VideoItem(musicName,uri ,uri,type,videoSize,addTime,undefined,fileSize,
  674. imagePath,artist,album,file.name)
  675. item.duration = duration+'';
  676. item.mimeType = mimeType;
  677. item.trackCount = trackCount;
  678. item.sampleRate = sampleRate;
  679. item.isFav = 0;
  680. item.playCount = 0;
  681. item.pyStr = pinyin4js.getShortPinyin(musicName)
  682. // item.lyricContent = await extractLyricsContent(uri)
  683. let metaItem = await parseAudioMetadata(uri)
  684. if(metaItem){
  685. item.lyricContent = metaItem.lyricContent
  686. item.bit_rate = formatBitrateToKbps(metaItem.bit_rate || "0");
  687. item.year = metaItem.year ||'unknown'
  688. item.probe_score = metaItem.probe_score
  689. item.nb_streams = metaItem.nb_streams
  690. item.nb_programs = metaItem.nb_programs
  691. }
  692. })
  693. } catch (error) {
  694. console.error('uriGetAssetsFromFile failed with err: ' + JSON.stringify(error));
  695. }
  696. return item
  697. }
  698. static async readMetaInfoFFmpeg(context:Context,inputPath: string,type:number): Promise<VideoItem> {
  699. return new Promise((resolve, reject) => {
  700. let commands = ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", inputPath];
  701. let outputJson = "";
  702. FFmpeg.execute(commands, {
  703. logCallback: (logLevel: number, logMessage: string) => console.log(`[${logLevel}]${logMessage}`),
  704. outputCallback: (message: string) => {
  705. outputJson += message;
  706. },
  707. }).then(async () => {
  708. try {
  709. const metadata: FFprobeMetadata = JSON.parse(outputJson);
  710. const format = metadata.format;
  711. console.log(`onecold outputJson:${outputJson}`);
  712. let file = fs.openSync(inputPath, fs.OpenMode.READ_ONLY | fs.OpenMode.CREATE)
  713. console.info('readMetaInfoFFmpeg asset file.path: ', file.path);
  714. let videoItem = new VideoItem(file.name,inputPath,inputPath,type,0,'')
  715. await fs.stat(file.fd).then(async (stat: fs.Stat) => {
  716. // 获取音频流的采样率
  717. let sampleRate:string|undefined = '';
  718. let bits_per_raw_sample:string|undefined = '';
  719. let channels:string|undefined = '';
  720. let channel_layout:string|undefined = '';
  721. let start_time:string|undefined = '';
  722. if (metadata.streams && metadata.streams.length > 0) {
  723. // 查找第一个音频流
  724. const audioStream = metadata.streams.find(stream => StrUtil.isNotEmpty(stream.sample_rate));
  725. if (audioStream) {
  726. sampleRate = audioStream.sample_rate;
  727. bits_per_raw_sample = audioStream.bits_per_raw_sample
  728. channel_layout = audioStream.channel_layout
  729. channels = audioStream.channels
  730. start_time = audioStream.start_time
  731. }
  732. }
  733. let videoSize = stat.size
  734. let fileSize = Utility.formatFSize(videoSize)
  735. //按照添加时间
  736. let addTime = Utility.getFormatDateStr(new Date(),'yyyy-MM-dd HH:mm');
  737. // Extract artist and title from tags
  738. const tags = format.tags || {};
  739. let artist = tags.artist ||tags.ARTIST || '';
  740. let title = tags.title ||tags.TITLE || '';
  741. const album = tags.album ||tags.ALBUM|| '';
  742. console.log(`onecold tags.tags:${JSON.stringify(tags)}`);
  743. // console.log(`onecold tags.LYRICS:${tags.LYRICS}`);
  744. // console.log(`onecold tags.lyrics:${tags.lyrics}`);
  745. // console.log(`onecold tags.UNSYNCEDLYRICS:${tags.UNSYNCEDLYRICS}`);
  746. if(StrUtil.isEmpty(title)){
  747. //自动解析像这样的获取不到元数据的 周杰伦-七里香.mp3文件
  748. console.log(`onecold musicName为空:${file.name}`);
  749. const musicData = parseMusicFileName(file.name);
  750. if (musicData.isValid) {
  751. // console.log(`onecold 艺术家:${musicData.artist}`); // 输出:周杰伦
  752. // console.log(`onecold 歌曲名:${musicData.title}`); // 输出:七里香
  753. title = musicData.title
  754. if(artist==''||artist==undefined)
  755. artist = musicData.artist
  756. } else {
  757. title = file.name
  758. // console.log("onecold 文件名格式不符合要求");
  759. }
  760. }
  761. let name: string = title;
  762. if (!name) {
  763. name = getFileNameWithoutExtension(inputPath);
  764. }
  765. let pixelMap:image.PixelMap|undefined|null = undefined
  766. // Create VideoItem
  767. videoItem = new VideoItem(
  768. name,
  769. inputPath, // id can be generated or left empty
  770. inputPath,
  771. type, // assuming it's local
  772. videoSize,
  773. addTime // convert to ISO string
  774. );
  775. // Set additional properties from format metadata
  776. videoItem.artist = artist;
  777. videoItem.album = album;
  778. videoItem.sampleRate = sampleRate
  779. videoItem.pyStr = pinyin4js.getShortPinyin(name)
  780. videoItem.fileName = FileUtil.getFileName(inputPath);
  781. if(format.duration)
  782. videoItem.duration = formatDuration(format.duration.toString()||'00:00')
  783. videoItem.size = fileSize;
  784. videoItem.bit_rate =formatBitrateToKbps(format.bit_rate || "0");
  785. videoItem.probe_score = format.probe_score;
  786. videoItem.nb_streams = format.nb_streams;
  787. videoItem.nb_programs = format.nb_programs;
  788. videoItem.year = tags.TYER || tags.date ||tags.DATE|| ''; // try different tag names for year
  789. videoItem.lyricContent = tags.LYRICS || tags.lyrics || tags.USLT || tags.UNSYNCEDLYRICS || '';
  790. //console.info('readMetaInfoFFmpeg videoItem.lyricContent: ', videoItem.lyricContent);
  791. // 如果标准字段没有歌词,则尝试解析 `lyrics-` 字段
  792. // tags 必须是 Record<string, string | undefined>(或 any)
  793. // 如果还是没有歌词内容,尝试查找自定义的lyrics-开头的属性(电脑版音乐标签内嵌歌词就是lyrics-XXX)
  794. if(StrUtil.isEmpty( videoItem.lyricContent)){
  795. const tagsRecord = tags as Record<string, string>;
  796. const possibleKeys = Object.keys(tagsRecord);
  797. for (let i = 0; i < possibleKeys.length; i++) {
  798. const key = possibleKeys[i];
  799. if (key && key.toLowerCase().startsWith('lyrics-')) {
  800. //console.info('readMetaInfoFFmpeg videoItem.key: ', key);
  801. // 通过转换后的 Record 类型安全访问属性
  802. videoItem.lyricContent = tagsRecord[key];
  803. //console.info('readMetaInfoFFmpeg videoItem.lyricContent2: ', videoItem.lyricContent);
  804. if (videoItem.lyricContent) {
  805. break;
  806. }
  807. }
  808. }
  809. }
  810. videoItem.genre = tags.genre||tags.GENRE|| '';
  811. videoItem.track = tags.track||tags.TRACK|| '';
  812. videoItem.ALBUMARTIST = tags.ALBUMARTIST||tags.album_artist||tags.albumartist||tags.TPE2|| '';
  813. videoItem.COMPOSER = tags.COMPOSER||tags.composer|| '';
  814. videoItem.LYRICIST = tags.LYRICIST||tags.lyricist||tags.TEXT ||'';
  815. videoItem.COMMENT = tags.COMMENT||tags.comment||tags.COMM|| '';
  816. videoItem.disc = tags.disc|| '';
  817. videoItem.bits_per_raw_sample = bits_per_raw_sample ||'1'
  818. videoItem.channel_layout = channel_layout || ''
  819. videoItem.channels = channels ||'0'
  820. videoItem.start_time = start_time || '00:00'
  821. videoItem.mimeType = format.format_name
  822. // 检查是否有封面图片流
  823. const hasCover = metadata.streams.some(stream =>
  824. stream.disposition?.attached_pic === 1
  825. );
  826. console.info('readMetaInfoFFmpeg asset hasCover: ', hasCover);
  827. let md5Name = await MD5.digestSync(inputPath)
  828. let imagePath = `${context.filesDir}${FileUtil.separator}${md5Name}.jpg`;
  829. console.info('readMetaInfoFFmpeg asset imagePath: ', imagePath);
  830. // 如果有封面图片,则提取
  831. try {
  832. if (hasCover) {
  833. //提取封面
  834. let isSuccess:boolean= await getFFmpegCover(inputPath, imagePath);
  835. if(isSuccess){
  836. imagePath = fileUri.getUriFromPath(imagePath)
  837. }else{
  838. imagePath = ''
  839. }
  840. videoItem.pixelMapPath = imagePath;
  841. }else if(Utility.isVideoByExtension(inputPath)){
  842. pixelMap = await Utility.getFetchFrameByTime(inputPath)
  843. if(pixelMap!==undefined&&pixelMap!==null){
  844. imagePath = await ImageUtil.savePixelMap(pixelMap,context.filesDir,md5Name)
  845. imagePath = fileUri.getUriFromPath(imagePath)
  846. }else{
  847. imagePath = ''
  848. }
  849. imagePath = fileUri.getUriFromPath(imagePath)
  850. videoItem.pixelMapPath = imagePath;
  851. }
  852. } catch (error) {
  853. console.warn(' 提取封面图片失败:', error.message);
  854. }
  855. if(sampleRate&&format.bit_rate){
  856. videoItem.md5Str = determineAudioQuality( videoItem.mimeType,Number(format.bit_rate),Number(sampleRate))
  857. }
  858. console.info('Successfully parsed metadata:', videoItem);
  859. resolve(videoItem);
  860. })
  861. } catch (error) {
  862. console.error('Failed to parse metadata:', error);
  863. reject(new Error('Failed to parse metadata: ' + error.message));
  864. }
  865. }).catch((error: Error) => {
  866. console.error(`Execution failed with error: ${error.message}`);
  867. reject(error);
  868. });
  869. });
  870. }
  871. private completionNum(num: number): string | number {
  872. if (num < 10) {
  873. return '0' + num;
  874. } else {
  875. return num;
  876. }
  877. }
  878. //根据字节获取大小
  879. static formatFSize(bytes:number):string {
  880. const units = ['Bytes', 'K', 'M', 'G'];
  881. let size = bytes;
  882. let unitIndex = 0;
  883. while (size >= 1024 && unitIndex < units.length - 1) {
  884. size /= 1024;
  885. unitIndex++;
  886. }
  887. // 保留两位小数, 四舍五入
  888. size = Math.round(size * 10) / 10;
  889. return size + units[unitIndex]
  890. }
  891. static gotoMarket(context:common.UIAbilityContext,bundleName:string) {
  892. const want: Want = {
  893. uri: `store://appgallery.huawei.com/app/detail?id=${bundleName}`
  894. };
  895. context.startAbility(want).then(()=>{
  896. //拉起成功
  897. }).catch(()=>{
  898. // 拉起失败
  899. });
  900. }
  901. static async doShare(item:VideoItem,context:common.UIAbilityContext){
  902. // 生成视频封面图
  903. const imagePackerApi: image.ImagePacker = image.createImagePacker();
  904. const buffer: ArrayBuffer = await (imagePackerApi.packing(await Utility.getFetchFrameByTime(item.filePath), {
  905. format: 'image/jpeg',
  906. quality: 30
  907. }) as Promise<ArrayBuffer>);
  908. // 构造ShareData,需配置一条有效数据信息
  909. let shareData: systemShare.SharedData = new systemShare.SharedData({
  910. utd: uniformTypeDescriptor.UniformDataType.MEDIA,
  911. uri: fileUri.getUriFromPath(item.filePath),
  912. title: item.name, // 不传title字段时,显示视频文件名
  913. // description: '好听的音乐', // 不传description字段时,显示视频大小
  914. thumbnail: new Uint8Array(buffer), // 优先使用传递的缩略图做预览 不传则默认使用视频第一帧画面做预览图
  915. });
  916. // 进行分享面板显示
  917. let controller: systemShare.ShareController = new systemShare.ShareController(shareData);
  918. // let context = getContext(this) as common.UIAbilityContext;
  919. controller.show(context, {
  920. selectionMode: systemShare.SelectionMode.SINGLE,
  921. previewMode: systemShare.SharePreviewMode.DETAIL,
  922. }).then(() => {
  923. console.info('ShareController show success.');
  924. }).catch((error: BusinessError) => {
  925. console.error(`ShareController show error. code: ${error.code}, message: ${error.message}`);
  926. });
  927. }
  928. //分享索引index的视频
  929. static async doShareMusic(item:VideoItem,context:common.UIAbilityContext){
  930. // 构造ShareData,需配置一条有效数据信息
  931. let shareData: systemShare.SharedData = new systemShare.SharedData({
  932. utd: uniformTypeDescriptor.UniformDataType.AUDIO,
  933. uri: fileUri.getUriFromPath(item.filePath),
  934. title: item.name, // 不传title字段时,显示视频文件名
  935. description: '好听的音乐', // 不传description字段时,显示视频大小
  936. });
  937. // 进行分享面板显示
  938. let controller: systemShare.ShareController = new systemShare.ShareController(shareData);
  939. // let context = getContext(this) as common.UIAbilityContext;
  940. controller.show(context, {
  941. selectionMode: systemShare.SelectionMode.SINGLE,
  942. previewMode: systemShare.SharePreviewMode.DETAIL,
  943. }).then(() => {
  944. console.info('ShareController show success.');
  945. }).catch((error: BusinessError) => {
  946. console.error(`ShareController show error. code: ${error.code}, message: ${error.message}`);
  947. });
  948. }
  949. static getNameList(localList:Array<VideoItem>){
  950. let list: Array<string> = [];
  951. for(let i=0;i<localList.length;i++){
  952. if(StrUtil.isNotEmpty(localList[i].name))
  953. list.push(localList[i].name);
  954. }
  955. return list
  956. }
  957. //获取列表有封面的值
  958. static getFirstCoverFromList(localList:Array<VideoItem>):string{
  959. let list: Array<string> = [];
  960. for(let i=0;i<localList.length;i++){
  961. let pix = localList[i].pixelMapPath
  962. if(pix){
  963. return pix
  964. }
  965. }
  966. return ''
  967. }
  968. //根据type获取对应的播放列表(CommonConstants.TYPE_LOCAL:本地,CommonConstants.TYPE_Dir:私密视频)
  969. static getGlobalNameList(localList:Array<VideoItem>,type:number){
  970. let list: Array<string> = [];
  971. for(let i=0;i<localList.length;i++){
  972. if(localList[i].type === type){
  973. list.push(localList[i].name);
  974. }
  975. }
  976. return list
  977. }
  978. //根据type获取对应的播放列表(CommonConstants.TYPE_LOCAL:本地,CommonConstants.TYPE_LOCK:私密视频)
  979. static getGlobalList(localList:Array<VideoItem>,type:number){
  980. let list: Array<VideoItem> = [];
  981. for(let i=0;i<localList.length;i++){
  982. if(localList[i].type === type){
  983. list.push(localList[i]);
  984. }
  985. }
  986. return list
  987. }
  988. //根据filePath获取当前索引index
  989. static getCurIndexFromGlobalList(localList:Array<VideoItem>,filePath:string){
  990. let index: number = 0;
  991. for(let i=0;i<localList.length;i++){
  992. if(localList[i].filePath === filePath){
  993. index = i
  994. return index
  995. }
  996. }
  997. return index
  998. }
  999. //新的查询是否收藏的方法
  1000. static getIsFav(favList: Array<VideoItem>,item:VideoItem|undefined){
  1001. if(ArrayUtil.isEmpty(favList)){
  1002. return false
  1003. }
  1004. if(item===undefined){
  1005. return false
  1006. }
  1007. for(let i=0;i<favList.length;i++){
  1008. if(favList[i].filePath === item.filePath&&favList[i].isFav===1){
  1009. return true
  1010. }
  1011. }
  1012. return false
  1013. }
  1014. static getIsFac(facList: Array<String>,item:VideoItem|undefined){
  1015. if(ArrayUtil.isEmpty(facList)){
  1016. return false
  1017. }
  1018. if(item===undefined){
  1019. return false
  1020. }
  1021. for(let i=0;i<facList.length;i++){
  1022. if(facList[i] === item.name||facList[i]===item.fileName){
  1023. return true
  1024. }
  1025. }
  1026. return false
  1027. }
  1028. static resourceToString(context:Context,resource:Resource){
  1029. if(!context||!resource)
  1030. return ''
  1031. return context.resourceManager.getStringSync(resource).toString()
  1032. }
  1033. //根据type获取对应的播放列表(CommonConstants.TYPE_LOCAL:本地,CommonConstants.TYPE_LOCK:私密视频)
  1034. static getGlobalMusicList(localList:Array<VideoItem>,type:number){
  1035. let list: Array<VideoItem> = [];
  1036. for(let i=0;i<localList.length;i++){
  1037. if(localList[i].type === type){
  1038. list.push(localList[i]);
  1039. }
  1040. }
  1041. return list
  1042. }
  1043. static isHaoFreeTime():boolean{
  1044. if(DateUtil.isWeekend()){
  1045. return true
  1046. }
  1047. let str = DateUtil.getFormatDateStr(new Date(), 'HH')
  1048. let a = Number(str);
  1049. if(isNaN(a))
  1050. return false
  1051. // ToastUtil.showToast('a='+a)
  1052. if (a >= 8 && a <13) {//白天
  1053. return false;
  1054. }
  1055. if (a >= 13 && a <20) {//白天
  1056. return false;
  1057. }
  1058. if (a >= 0 && a < 8) {//凌晨
  1059. return true;
  1060. }
  1061. if (a >= 20 && a <= 24) {//晚上
  1062. return true;
  1063. }
  1064. return false
  1065. }
  1066. static getMusisBg():Resource {
  1067. let index = RandomUtil.getRandomNumber(0,9)
  1068. LogUtil.info('getMusisBg index = '+index)
  1069. return CommonConstants.musicBgList[index]
  1070. }
  1071. static getMusisBg2(index:number):Resource {
  1072. const adjustedIndex = index % 10;
  1073. LogUtil.info('getMusisBg adjustedIndex = '+adjustedIndex)
  1074. return CommonConstants.musicBgList[adjustedIndex]
  1075. }
  1076. static getParentDirectory(filePath: string): string {
  1077. // 使用正则表达式匹配路径分隔符(支持 Unix 和 Windows)
  1078. const lastSlashIndex = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\'));
  1079. if (lastSlashIndex === -1) {
  1080. return '';
  1081. }
  1082. return filePath.substring(0, lastSlashIndex);
  1083. }
  1084. // 开启沉浸式显示模式
  1085. static async enableFullScreen() {
  1086. const ctx = getContext()
  1087. const win = await window.getLastWindow(ctx)
  1088. win.setWindowLayoutFullScreen(true)
  1089. const top = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM)
  1090. AppStorage.setOrCreate('topHeight', px2vp(top.topRect.height))
  1091. AppStorage.setOrCreate('bottomHeight', px2vp(top.bottomRect.height))
  1092. }
  1093. // 关闭沉浸式显示模式
  1094. static async disableFullScreen() {
  1095. const ctx = getContext()
  1096. const win = await window.getLastWindow(ctx)
  1097. win.setWindowLayoutFullScreen(false)
  1098. AppStorage.setOrCreate('topHeight', 0)
  1099. AppStorage.setOrCreate('bottomHeight', 0)
  1100. }
  1101. // 设置状态栏文字颜色为白色
  1102. static async setStatusBarLight() {
  1103. const ctx = getContext()
  1104. const win = await window.getLastWindow(ctx)
  1105. win.setWindowSystemBarProperties({
  1106. statusBarContentColor: '#ffffff'
  1107. })
  1108. }
  1109. // 设置状态栏文字颜色为黑色
  1110. static async setStatusBarDark() {
  1111. const ctx = getContext()
  1112. const win = await window.getLastWindow(ctx)
  1113. win.setWindowSystemBarProperties({
  1114. statusBarContentColor: '#000000'
  1115. })
  1116. }
  1117. // 优化点:完全基于Promise链的异步处理
  1118. static async getAppName(context: Context): Promise<string> {
  1119. try {
  1120. // 1. 同步化BundleInfo获取
  1121. const bundleInfo = await bundleManager.getBundleInfoForSelf(
  1122. bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION
  1123. );
  1124. // 2. 安全获取labelId(新增空值校验)
  1125. const labelId = bundleInfo.appInfo?.labelId;
  1126. if (!labelId || labelId <= 0) {
  1127. throw new Error("Invalid labelId: " + labelId);
  1128. }
  1129. // 3. 异步资源解析(替换危险的getStringSync)
  1130. return await context.resourceManager.getStringValue(labelId);
  1131. } catch (err) {
  1132. console.error(`[${new Date().toISOString()}] AppName Error: CODE=${err.code}, MSG=${err.message}`);
  1133. // 4. 多级降级策略
  1134. return AppUtil.getBundleName() // 最终兜底
  1135. }
  1136. }
  1137. //按名称升序
  1138. static doSortListAscending( list:Array<VideoItem>){
  1139. let options: Intl.CollatorOptions = {
  1140. localeMatcher: "lookup",
  1141. usage: "sort",
  1142. sensitivity: "case" // 区分大小写
  1143. };
  1144. const collator = new Intl.Collator("zh-CN", options);
  1145. list.sort((a, b) => {
  1146. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1147. if (typeOrder !== 0) {
  1148. return typeOrder;
  1149. }
  1150. const partsA = extractParts(a.name);
  1151. const partsB = extractParts(b.name);
  1152. const nonNumericComparison = collator.compare(partsA.nonNumeric, partsB.nonNumeric);
  1153. if (nonNumericComparison !== 0) {
  1154. return nonNumericComparison;
  1155. }
  1156. return partsA.numeric - partsB.numeric;
  1157. });
  1158. }
  1159. //按名称降序
  1160. static doSortListDescending(list:Array<VideoItem>){
  1161. const options: Intl.CollatorOptions = {
  1162. localeMatcher: "lookup",
  1163. usage: "sort",
  1164. sensitivity: "case" // 区分大小写
  1165. };
  1166. const collator = new Intl.Collator("zh-CN", options);
  1167. list.sort((a, b) => {
  1168. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  1169. if (typeOrder !== 0) {
  1170. return typeOrder;
  1171. }
  1172. const partsA = extractParts(a.name);
  1173. const partsB = extractParts(b.name);
  1174. const nonNumericComparison = collator.compare(partsB.nonNumeric, partsA.nonNumeric);
  1175. if (nonNumericComparison !== 0) {
  1176. return nonNumericComparison;
  1177. }
  1178. return partsB.numeric - partsA.numeric;
  1179. });
  1180. }
  1181. /**
  1182. * 读取本地会员到期时间(解密.vv文件)
  1183. * @returns
  1184. */
  1185. static async getLocalNobleExpireDate(): Promise<string> {
  1186. // return "2025-08-08 12:00";
  1187. try {
  1188. const documentViewPicker = new picker.DocumentViewPicker()
  1189. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  1190. let download_path = new fileUri.FileUri(documentSaveResult[0]).path + '/'
  1191. let filePath = download_path + STR_LOCK_VIDEO+ '/' + VIP_FILEPATH
  1192. let expireDate = Utility.readDataFromFile(filePath)
  1193. return expireDate;
  1194. } catch (e) {
  1195. return '';
  1196. }
  1197. }
  1198. static readDataFromFile(filePath: string) {
  1199. if(!FileUtil.accessSync(filePath)){
  1200. return ''
  1201. }
  1202. let readTextOptions: ReadTextOptions = {
  1203. offset: 0,
  1204. length: 0,
  1205. encoding: 'utf-8'
  1206. };
  1207. let stat = fileIo.statSync(filePath);
  1208. readTextOptions.length = stat.size;
  1209. let str = fileIo.readTextSync(filePath, readTextOptions);
  1210. const parsedData:VipData = JSON.parse(str) as VipData;
  1211. // LogUtil.info('onecold parsedData.expireDate = ' + parsedData.expireDate)
  1212. let result = Base64Util.decodeSync( parsedData.expireDate)
  1213. // LogUtil.info('onecold 解密的result = ' +StrUtil.unit8ArrayToStr(result))
  1214. return StrUtil.unit8ArrayToStr(result);
  1215. }
  1216. }
  1217. interface PathStat {
  1218. path: string;
  1219. isDirectory: boolean;
  1220. }
  1221. async function isDirectory(filePath: string): Promise<boolean> {
  1222. try {
  1223. const stat = await fs.stat(filePath);
  1224. return stat.isDirectory();
  1225. } catch (error) {
  1226. console.error('Error getting file stat:', error);
  1227. return false;
  1228. }
  1229. }
  1230. //排序模式参数
  1231. interface VideoNameParts {
  1232. nonNumeric: string;
  1233. numeric: number;
  1234. suffix:string;
  1235. }
  1236. function extractParts(name: string): VideoNameParts {
  1237. // 更完善的正则表达式,处理各种情况
  1238. // 匹配:非数字前缀 + 数字部分 + 可选的剩余部分
  1239. const match = name.match(/^(\D*)(\d+)(.*)$/);
  1240. if (match) {
  1241. return {
  1242. nonNumeric: match[1] || '', // 非数字前缀
  1243. numeric: parseInt(match[2], 10), // 数字部分
  1244. suffix: match[3] || '' // 剩余部分(可能包含扩展名等)
  1245. };
  1246. }
  1247. // 如果没有找到数字模式,将整个名称作为非数字部分
  1248. return {
  1249. nonNumeric: name,
  1250. numeric: 0,
  1251. suffix: ''
  1252. };
  1253. }
  1254. function getInstallTime(): number | null {
  1255. // 从本地存储中获取安装时间
  1256. return PreferencesUtil.getNumberSync('installTime')
  1257. }
  1258. function setInstallTime(time: number) {
  1259. // 将安装时间存储到本地存储中
  1260. PreferencesUtil.putSync('installTime',time)
  1261. }
  1262. function fetchAlbumCover(avMetadataExtractor: media.AVMetadataExtractor): Promise<image.PixelMap | null> {
  1263. return new Promise((resolve, reject) => {
  1264. avMetadataExtractor.fetchAlbumCover((error: BusinessError, pixelMap: image.PixelMap) => {
  1265. if (error) {
  1266. console.error(`Failed to fetch AlbumCover, error = ${JSON.stringify(error)}`);
  1267. resolve(null);
  1268. } else {
  1269. resolve(pixelMap);
  1270. }
  1271. avMetadataExtractor.release();
  1272. });
  1273. });
  1274. }
  1275. //排序类型
  1276. function getTypeOrder(type: number) {
  1277. switch (type) {
  1278. case CommonConstants.TYPE_IS_DIR:
  1279. return 1; // First
  1280. case CommonConstants.TYPE_IS_CSJAD:
  1281. return 2; // Middle
  1282. case CommonConstants.TYPE_LOCAL:
  1283. return 3; // Last
  1284. default:
  1285. return 4; // Unknown types, if any, go last
  1286. }
  1287. }
  1288. function convertSecondsToTime(secondsStr: string): string {
  1289. if (!secondsStr || isNaN(Number(secondsStr))) {
  1290. return "00:00";
  1291. }
  1292. let seconds = parseInt(secondsStr, 10);
  1293. seconds = Math.floor(seconds / 1000);
  1294. const hours = Math.floor(seconds / 3600);
  1295. const minutes = Math.floor((seconds % 3600) / 60);
  1296. const secs = seconds % 60;
  1297. const formatNumber = (num: number) => num.toString().padStart(2, '0');
  1298. if (hours > 0) {
  1299. return `${formatNumber(hours)}:${formatNumber(minutes)}:${formatNumber(secs)}`;
  1300. } else {
  1301. return `${formatNumber(minutes)}:${formatNumber(secs)}`;
  1302. }
  1303. }
  1304. /**
  1305. * 秒数 → 智能时间格式(自动选择 MM:SS 或 HH:MM:SS)
  1306. * @param seconds 秒数字符串(如 "283.524351" 或 "3675")
  1307. * @param forceHHMMSS 强制使用 HH:MM:SS 格式(默认自动判断)
  1308. * @returns 格式化后的时间字符串
  1309. */
  1310. function formatDuration(seconds: string, forceHHMMSS: boolean = false): string {
  1311. // 1. 校验输入
  1312. const secNum = parseFloat(seconds);
  1313. if (isNaN(secNum) || secNum < 0) return forceHHMMSS ? "00:00:00" : "00:00";
  1314. // 2. 计算时间分量
  1315. const totalSec = Math.floor(secNum);
  1316. const hours = Math.floor(totalSec / 3600);
  1317. const mins = Math.floor((totalSec % 3600) / 60);
  1318. const secs = totalSec % 60;
  1319. // 3. 格式化输出
  1320. const pad = (n: number) => n.toString().padStart(2, '0');
  1321. return forceHHMMSS || hours > 0
  1322. ? `${pad(hours)}:${pad(mins)}:${pad(secs)}` // HH:MM:SS
  1323. : `${pad(mins)}:${pad(secs)}`; // MM:SS
  1324. }
  1325. /**
  1326. * 定义解析结果的数据结构
  1327. */
  1328. class MusicInfo {
  1329. artist: string = ""; // 艺术家名称
  1330. title: string = ""; // 歌曲名称
  1331. isValid: boolean = false; // 格式是否有效
  1332. }
  1333. /**
  1334. * 精简版常见中文姓氏(音乐场景优化版)
  1335. */
  1336. const COMMON_CHINESE_SURNAMES = [
  1337. // 超常见姓氏(覆盖约80%人口)
  1338. '李','王','张','刘','陈','杨','黄','赵','吴','周',
  1339. '徐','孙','马','朱','胡','林','郭','何','高','罗',
  1340. '郑','梁','谢','宋','唐','许','韩','邓','曹','彭',
  1341. '曾','萧','田','董','潘','袁','于','蔡','余','杜',
  1342. // 音乐行业常见姓氏(歌手高频姓)
  1343. '汪','苏','薛','谭','华','金','魏','陶','姜','窦',
  1344. '章','毛','易','方','宋','任','沈','贾','江','孔',
  1345. // 组合/乐队常见字
  1346. '羽','泉','信','乐','花','飞','龙','风','云','草'
  1347. ];
  1348. /**
  1349. * 歌手特征关键词(优化版)
  1350. */
  1351. const ARTIST_KEYWORDS = [
  1352. // 中文特征
  1353. '乐队','组合','乐团','和','&','合唱',' featuring',
  1354. // 英文特征
  1355. 'feat','ft','with','vs','presents','presents',
  1356. // 符号特征
  1357. '×','X','※','◆','♫'
  1358. ];
  1359. /**
  1360. * 智能解析音乐文件名(支持多种分隔符和格式)
  1361. * @param fileName - 待解析的完整文件名
  1362. * @returns 结构化音乐信息
  1363. */
  1364. /**
  1365. * 智能解析音乐文件名
  1366. */
  1367. function parseMusicFileName(fileName: string): MusicInfo {
  1368. const result: MusicInfo = new MusicInfo();
  1369. if (!fileName) return result;
  1370. // 预处理
  1371. const cleanName: string = fileName.trim();
  1372. const lastDotIndex: number = cleanName.lastIndexOf('.');
  1373. const baseName: string = lastDotIndex > 0 ?
  1374. cleanName.substring(0, lastDotIndex).trim() :
  1375. cleanName;
  1376. // 支持的分隔符(明确定义类型)
  1377. const separators: string[] = ['-', '-', '—', '~', '~'];
  1378. // 寻找分隔位置
  1379. let bestSplitIndex: number = -1;
  1380. for (const sep of separators) {
  1381. const index: number = baseName.lastIndexOf(sep);
  1382. if (index > bestSplitIndex) {
  1383. bestSplitIndex = index;
  1384. }
  1385. }
  1386. // 分割字符串
  1387. if (bestSplitIndex > 0 && bestSplitIndex < baseName.length - 1) {
  1388. let part1: string = baseName.substring(0, bestSplitIndex).trim();
  1389. let part2: string = baseName.substring(bestSplitIndex + 1).trim();
  1390. // 处理前缀序号
  1391. part1 = part1.replace(/^\d+[\s\.\-- —~~]*/, '').trim();
  1392. // 判断歌手部分(明确定义返回类型)
  1393. const identifyArtist = (str: string): boolean => {
  1394. return COMMON_CHINESE_SURNAMES.some((surname: string) =>
  1395. str.startsWith(surname) ||
  1396. new RegExp(`[ ,,、&&]${surname}`).test(str)
  1397. ) || ARTIST_KEYWORDS.some((keyword: string) =>
  1398. str.includes(keyword)
  1399. );
  1400. };
  1401. // 判断歌手位置
  1402. const part1IsArtist: boolean = identifyArtist(part1);
  1403. const part2IsArtist: boolean = identifyArtist(part2);
  1404. if (part1IsArtist && !part2IsArtist) {
  1405. result.artist = part1;
  1406. result.title = part2;
  1407. } else if (part2IsArtist && !part1IsArtist) {
  1408. result.artist = part2;
  1409. result.title = part1;
  1410. } else {
  1411. result.artist = part1.length <= part2.length ? part1 : part2;
  1412. result.title = part1.length <= part2.length ? part2 : part1;
  1413. }
  1414. // 后处理
  1415. result.title = result.title
  1416. .replace(/(?:\(|()[^))]*(?:)|\))/g, '')
  1417. .replace(/\s*[—-]\s*(?:Live|Version|Remix|伴奏).*/i, '')
  1418. .trim();
  1419. // 有效性验证
  1420. result.isValid = result.artist.length > 0 &&
  1421. result.title.length > 0;
  1422. } else {
  1423. result.title = baseName;
  1424. result.isValid = result.title.length > 0;
  1425. }
  1426. return result;
  1427. }
  1428. function getFileNameWithoutExtension(filePath: string): string {
  1429. const fileName = filePath.split('/').pop() || '';
  1430. const lastDotIndex = fileName.lastIndexOf('.');
  1431. return lastDotIndex > 0 ? fileName.substring(0, lastDotIndex) : fileName;
  1432. }
  1433. /**
  1434. * 从音乐文件中提取封面
  1435. * @param inputPath 音乐文件路径
  1436. * @returns Promise<void>
  1437. */
  1438. // async function getFFmpegCover(inputPath: string, outputPath: string) : Promise<boolean>{
  1439. // let commands = ["ffmpeg", "-y","-i", inputPath, "-map", "0:v", "-c:v", "copy", outputPath];
  1440. // FFmpeg.execute(commands, {
  1441. // logCallback: (logLevel: number, logMessage: string) => {
  1442. // console.info(`[FFmpeg LOG] [${logLevel}]${logMessage}`)
  1443. // },
  1444. // progressCallback: (message: string) => {
  1445. // console.info(`[FFmpeg progress]${JSON.stringify(FFProgressMessageParser.parse(message))}`)
  1446. // },
  1447. // })
  1448. // .then(() => {
  1449. // return true
  1450. // console.info("FFmpeg execution succeeded.");
  1451. // })
  1452. // .catch((error: Error) => {
  1453. // return false
  1454. // console.error(`FFmpeg execution failed with error: ${error.message}`);
  1455. // });
  1456. // return ;
  1457. // }
  1458. /**
  1459. * 从音乐文件中提取封面
  1460. * @param inputPath 音乐文件路径
  1461. * @param outputPath 封面输出路径
  1462. * @returns Promise<boolean> 表示操作是否成功
  1463. */
  1464. async function getFFmpegCover(inputPath: string, outputPath: string): Promise<boolean> {
  1465. let commands = ["ffmpeg", "-y","-i", inputPath, "-map", "0:v", "-c:v", "copy", outputPath];
  1466. try {
  1467. await FFmpeg.execute(commands, {
  1468. logCallback: (logLevel: number, logMessage: string) => {
  1469. console.info(`[FFmpeg LOG] [${logLevel}] ${logMessage}`);
  1470. },
  1471. progressCallback: (message: string) => {
  1472. console.info(`[FFmpeg progress] ${JSON.stringify(FFProgressMessageParser.parse(message))}`);
  1473. },
  1474. });
  1475. console.info("FFmpeg execution succeeded.");
  1476. return true;
  1477. } catch (error) {
  1478. console.error(`FFmpeg execution failed with error: ${error instanceof Error ? error.message : String(error)}`);
  1479. return false;
  1480. }
  1481. }
  1482. /**
  1483. * 从视频文件中提取封面 提前视频第5帧的封面
  1484. * @param inputPath 文件路径
  1485. * @returns Promise<void>
  1486. */
  1487. async function getVideoFFmpegCover(inputPath: string, outputPath: string) {
  1488. // 更可靠的命令,专门提取视频第一帧作为封面
  1489. const commands = [
  1490. "ffmpeg",
  1491. "-y", // 覆盖输出文件(如果存在)
  1492. "-i", inputPath, // 输入文件
  1493. "-ss", "00:00:00", // 定位到开始位置
  1494. "-vframes", "1", // 只提取1帧
  1495. "-q:v", "2", // 高质量JPEG(1-31,2是最高质量)
  1496. "-f", "image2", // 强制输出为图像格式
  1497. outputPath
  1498. ];
  1499. FFmpeg.execute(commands, {
  1500. logCallback: (logLevel: number, logMessage: string) => {
  1501. console.info(`[FFmpegX LOG] [${logLevel}]${logMessage}`)
  1502. },
  1503. progressCallback: (message: string) => {
  1504. console.info(`[FFmpegX progress]${JSON.stringify(FFProgressMessageParser.parse(message))}`)
  1505. },
  1506. })
  1507. .then(() => {
  1508. })
  1509. .catch((error: Error) => {
  1510. console.error(`FFmpegX execution failed with error: ${error.message}`);
  1511. });
  1512. }
  1513. /**
  1514. * 从音乐文件中提取歌词内容
  1515. * @param inputPath 音乐文件路径
  1516. * @returns Promise<string> 直接返回歌词内容,若无歌词则返回空字符串
  1517. */
  1518. async function extractLyricsContent(inputPath: string): Promise<string> {
  1519. return new Promise(async (resolve, reject) => {
  1520. try {
  1521. // 1. 使用ffprobe获取元数据
  1522. const commands = [
  1523. 'ffprobe',
  1524. '-v', 'quiet',
  1525. '-print_format', 'json',
  1526. '-show_format',
  1527. inputPath
  1528. ];
  1529. let outputJson = '';
  1530. await FFmpeg.execute(commands, {
  1531. outputCallback: (message: string) => outputJson += message,
  1532. });
  1533. // 2. 解析歌词标签
  1534. const metadata:FFprobeMetadata = JSON.parse(outputJson);
  1535. const tags = metadata.format?.tags || {};
  1536. // 3. 从常见标签中查找歌词(优先级顺序)
  1537. const lyricContent =
  1538. tags.LYRICS || // 标准标签
  1539. tags.lyrics || // 小写变体
  1540. tags.USLT || // ID3v2标签
  1541. tags.UNSYNCEDLYRICS ||
  1542. '';
  1543. resolve(lyricContent.trim());
  1544. } catch (error) {
  1545. reject(`解析失败: ${error instanceof Error ? error.message : String(error)}`);
  1546. }
  1547. });
  1548. }
  1549. /**
  1550. * 解析音乐文件元数据(包含歌词和其他关键字段)
  1551. * @param inputPath 文件路径
  1552. * @returns Promise<VideoItem> 包含完整元数据的对象
  1553. */
  1554. async function parseAudioMetadata(inputPath: string): Promise<VideoItem> {
  1555. return new Promise(async (resolve, reject) => {
  1556. try {
  1557. // 1. 执行FFprobe命令
  1558. const commands: string[] = [
  1559. 'ffprobe',
  1560. '-v', 'quiet',
  1561. '-print_format', 'json',
  1562. '-show_format',
  1563. '-show_streams',
  1564. inputPath
  1565. ];
  1566. let outputJson = '';
  1567. await FFmpeg.execute(commands, {
  1568. outputCallback: (message: string) => outputJson += message,
  1569. });
  1570. // 2. 解析元数据
  1571. const metadata = JSON.parse(outputJson) as FFprobeMetadata;
  1572. const format:FFprobeFormat = metadata.format ;
  1573. const tags = format.tags||{} ;
  1574. // 3. 构建VideoItem基础信息
  1575. const videoItem = new VideoItem(
  1576. tags.title || getFileNameWithoutExtension(inputPath),
  1577. inputPath, // id
  1578. inputPath,
  1579. CommonConstants.TYPE_LOCAL,
  1580. 0,
  1581. new Date().toISOString() // 使用当前时间作为默认创建时间
  1582. );
  1583. // 4. 设置关键字段
  1584. videoItem.bit_rate = format.bit_rate || '';
  1585. videoItem.probe_score = format.probe_score || 0;
  1586. videoItem.year = tags.TYER || tags.date || '';
  1587. videoItem.lyricContent =
  1588. tags.LYRICS ??
  1589. tags.lyrics ??
  1590. tags.USLT ??
  1591. tags.UNSYNCEDLYRICS ??
  1592. '';
  1593. // 5. 设置其他可选字段
  1594. videoItem.artist = tags.artist || '';
  1595. videoItem.album = tags.album || '';
  1596. videoItem.duration = format.duration || '';
  1597. videoItem.nb_streams = format.nb_streams;
  1598. videoItem.nb_programs = format.nb_programs;
  1599. resolve(videoItem);
  1600. } catch (error) {
  1601. reject(new Error(`元数据解析失败: ${error instanceof Error ? error.message : String(error)}`));
  1602. }
  1603. });
  1604. }
  1605. /**
  1606. * 将比特率(bps)转换为 kbps 并格式化
  1607. * @param bitRate 比特率字符串(如 "5644802")
  1608. * @param decimalPlaces 保留小数位数(默认0)
  1609. * @returns 格式化后的 kbps 字符串(如 "5644 kbps")
  1610. */
  1611. function formatBitrateToKbps(bitRate: string, decimalPlaces: number = 0): string {
  1612. // 1. 转换为数字
  1613. const bitsPerSecond = parseInt(bitRate);
  1614. if (isNaN(bitsPerSecond) || bitsPerSecond < 0) return "0 kbps";
  1615. // 2. 计算 kbps(1 kbps = 1000 bps)
  1616. const kbps = bitsPerSecond / 1000;
  1617. // 3. 格式化输出
  1618. return `${kbps.toFixed(decimalPlaces)} kbps`;
  1619. }
  1620. // 定义音质等级
  1621. export enum AudioQuality {
  1622. LQ = "LQ", // 低音质
  1623. HQ = "HQ", // 高音质
  1624. SQ = "SQ", // 无损
  1625. HIRES = "Hi-Res", // 高解析度
  1626. HR = "HR" // 高解析度
  1627. }
  1628. // 明确定义支持的音频格式类型
  1629. interface SupportedFormats {
  1630. LOSSY: Set<string>;
  1631. LOSSLESS: Set<string>;
  1632. }
  1633. // 声明并初始化支持的音频格式(符合类型定义)
  1634. const SUPPORTED_FORMATS: SupportedFormats = {
  1635. LOSSY: new Set(['mp3', 'aac', 'ogg', 'opus', 'wma']),
  1636. LOSSLESS: new Set(['flac', 'alac', 'ape', 'wav', 'aiff', 'dsf','aif'])
  1637. };
  1638. /**
  1639. * 根据音频参数判断音质等级
  1640. * @param format 编码格式(字符串,不区分大小写,如"MP3"或"flac")
  1641. * @param bitrate 比特率(单位:bps,如320kbps需传入320000)
  1642. * @param sampleRate 采样率(单位:Hz,如44.1kHz需传入44100)
  1643. * @param bitDepth 位深(单位:bit,默认16bit,Hi-Res需≥24bit)
  1644. * @returns AudioQuality 音质等级
  1645. */
  1646. function determineAudioQuality(
  1647. format: string,
  1648. bitrate: number,
  1649. sampleRate: number,
  1650. ): AudioQuality {
  1651. // 统一转为小写便于比较
  1652. const normalizedFormat = format.toLowerCase();
  1653. // --------------- 第一步:判断是否无损/Hi-Res ---------------
  1654. const isLossless = SUPPORTED_FORMATS.LOSSLESS.has(normalizedFormat);
  1655. if (isLossless) {
  1656. // Hi-Res标准:采样率≥96kHz且位深≥24bit
  1657. if (sampleRate >= 48000 ) {
  1658. return AudioQuality.HIRES;
  1659. }
  1660. // CD级无损标准:采样率≥44.1kHz且位深≥16bit
  1661. if (sampleRate >= 44100) {
  1662. return AudioQuality.SQ;
  1663. }
  1664. }
  1665. // --------------- 第二步:有损音质判断 ---------------
  1666. // 高音质标准:比特率≥256kbps且采样率≥44.1kHz
  1667. if (bitrate >= 256000 && sampleRate >= 44100) {
  1668. return AudioQuality.HQ;
  1669. }
  1670. // 其余情况为低音质
  1671. else {
  1672. return AudioQuality.LQ;
  1673. }
  1674. }
  1675. function getFileFormatByPath(filePath: string): string {
  1676. // 检查文件路径是否有效
  1677. if (!filePath || filePath.length === 0) {
  1678. console.error(' 文件路径不能为空');
  1679. return '';
  1680. }
  1681. // 获取最后一个点号的位置
  1682. const lastDotIndex = filePath.lastIndexOf('.');
  1683. // 如果没有点号或者点号在最后一位,返回空字符串
  1684. if (lastDotIndex === -1 || lastDotIndex === filePath.length - 1) {
  1685. return '';
  1686. }
  1687. // 返回点号后的部分(转换为小写)
  1688. return filePath.substring(lastDotIndex + 1).toLowerCase();
  1689. }