import { BusinessError, pasteboard } from '@kit.BasicServicesKit'; import { AppUtil, ArrayUtil, Base64Util, DateUtil, FileUtil, ImageUtil, LogUtil, MD5, PreferencesUtil, RandomUtil, StrUtil } from '@pura/harmony-utils'; import { media } from '@kit.MediaKit'; import fs, { ReadTextOptions } from '@ohos.file.fs'; import { image } from '@kit.ImageKit'; import fileIo from '@ohos.file.fs'; import { VideoItem } from '../../viewmodel/VideoItem'; import { photoAccessHelper } from '@kit.MediaLibraryKit'; import { dataSharePredicates, uniformTypeDescriptor } from '@kit.ArkData'; import { systemShare } from '@kit.ShareKit'; import { fileUri, picker } from '@kit.CoreFileKit'; import { common, UIAbility, Want } from '@kit.AbilityKit'; import { CommonConstants } from '../constants/CommonConstants'; import { window } from '@kit.ArkUI'; import { bundleManager } from '@kit.AbilityKit' import { pinyin4js } from '@ohos/pinyin4js'; import { VipData } from '../../viewmodel/VipData'; import { LocalMusic } from '../../view/LocalMusic'; import { VipPage } from '../../pages/VipPage'; import { FFmpeg, FFProgressMessageParser } from '@sj/ffmpeg'; interface FFMpegTags { album?: string; ALBUM?: string; artist?: string; ARTIST?: string; TITLE?: string; title?: string; track?: string; TRACK?: string; TYER?: string; year?: string; genre?:string; GENRE?:string; date?: string; DATE?: string; LYRICS?: string; lyrics?: string; // 小写变体 USLT?: string; // ID3v2同步歌词 UNSYNCEDLYRICS?: string; // ID3v2非同步歌词 // Add any other tag properties you expect } interface FFprobeFormat { filename: string; nb_streams: number; nb_programs: number; format_name: string; format_long_name: string; duration: string; size: string; bit_rate: string; probe_score: number; tags?: FFMpegTags; } interface FFprobeStream { // Define stream properties as needed codec_type?: string; // 流类型,如"audio"、"video" sample_rate?: string; // 采样率 bit_rate?: string; // 比特率 disposition?: StreamDisposition; // 添加disposition属性 } interface StreamDisposition { default?: number; dub?: number; original?: number; comment?: number; lyrics?: number; karaoke?: number; forced?: number; hearing_impaired?: number; visual_impaired?: number; clean_effects?: number; attached_pic?: number; // 添加封面图片标识 timed_thumbnails?: number; captions?: number; descriptions?: number; metadata?: number; dependent?: number; still_image?: number; } interface FFprobeMetadata { streams: FFprobeStream[]; format: FFprobeFormat; } export class Utility { private constructor() {} static isOpenTime():boolean{ const currentDate = new Date(); const targetDate = new Date(CommonConstants.OPEN_DATE); if (currentDate > targetDate) { return true } return false } static readonly FOREVER_DATE: string = 'forever'; /** * 是否会员(只看线上会员状态) */ static isNoble(): boolean { // 只判断线上会员状态 return PreferencesUtil.getBooleanSync('hasActiveSubscription', false); } static isForever(): boolean { // 判断是不是永久会员 return PreferencesUtil.getBooleanSync('isForever', false); } /** * 旧版客户端判断会员状态 * @returns */ static isNobleForOld():boolean{ if(!Utility.isOpenTime())//提交审核的审核,刚刚开始可以全部是赞助用户。 return true return PreferencesUtil.getBooleanSync('isNoble',false) } /** * setNoble方法废弃,保留兼容但不做任何操作 */ static setNoble(expireDate:string){ let isNoble = false if(StrUtil.isNotEmpty(expireDate)){ if(expireDate===VipPage.FOREVER_DATE){ PreferencesUtil.putSync('isForever',true) isNoble = true }else{ PreferencesUtil.putSync('isForever',false) const currentDate = new Date(); const targetDate = DateUtil.getFormatDate(expireDate) if (currentDate > targetDate) { isNoble = false }else{ isNoble = true } } } PreferencesUtil.putSync('isNoble',isNoble) } /** * 判断用户安装app是否超过2天,超过2天(2800分钟)才展示广告 显示广告 24*60=1440 1440*2=2800 * @param day * @returns */ static isPassInstallTime(day:number):boolean{ //获取当前时间 let currentTime = new Date().getTime(); // 尝试从存储中获取安装时间 let installTime = getInstallTime(); if (installTime===0||installTime === null|| installTime===undefined) { // 如果没有存储安装时间,则存储当前时间为安装时间 setInstallTime(currentTime); return false } else { // 计算时间差(以分钟为单位) const timeDifference = (currentTime - installTime) / (1000 * 60); LogUtil.debug("onecold timeDifference=" + timeDifference) // 如果超过5分钟,显示广告 24*60=1440 1440*2=2800 if (timeDifference > 24*60*day) { return true }else{ return false } } } // 定义一个函数来获取当前的时间段 static getTimePeriod(): string { const now = new Date(); const hours = now.getHours(); if (hours >= 5 && hours < 12) { return "早上好"; } else if (hours >= 12 && hours < 18) { return "下午好"; } else if (hours >= 18 && hours < 22) { return "晚上好"; } else { return "夜深了"; } } static optimizedFormat(speed: number): string { if (speed) { const str = speed.toFixed(2); let end = str.length; while (end > 0 && (str[end - 1] === '0' || str[end - 1] === '.')) { end--; if (str[end] === '.') { break; } } return str.slice(0, end || 1) + 'x'; } else { return '1x' } } static isHaoOpenTime():boolean{ const currentDate = new Date(); const targetDate = new Date('2025-04-20'); if (currentDate < targetDate) { return true } return false } static addDays(date: Date, days: number): Date { const result = new Date(date); result.setDate(result.getDate() + days); return result; } static convertToKHz(sampleRateHz: string|undefined): string { if(StrUtil.isEmpty(sampleRateHz)||sampleRateHz ===undefined) return '0KHz' const sampleRateKHz = Number(sampleRateHz) / 1000; return `${sampleRateKHz} KHz`; } /** * 格式化媒体格式类型显示 * @param mimeType 媒体格式类型字符串 * @return 格式化后的显示字符串 */ static formatMimeType(mimeType: string | undefined): string { if (StrUtil.isEmpty(mimeType) || mimeType === undefined) { return 'unknown'; } // 从MIME类型中提取格式部分,例如 "audio/mp3" -> "MP3" try { const parts = mimeType.split('/'); if (parts.length > 1) { return parts[1].toUpperCase(); } else { return mimeType.toUpperCase(); } } catch (err) { console.error(`格式化媒体类型出错: ${err}`); return 'unknown'; } } //根据字节获取大小 static formatFileSize(bytes:number) { const units = ['Bytes', 'Kbps', 'Mbps']; let size = bytes; let unitIndex = 0; while (size >= 1024 && unitIndex < units.length - 1) { size /= 1024; unitIndex++; } if(size > 1024&&unitIndex==2){ size = size*0.1 } if(size > 1024&&unitIndex==2){ size = size*0.1 } if(size > 480&&unitIndex==2){ size = size*0.5 } // 保留两位小数, 四舍五入 size = Math.round(size * 10) / 10; return size + units[unitIndex] } //根据字节获取大小无单位 static formatFileSizeWithout(bytes:number) { const units = ['Bytes', 'Kbps', 'Mbps']; let size = bytes; let unitIndex = 0; while (size >= 1024 && unitIndex < units.length - 1) { size /= 1024; unitIndex++; } if(size > 1024&&unitIndex==2){ size = size*0.1 } if(size > 1024&&unitIndex==2){ size = size*0.1 } if(size > 480&&unitIndex==2){ size = size*0.5 } // 保留两位小数, 四舍五入 size = Math.round(size * 10) / 10; return size } static copyText(text:string):boolean{ const pasteboardData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN,text) const systemPasteboard = pasteboard.getSystemPasteboard() systemPasteboard.setData(pasteboardData) systemPasteboard.getData().then((data)=>{ return data }) return false } static getDbm(rssi:number):number{ return Math.round((rssi / 2) + 100) } //根据数字形式的IP地址获取字符串形式的IP地址 static getIpAddrFromNum(ipNum: number): string { return (ipNum >>> 24) + '.' + (ipNum >> 16 & 0xFF) + '.' + (ipNum >> 8 & 0xFF) + '.' + (ipNum & 0xFF); } static resolveIP(ip:number) { let address: string = ip.toString() if (address === '0') { return '00:00:000:000' } address.substring(0, 2) return `${address.substring(0, 2)}:${address.substring(2, 4)}:${address.substring(4, 7)}:${address.substring(7, 10)}` } static isFreeTime():boolean{ if(DateUtil.isWeekend()){ return true } let str = DateUtil.getFormatDateStr(new Date(), 'HH') let a = Number(str); if(isNaN(a)) return false // ToastUtil.showToast('a='+a) if (a >= 7 && a <13) {//白天 return false; } if (a >= 13 && a <20) {//白天 return false; } if (a >= 0 && a < 7) {//凌晨 return true; } if (a >= 20 && a <= 24) {//晚上 return true; } return false } //判断是否是音乐文件 static isMusicByExtension(filename:string) { const extensions = CommonConstants.REAL_MUSIC_FORMAT const lastIndex = filename.lastIndexOf('.'); if (lastIndex!== -1) { const fileExtension = filename.slice(lastIndex).toLowerCase(); return extensions.includes(fileExtension); } return false; } //判断是否是媒体文件 音乐和视频都可以 static isMeidaByExtension(filename:string) { const extensions = CommonConstants.MEDIA_FORMAT const lastIndex = filename.lastIndexOf('.'); if (lastIndex!== -1) { const fileExtension = filename.slice(lastIndex).toLowerCase(); return extensions.includes(fileExtension); } return false; } //判断是否是视频文件 static isVideoByExtension(filename:string) { const extensions = CommonConstants.VIDEO_FORMAT const lastIndex = filename.lastIndexOf('.'); if (lastIndex!== -1) { const fileExtension = filename.slice(lastIndex).toLowerCase(); return extensions.includes(fileExtension); } return false; } // 获取缩略图 static async getFetchFrameByTime(filePath: string) { if(Utility.isMusicByExtension(filePath)){ return undefined } let pixelMap:image.PixelMap|undefined =undefined; try{ // 创建AVImageGenerator对象 let avImageGenerator: media.AVImageGenerator = await media.createAVImageGenerator() let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY); let avFileDescriptor: media.AVFileDescriptor = { fd: file.fd }; avImageGenerator.fdSrc = avFileDescriptor; // 初始化入参 let timeUs = 0 let queryOption = media.AVImageQueryOptions.AV_IMAGE_QUERY_NEXT_SYNC let param: media.PixelMapParams = { width : 300, height : 400, } // 获取缩略图(promise模式) pixelMap = await avImageGenerator.fetchFrameByTime(timeUs, queryOption, param) // 释放资源(promise模式) avImageGenerator.release() console.info(`release success.`) fs.closeSync(file); }catch (error) { console.error('uriGetAssets failed with err: ' + JSON.stringify(error)); } return pixelMap } // 获取fd文件路径 static async getFdDir(path:string){ let fdPath = 'fd://'; let file = await fileIo.open(path) fdPath = fdPath + '' + file.fd; return fdPath } // 根据uri获取文件名称 static getMediaNameByUri(myUri: string) { let myFileName = (myUri.split('/').pop()) as string; return decodeURIComponent(myFileName) } static msToStandardTime(ms:string):string{ let date = new Date(ms); let hours = date.getHours(); let minutes = date.getMinutes(); let seconds = date.getSeconds(); return hours + ':' + minutes + ':' + seconds; } static getTimestampFromDateStr(dateStr: string, format: string = 'yyyy-MM-dd HH:mm'): number { // 定义正则表达式以匹配日期字符串中的各部分 const regex = format .replace('yyyy', '(\\d{4})') .replace('MM', '(\\d{2})') .replace('dd', '(\\d{2})') .replace('HH', '(\\d{2})') .replace('mm', '(\\d{2})'); const match = new RegExp(regex).exec(dateStr); if (!match) { throw new Error('Invalid date string or format'); } // 解析匹配结果 const year = Number(match[1]); const month = Number(match[2]); const day = Number(match[3]); const hours = Number(match[4]); const minutes = Number(match[5]); // 创建 Date 对象 const dateObj = new Date(year, month - 1, day, hours, minutes); // 返回时间戳(以秒为单位) return Math.floor(dateObj.getTime() / 1000); } static getFormatDateStr(date: number | string | Date, format: string = 'yyyy-MM-dd HH:mm:ss'): string { // 将输入转换为 Date 对象 let dateObj: Date; if (typeof date === 'number') { // 如果是十位时间戳,转换为毫秒数 dateObj = new Date(date.toString().length === 10 ? date * 1000 : date); } else if (typeof date === 'string') { // 如果是字符串,尝试解析为 Date 对象 dateObj = new Date(date); } else { // 如果是 Date 对象,直接使用 dateObj = date; } // 定义替换规则 const replacements = new Map([ ['yyyy', String(dateObj.getFullYear())], ['MM', String(dateObj.getMonth() + 1).padStart(2, '0')], ['dd', String(dateObj.getDate()).padStart(2, '0')], ['HH', String(dateObj.getHours()).padStart(2, '0')], ['mm', String(dateObj.getMinutes()).padStart(2, '0')], ['ss', String(dateObj.getSeconds()).padStart(2, '0')] ]); // 替换格式字符串中的占位符 replacements.forEach((value, key) => { format = format.replace(new RegExp(key, 'g'), value); }); return format; } //获取从文件管理器获得的视频资源的属性值 static async uriGetAssetsFromFile(context:Context,uri:string,type:number,isLoadPixelMap?:boolean): Promise { let item:VideoItem = new VideoItem('',uri,uri,type,0,'') try { console.info('asset file.uri: ', uri); let file = fs.openSync(uri, fs.OpenMode.READ_ONLY | fs.OpenMode.CREATE) console.info("file.fd " + file.fd); let fdfd = 'fd://' + file.fd //3、通过fs.stat方法获取stat对象 console.info('asset file.name: ', file.name); console.info('asset file.uri: ', uri); console.info('asset file.fd: ', file.fd); console.info('asset file.path: ', file.path); item = new VideoItem(file.name,uri,uri,type,0,'') await fs.stat(file.fd).then(async (stat: fs.Stat) => { console.info("get file info succeed, the size of file is " + stat.size); let videoSize = stat.size // let videoTime = stat.ctime let fileSize = Utility.formatFSize(videoSize) let cTime = Utility.getFormatDateStr(stat.mtime,'yyyy-MM-dd HH:mm') // console.info('asset stat.ino: ', stat.ino); // console.info('asset stat.mode: ', stat.mode); // console.info('asset stat.uid: ', stat.uid); // console.info('asset stat.ino: ', stat.gid); // console.info('asset stat.size: ', stat.size); console.info('asset stat.ctime: ', stat.ctime); // console.info('asset stat.mtime: ', stat.mtime); // console.info('asset stat.duration: ', duration); let pixelMap:image.PixelMap|undefined = undefined if(isLoadPixelMap){ //获取缩略图 if(Utility.isVideoByExtension(uri)){ pixelMap = await Utility.getFetchFrameByTime(uri) }else{ pixelMap = await Utility.getFetchMetadataFromFdSrcByPromise(uri) } } item = new VideoItem( file.name,uri ,uri,type,videoSize,cTime,pixelMap,fileSize, await ImageUtil.pixelMapToBase64Str(pixelMap)) }) } catch (error) { console.error('uriGetAssetsFromFile failed with err: ' + JSON.stringify(error)); } return item } static async getFilePixelMapBig(uri:string){ let pixelMap:image.PixelMap|undefined = undefined if(Utility.isMusicByExtension(uri)){ pixelMap = await Utility.getFetchMetadataFromFdSrcByPromise(uri) }else{ pixelMap = await Utility.getFetchFrameByTime(uri) } return ImageUtil.pixelMapToBase64StrBig(pixelMap) } static async getFilePixelMap(uri:string){ let pixelMap:image.PixelMap|undefined = undefined if(Utility.isMusicByExtension(uri)){ pixelMap = await Utility.getFetchMetadataFromFdSrcByPromise(uri) }else{ pixelMap = await Utility.getFetchFrameByTime(uri) } return ImageUtil.pixelMapToBase64Str(pixelMap) } //根据filePathe获取对应的播放Index static getIndexFromList(localList:Array,filePath:string){ let list: Array = []; for(let i=0;i { let cover: image.PixelMap | undefined = undefined; if (canIUse("SystemCapability.Multimedia.Media.AVMetadataExtractor")) { try { // 创建AVMetadataExtractor对象 const avMetadataExtractor: media.AVMetadataExtractor = await media.createAVMetadataExtractor(); // 设置fdSrc const fd = await fs.openSync(uri, fs.OpenMode.READ_ONLY); avMetadataExtractor.fdSrc = fd; // 获取元数据(promise模式) const metadata = await avMetadataExtractor.fetchMetadata(); metadata.author console.info(`get meta data, hasAudio: ${metadata.hasAudio}`); // 获取专辑封面(promise模式) cover = await avMetadataExtractor.fetchAlbumCover(); // 释放资源(promise模式) await avMetadataExtractor.release(); console.info('release success.'); } catch (error) { console.error('Error during metadata extraction:', error); } } else { console.warn('AVMetadataExtractor capability is not supported.'); } return cover; } static formatTimestamp(timestamp: number): string { // 将时间戳转换为 Date 对象 const date = new Date(timestamp); // 获取各个部分 const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需要加1 const day = String(date.getDate()).padStart(2, '0'); const hours = String(date.getHours()).padStart(2, '0'); const minutes = String(date.getMinutes()).padStart(2, '0'); const seconds = String(date.getSeconds()).padStart(2, '0'); // 拼接成所需的格式 return `${year}-${month}-${day} ${hours}:${minutes}`; } //获取音乐资源的属性值, static async uriGetMusicAssetsFromFile(context:Context,uri:string,type:number,isLoadPixelMap?:boolean): Promise { return Utility.readMetaInfoFFmpeg(context,uri,type) //华为官方不支持的格式 不支持内嵌歌词Dsf,aif,aiff,wav 不支持内嵌封面dsf,aif,aiff if(StrUtil.isNotEmpty(uri)){ if(uri.toLowerCase().endsWith('.dsf') ||uri.toLowerCase().endsWith('.aif') // ||uri.toLowerCase().endsWith('.wav') ||uri.toLowerCase().endsWith('.aiff')){ return Utility.readMetaInfoFFmpeg(context,uri,type) } } let item:VideoItem = new VideoItem('',uri,uri,type,0,'') try { console.info('asset file.uri: ', uri); let file = fs.openSync(uri, fs.OpenMode.READ_ONLY | fs.OpenMode.CREATE) console.info("file.fd " + file.fd); let fdfd = 'fd://' + file.fd //3、通过fs.stat方法获取stat对象 console.info('asset file.name: ', file.name); console.info('asset file.uri: ', uri); console.info('asset file.fd: ', file.fd); console.info('asset file.path: ', file.path); item = new VideoItem(file.name,uri,uri,type,0,'') await fs.stat(file.fd).then(async (stat: fs.Stat) => { console.info("get file info succeed, the size of file is " + stat.size); let videoSize = stat.size // let videoTime = stat.ctime let fileSize = Utility.formatFSize(videoSize) //按照添加时间 let addTime = Utility.getFormatDateStr(new Date(),'yyyy-MM-dd HH:mm'); // console.info('onecold asset addTime: ', addTime); // let cTime = Utility.getFormatDateStr(stat.mtime,'yyyy-MM-dd HH:mm') // console.info('asset stat.ctime: ', stat.ctime); let musicName:string | undefined = file.name let artist:string | undefined = '' let album:string | undefined = '' let pixelMap:image.PixelMap|undefined|null = undefined let imagePath = '' let duration:string | undefined = '' let mimeType:string | undefined = '' let trackCount:string | undefined = ''//轨道数量 let sampleRate:string | undefined = ''//音频的采样率单位为Hz if (canIUse("SystemCapability.Multimedia.Media.AVMetadataExtractor")) { try { // 创建AVMetadataExtractor对象 const avMetadataExtractor: media.AVMetadataExtractor = await media.createAVMetadataExtractor(); // 设置fdSrc const fd = await fs.openSync(uri, fs.OpenMode.READ_ONLY); avMetadataExtractor.fdSrc = fd; // 获取元数据(promise模式) const metadata = await avMetadataExtractor.fetchMetadata(); if(StrUtil.isNotEmpty(metadata.title)){ musicName = metadata.title }else{ //自动解析像这样的获取不到元数据的 周杰伦-七里香.mp3文件 console.log(`onecold musicName为空:${file.name}`); const musicData = parseMusicFileName(file.name); if (musicData.isValid) { // console.log(`onecold 艺术家:${musicData.artist}`); // 输出:周杰伦 // console.log(`onecold 歌曲名:${musicData.title}`); // 输出:七里香 musicName = musicData.title if(artist==''||artist==undefined) artist = musicData.artist } else { musicName = file.name // console.log("onecold 文件名格式不符合要求"); } } if(StrUtil.isNotEmpty(metadata.artist)){ artist = metadata.artist } if(artist==undefined) artist = '' if(StrUtil.isNotEmpty(metadata.album)){ album = metadata.album }else{ album = '' } if(StrUtil.isNotEmpty(metadata.duration)){ if(metadata.duration) duration = convertSecondsToTime(metadata.duration.toString()) } if(StrUtil.isNotEmpty(metadata.mimeType)){ mimeType = metadata.mimeType } if(StrUtil.isNotEmpty(metadata.trackCount)){ trackCount = metadata.trackCount } if(StrUtil.isNotEmpty(metadata.sampleRate)){ sampleRate = metadata.sampleRate } let name = await MD5.digestSync(uri) if(isLoadPixelMap){ // 获取专辑封面(promise模式) // pixelMap = await avMetadataExtractor.fetchAlbumCover(); // // 释放资源(promise模式) // await avMetadataExtractor.release(); pixelMap = await fetchAlbumCover(avMetadataExtractor) // console.info('onecold release success. name= '+musicName); if(pixelMap!==undefined&&pixelMap!==null){ // console.info('onecold pixelMap is not empty= '+musicName); imagePath = await ImageUtil.savePixelMap(pixelMap,context.filesDir,name) imagePath = fileUri.getUriFromPath(imagePath) }else{ // console.info('onecold pixelMap is empty= '+musicName); imagePath = '' // if(StrUtil.isNotEmpty(artist)) // imagePath = await NetAxiosUtil.getLyricCover(musicName,artist) } }else{ imagePath = context.filesDir + FileUtil.separator + name imagePath = fileUri.getUriFromPath(imagePath) } console.info('onecold release success. imagePath= '+imagePath); } catch (error) { console.error('Error during metadata extraction:', error); } } else { console.warn('AVMetadataExtractor capability is not supported.'); } if(musicName==undefined) musicName = file.name item = new VideoItem(musicName,uri ,uri,type,videoSize,addTime,undefined,fileSize, imagePath,artist,album,file.name) item.duration = duration+''; item.mimeType = mimeType; item.trackCount = trackCount; item.sampleRate = sampleRate; item.isFav = 0; item.playCount = 0; item.pyStr = pinyin4js.getShortPinyin(musicName) // item.lyricContent = await extractLyricsContent(uri) let metaItem = await parseAudioMetadata(uri) if(metaItem){ item.lyricContent = metaItem.lyricContent item.bit_rate = formatBitrateToKbps(metaItem.bit_rate || "0"); item.year = metaItem.year ||'unknown' item.probe_score = metaItem.probe_score item.nb_streams = metaItem.nb_streams item.nb_programs = metaItem.nb_programs } }) } catch (error) { console.error('uriGetAssetsFromFile failed with err: ' + JSON.stringify(error)); } return item } static async readMetaInfoFFmpeg(context:Context,inputPath: string,type:number): Promise { return new Promise((resolve, reject) => { let commands = ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", inputPath]; let outputJson = ""; FFmpeg.execute(commands, { logCallback: (logLevel: number, logMessage: string) => console.log(`[${logLevel}]${logMessage}`), outputCallback: (message: string) => { outputJson += message; }, }).then(async () => { try { let videoItem:VideoItem = new VideoItem('',inputPath,inputPath,type,0,'') const metadata: FFprobeMetadata = JSON.parse(outputJson); const format = metadata.format; let file = fs.openSync(inputPath, fs.OpenMode.READ_ONLY | fs.OpenMode.CREATE) console.info('readMetaInfoFFmpeg asset file.path: ', file.path); videoItem = new VideoItem(file.name,inputPath,inputPath,type,0,'') await fs.stat(file.fd).then(async (stat: fs.Stat) => { // 获取音频流的采样率 let sampleRate = ''; if (metadata.streams && metadata.streams.length > 0) { // 查找第一个音频流 const audioStream = metadata.streams.find(stream => StrUtil.isNotEmpty(stream.sample_rate)); if (audioStream&&audioStream.sample_rate) { sampleRate = audioStream.sample_rate; } } let videoSize = stat.size let fileSize = Utility.formatFSize(videoSize) //按照添加时间 let addTime = Utility.getFormatDateStr(new Date(),'yyyy-MM-dd HH:mm'); // Extract artist and title from tags const tags = format.tags || {}; let artist = tags.artist ||tags.ARTIST || ''; let title = tags.title ||tags.TITLE || ''; const album = tags.album ||tags.ALBUM|| ''; if(StrUtil.isEmpty(title)){ //自动解析像这样的获取不到元数据的 周杰伦-七里香.mp3文件 console.log(`onecold musicName为空:${file.name}`); const musicData = parseMusicFileName(file.name); if (musicData.isValid) { // console.log(`onecold 艺术家:${musicData.artist}`); // 输出:周杰伦 // console.log(`onecold 歌曲名:${musicData.title}`); // 输出:七里香 title = musicData.title if(artist==''||artist==undefined) artist = musicData.artist } else { title = file.name // console.log("onecold 文件名格式不符合要求"); } } let name: string = title; if (!name) { name = getFileNameWithoutExtension(inputPath); } // Create VideoItem videoItem = new VideoItem( name, inputPath, // id can be generated or left empty inputPath, type, // assuming it's local videoSize, addTime // convert to ISO string ); // Set additional properties from format metadata videoItem.artist = artist; videoItem.album = album; videoItem.mimeType = format.format_name videoItem.sampleRate = sampleRate videoItem.pyStr = pinyin4js.getShortPinyin(name) videoItem.fileName = FileUtil.getFileName(inputPath); if(format.duration) videoItem.duration = formatDuration(format.duration.toString()||'00:00') videoItem.size = fileSize; videoItem.bit_rate =formatBitrateToKbps(format.bit_rate || "0"); videoItem.probe_score = format.probe_score; videoItem.nb_streams = format.nb_streams; videoItem.nb_programs = format.nb_programs; videoItem.year = tags.TYER || tags.date ||tags.DATE|| Utility.resourceToString(context, $r('app.string.unknown')); // try different tag names for year videoItem.lyricContent = tags.LYRICS || tags.lyrics || tags.USLT || tags.UNSYNCEDLYRICS || ''; videoItem.genre = tags.genre||tags.GENRE|| Utility.resourceToString(context, $r('app.string.unknown')); videoItem.track = tags.track||tags.TRACK|| Utility.resourceToString(context, $r('app.string.unknown')); // 检查是否有封面图片流 const hasCover = metadata.streams.some(stream => stream.disposition?.attached_pic === 1 ); console.info('readMetaInfoFFmpeg asset hasCover: ', hasCover); // 如果有封面图片,则提取 if (hasCover) { try { let md5Name = await MD5.digestSync(inputPath) let imagePath = `${context.filesDir}${FileUtil.separator}${md5Name}.jpg`; console.info('readMetaInfoFFmpeg asset imagePath: ', imagePath); //提取封面 await getFFmpegCover(inputPath, imagePath); imagePath = fileUri.getUriFromPath(imagePath) videoItem.pixelMapPath = imagePath; } catch (error) { console.warn(' 提取封面图片失败:', error.message); } } console.info('Successfully parsed metadata:', videoItem); resolve(videoItem); }) } catch (error) { console.error('Failed to parse metadata:', error); reject(new Error('Failed to parse metadata: ' + error.message)); } }).catch((error: Error) => { console.error(`Execution failed with error: ${error.message}`); reject(error); }); }); } private completionNum(num: number): string | number { if (num < 10) { return '0' + num; } else { return num; } } //根据字节获取大小 static formatFSize(bytes:number):string { const units = ['Bytes', 'K', 'M', 'G']; let size = bytes; let unitIndex = 0; while (size >= 1024 && unitIndex < units.length - 1) { size /= 1024; unitIndex++; } // 保留两位小数, 四舍五入 size = Math.round(size * 10) / 10; return size + units[unitIndex] } static gotoMarket(context:common.UIAbilityContext,bundleName:string) { const want: Want = { uri: `store://appgallery.huawei.com/app/detail?id=${bundleName}` }; context.startAbility(want).then(()=>{ //拉起成功 }).catch(()=>{ // 拉起失败 }); } static async doShare(item:VideoItem,context:common.UIAbilityContext){ // 生成视频封面图 const imagePackerApi: image.ImagePacker = image.createImagePacker(); const buffer: ArrayBuffer = await (imagePackerApi.packing(await Utility.getFetchFrameByTime(item.filePath), { format: 'image/jpeg', quality: 30 }) as Promise); // 构造ShareData,需配置一条有效数据信息 let shareData: systemShare.SharedData = new systemShare.SharedData({ utd: uniformTypeDescriptor.UniformDataType.MEDIA, uri: fileUri.getUriFromPath(item.filePath), title: item.name, // 不传title字段时,显示视频文件名 // description: '好听的音乐', // 不传description字段时,显示视频大小 thumbnail: new Uint8Array(buffer), // 优先使用传递的缩略图做预览 不传则默认使用视频第一帧画面做预览图 }); // 进行分享面板显示 let controller: systemShare.ShareController = new systemShare.ShareController(shareData); // let context = getContext(this) as common.UIAbilityContext; controller.show(context, { selectionMode: systemShare.SelectionMode.SINGLE, previewMode: systemShare.SharePreviewMode.DETAIL, }).then(() => { console.info('ShareController show success.'); }).catch((error: BusinessError) => { console.error(`ShareController show error. code: ${error.code}, message: ${error.message}`); }); } //分享索引index的视频 static async doShareMusic(item:VideoItem,context:common.UIAbilityContext){ // 构造ShareData,需配置一条有效数据信息 let shareData: systemShare.SharedData = new systemShare.SharedData({ utd: uniformTypeDescriptor.UniformDataType.AUDIO, uri: fileUri.getUriFromPath(item.filePath), title: item.name, // 不传title字段时,显示视频文件名 description: '好听的音乐', // 不传description字段时,显示视频大小 }); // 进行分享面板显示 let controller: systemShare.ShareController = new systemShare.ShareController(shareData); // let context = getContext(this) as common.UIAbilityContext; controller.show(context, { selectionMode: systemShare.SelectionMode.SINGLE, previewMode: systemShare.SharePreviewMode.DETAIL, }).then(() => { console.info('ShareController show success.'); }).catch((error: BusinessError) => { console.error(`ShareController show error. code: ${error.code}, message: ${error.message}`); }); } static getNameList(localList:Array){ let list: Array = []; for(let i=0;i):string{ let list: Array = []; for(let i=0;i,type:number){ let list: Array = []; for(let i=0;i,type:number){ let list: Array = []; for(let i=0;i,filePath:string){ let index: number = 0; for(let i=0;i,item:VideoItem|undefined){ if(ArrayUtil.isEmpty(favList)){ return false } if(item===undefined){ return false } for(let i=0;i,item:VideoItem|undefined){ if(ArrayUtil.isEmpty(facList)){ return false } if(item===undefined){ return false } for(let i=0;i,type:number){ let list: Array = []; for(let i=0;i { try { // 1. 同步化BundleInfo获取 const bundleInfo = await bundleManager.getBundleInfoForSelf( bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION ); // 2. 安全获取labelId(新增空值校验) const labelId = bundleInfo.appInfo?.labelId; if (!labelId || labelId <= 0) { throw new Error("Invalid labelId: " + labelId); } // 3. 异步资源解析(替换危险的getStringSync) return await context.resourceManager.getStringValue(labelId); } catch (err) { console.error(`[${new Date().toISOString()}] AppName Error: CODE=${err.code}, MSG=${err.message}`); // 4. 多级降级策略 return AppUtil.getBundleName() // 最终兜底 } } //按名称升序 static doSortListAscending( list:Array){ let options: Intl.CollatorOptions = { localeMatcher: "lookup", usage: "sort", sensitivity: "case" // 区分大小写 }; const collator = new Intl.Collator("zh-CN", options); list.sort((a, b) => { const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type); if (typeOrder !== 0) { return typeOrder; } const partsA = extractParts(a.name); const partsB = extractParts(b.name); const nonNumericComparison = collator.compare(partsA.nonNumeric, partsB.nonNumeric); if (nonNumericComparison !== 0) { return nonNumericComparison; } return partsA.numeric - partsB.numeric; }); } //按名称降序 static doSortListDescending(list:Array){ const options: Intl.CollatorOptions = { localeMatcher: "lookup", usage: "sort", sensitivity: "case" // 区分大小写 }; const collator = new Intl.Collator("zh-CN", options); list.sort((a, b) => { const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type); if (typeOrder !== 0) { return typeOrder; } const partsA = extractParts(a.name); const partsB = extractParts(b.name); const nonNumericComparison = collator.compare(partsB.nonNumeric, partsA.nonNumeric); if (nonNumericComparison !== 0) { return nonNumericComparison; } return partsB.numeric - partsA.numeric; }); } /** * 读取本地会员到期时间(解密.vv文件) * @returns */ static async getLocalNobleExpireDate(): Promise { // return "2025-08-08 12:00"; try { const documentViewPicker = new picker.DocumentViewPicker() let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD }) let download_path = new fileUri.FileUri(documentSaveResult[0]).path + '/' let filePath = download_path + LocalMusic.STR_LOCK_VIDEO+ '/' + VipPage.VIP_FILEPATH let expireDate = Utility.readDataFromFile(filePath) return expireDate; } catch (e) { return ''; } } static readDataFromFile(filePath: string) { if(!FileUtil.accessSync(filePath)){ return '' } let readTextOptions: ReadTextOptions = { offset: 0, length: 0, encoding: 'utf-8' }; let stat = fileIo.statSync(filePath); readTextOptions.length = stat.size; let str = fileIo.readTextSync(filePath, readTextOptions); const parsedData:VipData = JSON.parse(str) as VipData; // LogUtil.info('onecold parsedData.expireDate = ' + parsedData.expireDate) let result = Base64Util.decodeSync( parsedData.expireDate) // LogUtil.info('onecold 解密的result = ' +StrUtil.unit8ArrayToStr(result)) return StrUtil.unit8ArrayToStr(result); } } interface PathStat { path: string; isDirectory: boolean; } async function isDirectory(filePath: string): Promise { try { const stat = await fs.stat(filePath); return stat.isDirectory(); } catch (error) { console.error('Error getting file stat:', error); return false; } } //排序模式参数 interface VideoNameParts { nonNumeric: string; numeric: number; } // 提取文件名中的非数字和数字部分 function extractParts(name: string): VideoNameParts { // Adjust the regex to handle names that start with numbers const match = name.match(/^(\D*?)(\d+)(\.\w+)?$/); if (match) { return { nonNumeric: match[1] || '', // Ensure nonNumeric is not undefined numeric: parseInt(match[2], 10), }; } return { nonNumeric: name, numeric: 0, }; } function getInstallTime(): number | null { // 从本地存储中获取安装时间 return PreferencesUtil.getNumberSync('installTime') } function setInstallTime(time: number) { // 将安装时间存储到本地存储中 PreferencesUtil.putSync('installTime',time) } function fetchAlbumCover(avMetadataExtractor: media.AVMetadataExtractor): Promise { return new Promise((resolve, reject) => { avMetadataExtractor.fetchAlbumCover((error: BusinessError, pixelMap: image.PixelMap) => { if (error) { console.error(`Failed to fetch AlbumCover, error = ${JSON.stringify(error)}`); resolve(null); } else { resolve(pixelMap); } avMetadataExtractor.release(); }); }); } //排序类型 function getTypeOrder(type: number) { switch (type) { case CommonConstants.TYPE_IS_DIR: return 1; // First case CommonConstants.TYPE_IS_CSJAD: return 2; // Middle case CommonConstants.TYPE_LOCAL: return 3; // Last default: return 4; // Unknown types, if any, go last } } function convertSecondsToTime(secondsStr: string): string { if (!secondsStr || isNaN(Number(secondsStr))) { return "00:00"; } let seconds = parseInt(secondsStr, 10); seconds = Math.floor(seconds / 1000); const hours = Math.floor(seconds / 3600); const minutes = Math.floor((seconds % 3600) / 60); const secs = seconds % 60; const formatNumber = (num: number) => num.toString().padStart(2, '0'); if (hours > 0) { return `${formatNumber(hours)}:${formatNumber(minutes)}:${formatNumber(secs)}`; } else { return `${formatNumber(minutes)}:${formatNumber(secs)}`; } } /** * 秒数 → 智能时间格式(自动选择 MM:SS 或 HH:MM:SS) * @param seconds 秒数字符串(如 "283.524351" 或 "3675") * @param forceHHMMSS 强制使用 HH:MM:SS 格式(默认自动判断) * @returns 格式化后的时间字符串 */ function formatDuration(seconds: string, forceHHMMSS: boolean = false): string { // 1. 校验输入 const secNum = parseFloat(seconds); if (isNaN(secNum) || secNum < 0) return forceHHMMSS ? "00:00:00" : "00:00"; // 2. 计算时间分量 const totalSec = Math.floor(secNum); const hours = Math.floor(totalSec / 3600); const mins = Math.floor((totalSec % 3600) / 60); const secs = totalSec % 60; // 3. 格式化输出 const pad = (n: number) => n.toString().padStart(2, '0'); return forceHHMMSS || hours > 0 ? `${pad(hours)}:${pad(mins)}:${pad(secs)}` // HH:MM:SS : `${pad(mins)}:${pad(secs)}`; // MM:SS } // 定义解析结果的数据结构 class MusicInfo { artist: string = ""; // 艺术家名称 title: string = ""; // 歌曲名称 isValid: boolean = false; // 格式是否有效 } /** * 解析音乐文件名 * @param fileName - 待解析的文件名(需包含扩展名) * @returns 包含解析结果的MusicInfo对象 */ /** * 智能解析音乐文件名(支持多种分隔符和前缀序号) * @param fileName - 待解析的完整文件名 * @returns 结构化音乐信息 */ function parseMusicFileName(fileName: string): MusicInfo { const result = new MusicInfo(); // 1. 预处理:移除首尾空格(保留中间空格) const cleanName = fileName.trim(); // 2. 提取文件扩展名(以最后一个点分隔) const lastDotIndex = cleanName.lastIndexOf('.'); if (lastDotIndex < 0) return result; // 无扩展名 const baseName = cleanName.substring(0, lastDotIndex).trim(); const extension = cleanName.substring(lastDotIndex + 1); // 3. 支持多种分隔符(中英文短横线) const separators = ['-', '-', '—']; // 半角/全角短横线 let dashIndex = -1; // 查找最后一个有效分隔符位置 for (const sep of separators) { const index = baseName.lastIndexOf(sep); if (index > dashIndex) dashIndex = index; } // 4. 核心解析逻辑 if (dashIndex > 0 && dashIndex < baseName.length - 1) { let artistPart = baseName.substring(0, dashIndex).trim(); result.title = baseName.substring(dashIndex + 1).trim(); // 5. 处理前缀序号(如"04 - ") const numPrefixRegex = /^\d+\s*[--—]\s*/; // 匹配数字+分隔符组合 artistPart = artistPart.replace(numPrefixRegex, '').trim(); // 6. 最终有效性验证 result.artist = artistPart; result.isValid = (result.artist.length > 0 && result.title.length > 0); } return result; } function getFileNameWithoutExtension(filePath: string): string { const fileName = filePath.split('/').pop() || ''; const lastDotIndex = fileName.lastIndexOf('.'); return lastDotIndex > 0 ? fileName.substring(0, lastDotIndex) : fileName; } /** * 从视频文件中提取封面 * @param inputPath 音乐文件路径 * @returns Promise */ async function extractCoverImage(inputPath: string, outputPath: string): Promise { const commands = [ 'ffmpeg', '-i', inputPath, '-an', // 禁用音频 '-vcodec', 'copy', // 直接复制视频流 '-f', 'image2', // 强制输出为图片 '-y', // 覆盖输出文件 outputPath ]; return new Promise((resolve, reject) => { FFmpeg.execute(commands, { logCallback: (logLevel: number, logMessage: string) => { console.log(`[${logLevel}]${logMessage}`); }, outputCallback: (message: string) => { console.log(`FFmpeg output: ${message}`); }, }).then(() => resolve()) .catch((error: BusinessError) => reject(error)); }); } /** * 从音乐文件中提取封面 * @param inputPath 音乐文件路径 * @returns Promise */ async function getFFmpegCover(inputPath: string, outputPath: string) { let commands = ["ffmpeg", "-y","-i", inputPath, "-map", "0:v", "-c:v", "copy", outputPath]; FFmpeg.execute(commands, { logCallback: (logLevel: number, logMessage: string) => { console.info(`[FFmpeg LOG] [${logLevel}]${logMessage}`) }, progressCallback: (message: string) => { console.info(`[FFmpeg progress]${JSON.stringify(FFProgressMessageParser.parse(message))}`) }, }) .then(() => { console.info("FFmpeg execution succeeded."); }) .catch((error: Error) => { console.error(`FFmpeg execution failed with error: ${error.message}`); }); } /** * 从音乐文件中提取歌词内容 * @param inputPath 音乐文件路径 * @returns Promise 直接返回歌词内容,若无歌词则返回空字符串 */ async function extractLyricsContent(inputPath: string): Promise { return new Promise(async (resolve, reject) => { try { // 1. 使用ffprobe获取元数据 const commands = [ 'ffprobe', '-v', 'quiet', '-print_format', 'json', '-show_format', inputPath ]; let outputJson = ''; await FFmpeg.execute(commands, { outputCallback: (message: string) => outputJson += message, }); // 2. 解析歌词标签 const metadata:FFprobeMetadata = JSON.parse(outputJson); const tags = metadata.format?.tags || {}; // 3. 从常见标签中查找歌词(优先级顺序) const lyricContent = tags.LYRICS || // 标准标签 tags.lyrics || // 小写变体 tags.USLT || // ID3v2标签 tags.UNSYNCEDLYRICS || ''; resolve(lyricContent.trim()); } catch (error) { reject(`解析失败: ${error instanceof Error ? error.message : String(error)}`); } }); } /** * 解析音乐文件元数据(包含歌词和其他关键字段) * @param inputPath 文件路径 * @returns Promise 包含完整元数据的对象 */ async function parseAudioMetadata(inputPath: string): Promise { return new Promise(async (resolve, reject) => { try { // 1. 执行FFprobe命令 const commands: string[] = [ 'ffprobe', '-v', 'quiet', '-print_format', 'json', '-show_format', '-show_streams', inputPath ]; let outputJson = ''; await FFmpeg.execute(commands, { outputCallback: (message: string) => outputJson += message, }); // 2. 解析元数据 const metadata = JSON.parse(outputJson) as FFprobeMetadata; const format:FFprobeFormat = metadata.format ; const tags = format.tags||{} ; // 3. 构建VideoItem基础信息 const videoItem = new VideoItem( tags.title || getFileNameWithoutExtension(inputPath), inputPath, // id inputPath, CommonConstants.TYPE_LOCAL, 0, new Date().toISOString() // 使用当前时间作为默认创建时间 ); // 4. 设置关键字段 videoItem.bit_rate = format.bit_rate || ''; videoItem.probe_score = format.probe_score || 0; videoItem.year = tags.TYER || tags.date || ''; videoItem.lyricContent = tags.LYRICS ?? tags.lyrics ?? tags.USLT ?? tags.UNSYNCEDLYRICS ?? ''; // 5. 设置其他可选字段 videoItem.artist = tags.artist || ''; videoItem.album = tags.album || ''; videoItem.duration = format.duration || ''; videoItem.nb_streams = format.nb_streams; videoItem.nb_programs = format.nb_programs; resolve(videoItem); } catch (error) { reject(new Error(`元数据解析失败: ${error instanceof Error ? error.message : String(error)}`)); } }); } /** * 将比特率(bps)转换为 kbps 并格式化 * @param bitRate 比特率字符串(如 "5644802") * @param decimalPlaces 保留小数位数(默认0) * @returns 格式化后的 kbps 字符串(如 "5644 kbps") */ function formatBitrateToKbps(bitRate: string, decimalPlaces: number = 0): string { // 1. 转换为数字 const bitsPerSecond = parseInt(bitRate); if (isNaN(bitsPerSecond) || bitsPerSecond < 0) return "0 kbps"; // 2. 计算 kbps(1 kbps = 1000 bps) const kbps = bitsPerSecond / 1000; // 3. 格式化输出 return `${kbps.toFixed(decimalPlaces)} kbps`; }