【问题标题】:ionic cordova get all mp3 files from sdcardionic cordova 从 sdcard 获取所有 mp3 文件
【发布时间】:2023-03-12 19:27:01
【问题描述】:

我正在开发一个音乐应用程序,我需要从 android 设备中检索所有 mp3 文件。我如何使用 ionic 和 cordova 来做到这一点?

我曾尝试使用cordova 文件插件,但我什至找不到列出目录中所有文件的方法。请帮忙。

 window.resolveLocalFileSystemURI(cordova.file.externalRootDirectory, function(fileSystem) {
   var directoryReader = fileSystem.createReader();
   directoryReader.readEntries(function(entries) {
     //alert(JSON.stringify(directoryReader));
     for(i=0;i<entries.length;i++)
     {
       alert(JSON.stringify(entries[i].name));

     }
     //alert(entries);
     //console.log(entries);
   });
 });

上面的代码只是给出了sd卡中的目录名。我需要一个逻辑来从所有目录和子目录中查找 mp3 文件。

【问题讨论】:

    标签: cordova ionic-framework filesystems ionic mp3


    【解决方案1】:

    如果有人想知道如何在 ionic2/3 上执行此操作,我们可以使用 cordova-plugin-file 从系统中检索所有文件。

    首先安装cordova-file-plugin。

    将此插件添加到您应用的模块中。

    然后像这样在任何你想要的地方使用它。

    import { FilePath } from '@ionic-native/file-path';
    import { File } from '@ionic-native/file';
    constructor(....
                , public filePath: FilePath
                , public platform: Platform
                , public file: File ) {
        this.platform.ready().then(() => {
          //the first parameter file.externalRootDirectory is for listing all files on application's root directory
          //The second parameter is the name of the folder. You can specify the nested folder here. e.g. 'Music/Coldplay'
          file.listDir(file.externalRootDirectory, '').then((result) => {
            for(let item of result)
            {
              if(item.isDirectory == true && item.name != '.' && item.name!= '..')
              {
                this.getFileList(item.name);//Get all the files inside the folder. recursion will probably be useful here.
              }
              else if (item.isFile == true)
              { 
                //File found
                this._fileList.push({
                  name: item.name,
                  path: item.fullPath
                });
              }
            }
          },
          (error) => {
            console.log(error);
          });      
        })
      }
    
      public getFileList(path: string): any
      {
        let file = new File();
        this.file.listDir(file.externalRootDirectory, path)
        .then((result)=>{
          for(let item of result)
          {
            if(item.isDirectory == true && item.name != '.' && item.name != '..')
            {
              this.getFileList(path + '/' + item.name);
            }
            else
            {
              this._fileList.push({
                name: item.name,
                path: item.fullPath
              })
            }
          }
        },(error)=>{
          console.log(error);
        })
      }
    

    **您可以通过在提取过程中某处比较扩展类型来过滤音频文件

    Complete cordova documentation

    Ionic documentation

    【讨论】:

      【解决方案2】:

      此例程将列出所选文件系统中的所有文件和文件夹。

          import { File } from "@ionic-native/file";
          import { Diagnostic } from "@ionic-native/diagnostic";
      
          constructor(
              ...
              public file: File,
              public diagnostic: Diagnostic
              ){
      
      
        // -------------------------
        listFileSys( which){
      
          // <which> chooses the file system - see switch below
          this.jcDebug += "\n" + "listFileSysSKOFLO(" + which + ")";
      
          let fileSysArray = [];
          let basePath = "";
      
          let tag = "unknown";
      
          // ************** RECURSE *************
          let jcListDir = (thisDir)=>{
      
            tag = "jcListDir: [" + thisDir + "]";
      
            this.file.listDir(basePath, thisDir)
            .then( (data)=>{
              tag = "listDir:" + thisDir;
              this.jcError += "\n" + tag + ":" + JSON.stringify( data);
              for( let ii = 0; ii < data.length; ii += 1){
                this.jcError += "\n" + data[ii].name + (data[ii].isDirectory? " [D]" : " [F]");
      
                let currentPath = thisDir;
                currentPath += (currentPath.length ? "/" : "");
                currentPath += data[ii].name;
                this.jcError += "\n" + "currentPath:" + currentPath;
      
                fileSysArray.push( currentPath);
      
                if( data[ii].isDirectory && ok2recurse){
                  jcListDir( currentPath);         // RECURSE !!!
                }
              }
            }, (errData)=>{
              tag = "listDir";
              this.jcError += "\n" + tag + ":ERR:" + JSON.stringify( errData);
            });
          };
          // ************** RECURSE *************
      
          // ***********************
          let runListDir = ()=>{
              this.jcDebug += "\n" + "basePath:" + basePath;
      
              // !!! START listing from basePath !!!
              jcListDir( ".");
          }
      
          // ***********************
          switch( which)
          {
            case 1:
              this.diagnostic.getExternalSdCardDetails()
              .then( (data) => {
                this.jcDebug += "\n" + "sd:" + JSON.stringify( data);
                this.jcDebug += "\n" + "Number of cards: " + data.length;
                for( let ii = 0; ii < data.length; ii += 1){
                  let thisElem = data[ii];
                  if( thisElem.type.toLowerCase() === "application" && thisElem.canWrite){
                    basePath = thisElem.filePath;
                    break;
                  }
                }
                if( !basePath){
                  this.jcDebug += "\n" + "no SD card found";
                  return;
                }
                runListDir();
              }, (errData)=>{
                tag = "getExternalSdCardDetails";
                this.jcError += "\n" + tag + ":ERR:" + JSON.stringify( errData);
              });
            break;
            case 2:
              basePath = this.file.externalDataDirectory;
              this.jcError += "\n" + "externalDataDirectory:" + basePath;
              runListDir();
              break;
            case 3:
              basePath = this.file.dataDirectory;
              this.jcError += "\n" + "dataDirectory:";
              runListDir();
              break;
            default:
              alert( "which???:" + which);
              return;
          }
      
          // wait for all to comnplete, then show
          // assume 1000 ms is adequate delay per promise
          let lastFileSysLen = -1
          let checkCount = 30; // max 30 * 1000 ms = 30 seconds
      
          // ************** RECURSE *************
            let checkComplete = () => {
            this.jcDebug += "\n" + "checkComplete " + checkCount + " [" + fileSysArray.length + "]";
            setTimeout( ()=>{
      
              // fileSysArr length stable?
              if( fileSysArray.length === lastFileSysLen){
                checkCount = 0;
              }
              lastFileSysLen = fileSysArray.length;
      
              checkCount -= 1;
              if( checkCount > 0){
                checkComplete();    // recurse
              } else {
      
                // STOP !!! and show FileSysArray
                this.jcInfo += "\n" + "show FileSysArray";
                this.jcInfo += "\n" + "fileSysArray.length = " + " [" + fileSysArray.length + "]";
      
                fileSysArray.sort();
      
                for( let elem of fileSysArray){
                  this.jcInfo += "\n" + elem;
                }
              }
            }, 1000);
          };
          // ************** RECURSE *************
          checkComplete();
        }
      

      必须有更好的方法来确定承诺何时全部解决......

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-05
        • 1970-01-01
        • 2016-06-20
        • 1970-01-01
        • 2011-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多