浏览代码

Merge remote-tracking branch 'origin/master' into feature/cdb/微信登录+用户中心

# Conflicts:
#	entry/src/main/ets/view/LocalMusic.ets
chendeben 1 年之前
父节点
当前提交
dc3511d2b7

+ 10 - 12
entry/src/main/ets/common/util/RdbUtils.ets

@@ -60,7 +60,10 @@ export default class RdbUtils {
       '        lyricContent TEXT,\n' +
       '        mimeType TEXT' +
       ')',
-    columns: ['id', 'name', 'filePath','mtype', 'videoSize', 'cTime','size', 'artist', 'album','fileName','parentPath','isFav','pixelMapPath','pixelMapToString', 'duration', 'mimeType', 'trackCount', 'sampleRate', 'lastPlayedStr', 'playCount', 'lyricContent']
+    columns: ['id', 'name', 'filePath','mtype', 'videoSize', 'cTime','size', 'artist', 'album',
+      'fileName','parentPath','isFav','pixelMapPath','pixelMapToString',
+      'duration',   'sampleRate','playCount',  'lastPlayedStr', 'trackCount',
+      'lyricContent','mimeType']
   };
 
   constructor(tableName: string, sqlCreateTable: string, columns: Array<string>) {
@@ -301,29 +304,24 @@ export default class RdbUtils {
     }
   }
 
+
   query(predicates: relationalStore.RdbPredicates, callback: Function = () => {
   }) {
     if (!callback || typeof callback === 'undefined' || callback === undefined) {
       Logger.info(RdbUtils.RDB_TAG, 'query() has no callback!');
       return;
     }
-    
     if (this.rdbStore) {
-      // 使用安全的列集合查询
-      // 首先仅查询基本列(确保100%存在)
-      const safeColumns = ['id', 'name', 'filePath', 'mtype', 'videoSize', 'cTime', 
-                           'size', 'artist', 'album', 'fileName', 'parentPath', 
-                           'isFav', 'pixelMapPath', 'pixelMapToString'];
-      
-      this.rdbStore.query(predicates, safeColumns, (err, resultSet) => {
+      this.rdbStore.query(predicates, this.columns, (err, resultSet) => {
         if (err) {
-          Logger.error(RdbUtils.RDB_TAG, `query() failed, err: ${err}`);
-          callback(null);
+          Logger.error(RdbUtils.RDB_TAG, `query() failed, err:  ${err}`);
           return;
         }
-        
+        // Logger.info(RdbUtils.RDB_TAG, 'query() finished.');
         callback(resultSet);
+        resultSet.close();
       });
     }
   }
+
 }

+ 54 - 4
entry/src/main/ets/common/util/Utility.ets

@@ -166,6 +166,30 @@ export class Utility {
     }
   }
 
+  /**
+   * 格式化媒体格式类型显示
+   * @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'];
@@ -702,7 +726,8 @@ export class Utility {
             }
 
             if(StrUtil.isNotEmpty(metadata.duration)){
-              duration = DateUtil.getFormatDateStr(metadata.duration,'HH:mm:ss')
+              if(metadata.duration)
+                duration = convertSecondsToTime(metadata.duration.toString())
             }
             if(StrUtil.isNotEmpty(metadata.mimeType)){
               mimeType = metadata.mimeType
@@ -775,8 +800,13 @@ export class Utility {
 
 
 
-
-
+  private completionNum(num: number): string | number {
+    if (num < 10) {
+      return '0' + num;
+    } else {
+      return num;
+    }
+  }
 
   //根据字节获取大小
   static  formatFSize(bytes:number):string {
@@ -1241,4 +1271,24 @@ function getTypeOrder(type: number) {
     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)}`;
+  }
+}

+ 23 - 129
entry/src/main/ets/view/LocalMusic.ets

@@ -73,7 +73,7 @@ import { secondToTime } from '../common/util/CommUtils';
 import { CommonConstants2 } from '../common/util/CommonConstants2';
 import { hilog } from '@kit.PerformanceAnalysisKit';
 import { LazyDataSource } from '../common/util/LazyDataSource';
-import MediaTable, { MediaMetadata } from '../common/util/MediaTable';
+import MediaTable from '../common/util/MediaTable';
 import NetAxiosUtil from '../common/util/NetAxiosUtil';
 import ImageUtils from '../common/util/ImageUtils';
 import { ringtone } from '@kit.RingtoneKit';
@@ -85,7 +85,6 @@ import { deviceInfo } from '@kit.BasicServicesKit';
 import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
 import { DEBUG } from 'BuildProfile';
 import { LrcParser } from '@sgaolei/lrc_parser';
-import { IBestIcon } from "@ibestservices/ibest-ui";
 import app, { AppResponse } from '@system.app';
 import { Log } from '@tencent/wechat_open_sdk';
 
@@ -631,40 +630,17 @@ export struct LocalMusic {
 
       this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
       this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
-      
-      // 打印加载的当前歌曲信息,用于调试
-      if (this.currentSong) {
-        console.info(`加载歌曲信息 - 采样率: ${this.currentSong.sampleRate}, MIME类型: ${this.currentSong.mimeType}`);
-      }
-      
       if (ArrayUtil.isEmpty(this.songList)) {
         this.songList = this.getCurFileList()
       } else {
-        this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong?.filePath || '')
+        this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
       }
       if (ArrayUtil.isNotEmpty(this.songList)) {
         this.sonDataSource.pushArrayData(this.songList)
         if (this.currentSong === undefined) {
+
           this.currentSong = this.songList[0]
         }
-        
-        // 如果当前歌曲缺少必要信息,尝试从数据库中重新加载
-        if (this.currentSong && (!this.currentSong.sampleRate || !this.currentSong.mimeType)) {
-          this.table.queryByFilePath(this.currentSong.filePath, (result: VideoItem[]) => {
-            if (result && result.length > 0) {
-              // 更新当前歌曲对象,手动复制属性
-              if (this.currentSong) {
-                const dbItem = result[0];
-                this.currentSong.sampleRate = dbItem.sampleRate;
-                this.currentSong.mimeType = dbItem.mimeType;
-                this.currentSong.duration = dbItem.duration;
-                this.currentSong.trackCount = dbItem.trackCount;
-                console.info(`从数据库更新歌曲属性 - 采样率: ${dbItem.sampleRate}, MIME类型: ${dbItem.mimeType}`);
-              }
-            }
-          });
-        }
-        
         this.videoUrl = this.currentSong.filePath
         this.name = this.currentSong.name
         this.cover = this.currentSong.pixelMapPath
@@ -792,7 +768,6 @@ export struct LocalMusic {
         files = result;
       }
 
-
       files.sort((a, b) => a.cTime.localeCompare(b.cTime));
       Utility.doSortListAscending(files)
 
@@ -820,7 +795,7 @@ export struct LocalMusic {
       console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
       // for (let i = 0; i < this.videoLocalList.length; i++) {
       //
-      //   console.info(`onecold gengxin 1: ${this.videoLocalList[i].pixelMapPath}`);
+      //   console.info(`onecold gengxin 1: ${this.videoLocalList[i].sampleRate}`);
       //
       // }
 
@@ -2184,14 +2159,11 @@ export struct LocalMusic {
   @Builder
   private DirItem(item: VideoItem, index?: number) {
     Row() {
-      // Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
-      // $r('app.media.music_group'))
-      SymbolGlyph($r('sys.symbol.identify_song'))
+      Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
+      $r('app.media.music_group'))
         .height(33)
         .width(33)
-        .fontColor([$r('app.color.img_color')])
-        .fontSize(33)
-        // .alt($r('app.media.music_group'))
+        .alt($r('app.media.music_group'))
         .borderRadius('100%')
         .clip(true)
         .margin({ left: 20, top: 8, bottom: 8 })
@@ -2503,7 +2475,6 @@ export struct LocalMusic {
             duration: 666,
             curve: 'ease-in-out' // 可选动画曲线
           })// .opacity(this.opacityItem)
-          .fillColor($r('app.color.img_color'))
           .clickEffect({ level: ClickEffectLevel.MIDDLE })
           .onClick(() => {
             this.isSearchMode = true
@@ -2519,14 +2490,12 @@ export struct LocalMusic {
             this.showRankDialog()
           })
 
-        SymbolGlyph(this.isGridMusic?$r('sys.symbol.list_bullet'):$r('sys.symbol.square_grid_2x2'))
-        .fontColor([$r('app.color.img_color')])
+        Image(this.isGridMusic?$r('app.media.list'):$r("app.media.grid"))
           .width(25)
           .animation({
             duration: 666,
             curve: 'ease-in-out' // 可选动画曲线
           })
-
           .clickEffect({ level: ClickEffectLevel.MIDDLE })
           .onClick(() => {
             this.isGridMusic = !this.isGridMusic
@@ -2545,11 +2514,10 @@ export struct LocalMusic {
 
       Row({ space: 8 }) {
         Row({ space: 8 }) {
-          // Image($r("app.media.hm_play"))
-          IBestIcon({name:'play-circle-o',iconSize:25,color:$r('app.color.img_color')})
+          Image($r("app.media.hm_play"))
             .width(25)
             .margin({ left: 8 })
-            // .fillColor($r('app.color.img_color'))
+            .fillColor('#ff5186')
           Text(`播放全部`)
             .fontColor($r('app.color.text_color'))
             .fontSize(14)
@@ -2625,7 +2593,6 @@ export struct LocalMusic {
             duration: 666,
             curve: 'ease-in-out' // 可选动画曲线
           })// .opacity(this.opacityItem)
-          .fillColor($r('app.color.img_color'))
           .clickEffect({ level: ClickEffectLevel.MIDDLE })
           .onClick(() => {
             this.isSearchMode = true
@@ -2636,20 +2603,17 @@ export struct LocalMusic {
             duration: 666,
             curve: 'ease-in-out' // 可选动画曲线
           })
-          .fillColor($r('app.color.img_color'))
           .clickEffect({ level: ClickEffectLevel.MIDDLE })
           .onClick(() => {
             this.isGridMusic = !this.isGridMusic
           })
-        // Image($r("app.media.refresh"))
-        IBestIcon({ name: 'replay',iconSize:25,color:$r('app.color.img_color') })
-          // .width(25)
+        Image($r("app.media.refresh"))
+          .width(25)
           .visibility(this.isHistory || this.isCanBack || this.isSearchMode ? Visibility.None : Visibility.Visible)
           .animation({
             duration: 666,
             curve: 'ease-in-out' // 可选动画曲线
           })// .opacity(this.opacityItem)
-          // .fillColor($r('app.color.img_color'))
           .clickEffect({ level: ClickEffectLevel.MIDDLE })
           .onClick(() => {
             if(this.isFavMusic){
@@ -2668,7 +2632,6 @@ export struct LocalMusic {
             duration: 666,
             curve: 'ease-in-out' // 可选动画曲线
           })
-          .fillColor($r('app.color.img_color'))
           .clickEffect({ level: ClickEffectLevel.MIDDLE })
           .onClick(() => {
             this.showRankDialog()
@@ -2678,13 +2641,12 @@ export struct LocalMusic {
         Image(this.isMultiSelect ? $r("app.media.cancel_multi") : $r("app.media.top_flower"))
           .width(24)
           .margin({ right: 10 })
-          // .fillColor('#ff5186')// .opacity(this.opacityItem)
+          .fillColor('#ff5186')// .opacity(this.opacityItem)
           .visibility(this.isHistory || this.isSearchMode ? Visibility.None : Visibility.Visible)
           .animation({
             duration: 666,
             curve: 'ease-in-out' // 可选动画曲线
           })
-          .fillColor($r('app.color.img_color'))
           .clickEffect({ level: ClickEffectLevel.MIDDLE })
           .onClick(() => {
             this.isMultiSelect = !this.isMultiSelect
@@ -2692,7 +2654,7 @@ export struct LocalMusic {
         Image($r("app.media.uninstall_green"))
           .width(24)
           .margin({ right: 10 })
-          .fillColor($r('app.color.img_color'))
+          .fillColor('#ff5186')
           .visibility(this.isHistory ? Visibility.Visible : Visibility.None)
           .animation({
             duration: 666,
@@ -3576,7 +3538,9 @@ export struct LocalMusic {
         this.name = this.currentSong.name
         this.cover = this.currentSong.pixelMapPath
 
-
+        LogUtil.info('this.currentSong.duration ='+this.currentSong.duration)
+        LogUtil.info('this.currentSong.sampleRate ='+this.currentSong.sampleRate)
+        LogUtil.info('this.currentSongmimeType ='+this.currentSong.mimeType)
         this.startPlayOrResumePlay()
         break;
 
@@ -3619,9 +3583,6 @@ export struct LocalMusic {
 
           if (ArrayUtil.isNotEmpty(this.songList)) {
             this.isShowPlay = true;
-            // 显示播放界面时重新提取音频元数据
-            this.refreshCurrentSongMetadata();
-            
             let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
             this.initLyric(lyricPath);
             if (FileUtil.accessSync(this.favPath)) {
@@ -3638,7 +3599,6 @@ export struct LocalMusic {
             .height(24)
             .width(24)
             .margin({ left: 8, right: 16 })
-            .fillColor($r('app.color.img_color'))
             .displayPriority(2)
             .onClick(() => {
               if (ArrayUtil.isNotEmpty(this.songList)) {
@@ -3664,7 +3624,6 @@ export struct LocalMusic {
               .height(32)
               .width(32)
               .displayPriority(3)
-              .fillColor($r('app.color.img_color'))
               .onClick(() => {
                 if (ArrayUtil.isNotEmpty(this.songList)) {
                   this.playOrPause()
@@ -3682,7 +3641,6 @@ export struct LocalMusic {
               right: 16,
               left: 16
             })
-            .fillColor($r('app.color.img_color'))
             .displayPriority(2)
             .onClick(() => {
               if (ArrayUtil.isNotEmpty(this.songList)) {
@@ -3697,7 +3655,6 @@ export struct LocalMusic {
             .height(24)
             .width(24)
             .displayPriority(1)
-            .fillColor($r('app.color.img_color'))
             .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
               height: '95%',
               dragBar: true,
@@ -4182,15 +4139,11 @@ export struct LocalMusic {
             .fontSize(14)
             .fontColor(Color.White)
             .margin({ left: 22 })
-          Text(Utility.convertToKHz(this.currentSong?.sampleRate || ''))
+          Text(Utility.convertToKHz(this.currentSong.sampleRate))
             .fontSize(14)
             .margin({ left: 10 })
             .fontColor(Color.White)
             .layoutWeight(1)
-            .onAppear(() => {
-              console.info('音频信息:'+JSON.stringify(this.currentSong))
-              console.info(`音频采样率原始值: ${this.currentSong?.sampleRate}, 类型: ${typeof this.currentSong?.sampleRate}`);
-            })
         }
         .width('100%')
         .margin({ top: 10, bottom: 10 })
@@ -4201,14 +4154,11 @@ export struct LocalMusic {
             .fontSize(14)
             .fontColor(Color.White)
             .margin({ left: 22 })
-          Text(Utility.formatMimeType(this.currentSong?.mimeType || ''))
+          Text(Utility.formatMimeType(this.currentSong.mimeType))
             .fontSize(14)
             .margin({ left: 10 })
             .fontColor(Color.White)
             .layoutWeight(1)
-            .onAppear(() => {
-              console.info(`音频MIME类型原始值: ${this.currentSong?.mimeType}, 类型: ${typeof this.currentSong?.mimeType}`);
-            })
         }
         .width('100%')
         .margin({ top: 10, bottom: 10 })
@@ -7450,53 +7400,6 @@ export struct LocalMusic {
     this.replayVisible = Visibility.Visible;
   }
 
-  // 从文件重新提取音频元数据
-  private async refreshCurrentSongMetadata() {
-    if (!this.currentSong || StrUtil.isEmpty(this.currentSong.filePath)) {
-      console.error('无法刷新元数据,当前歌曲或文件路径为空');
-      return;
-    }
-    
-    try {
-      // 直接从音频文件重新加载完整的元数据
-      console.info(`开始重新提取音频元数据: ${this.currentSong.filePath}`);
-      const refreshedItem = await Utility.uriGetMusicAssetsFromFile(
-        this.context, 
-        this.currentSong.filePath, 
-        CommonConstants.TYPE_LOCAL, 
-        false
-      );
-      
-      // 只更新元数据相关字段,保留其他字段
-      if (this.currentSong) {
-        this.currentSong.duration = refreshedItem.duration;
-        this.currentSong.mimeType = refreshedItem.mimeType;
-        this.currentSong.sampleRate = refreshedItem.sampleRate;
-        this.currentSong.trackCount = refreshedItem.trackCount;
-        
-        // 更新数据库中的记录以确保下次不需要重新提取
-        // 创建符合MediaMetadata接口的对象
-        const metadataToUpdate: MediaMetadata = {
-          duration: refreshedItem.duration,
-          mimeType: refreshedItem.mimeType,
-          sampleRate: refreshedItem.sampleRate,
-          trackCount: refreshedItem.trackCount
-        };
-        this.table.updateMediaMetadata(this.currentSong.filePath, metadataToUpdate, (success: boolean) => {
-          if (success) {
-            console.info('成功更新音频元数据到数据库');
-          } else {
-            console.error('更新音频元数据到数据库失败');
-          }
-        });
-        
-        console.info(`刷新后的采样率: ${this.currentSong.sampleRate}, MIME类型: ${this.currentSong.mimeType}`);
-      }
-    } catch (err) {
-      console.error(`刷新音频元数据失败: ${err}`);
-    }
-  }
-  
   private async play(url: string) {
     let that = this;
     that.showLoadIng();
@@ -7816,16 +7719,10 @@ export struct LocalMusic {
 
   //保存最后播放的那首歌和已经对应的播放列表
   saveLastPlayList() {
-    // 确保所有字段都被保存,特别是sampleRate和mimeType
-    if (this.currentSong) {
-      // 打印当前歌曲的采样率和MIME类型值,用于调试
-      console.info(`保存歌曲信息 - 采样率: ${this.currentSong.sampleRate}, MIME类型: ${this.currentSong.mimeType}`);
-      
-      // 将完整对象保存到LastMusicInfo
-      PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
-    }
-    
+
+    PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
     PreferencesUtil.putSync('LastMusicList', this.songList)
+
   }
 
   //添加播放历史记录
@@ -9022,10 +8919,8 @@ function cutPopupBuilder(dataBu: BubbleBean) {
         ListItem() {
           Row() {
             Column() {
-              // Image($r('app.media.music_group'))
-              SymbolGlyph($r('sys.symbol.identify_song'))
+              Image($r('app.media.music_group'))
                 .height(28)
-                .fontColor([$r('app.color.img_color')])
                 .alignSelf(ItemAlign.Center)
 
             }
@@ -9062,4 +8957,3 @@ function cutPopupBuilder(dataBu: BubbleBean) {
 
 }
 
-