list folders containing mp3 files using the Capacitor Filesystem

15 Views Asked by At

I'm trying to list folders containing mp3 files using the Capacitor Filesystem plugin in an Ionic project. However, I'm encountering issues with the 'path' and 'endsWith' usage, as it seems to return a mix of string and FileInfo types.

Could anyone help me understand why this approach doesn't work and how I might resolve this issue?

Thank you for your assistance.

import { Injectable } from '@angular/core';
import { Directory, Filesystem } from '@capacitor/filesystem';

@Injectable({
  providedIn: 'root'
})
export class MusicScannerService {
  constructor() { }

  public async scanFoldersWithMp3(directory: string = ''): Promise<string[]> {
    let foldersWithMp3: string[] = [];
    await this.scanDirectory(directory, foldersWithMp3);
    return foldersWithMp3.filter((value, index, self) => self.indexOf(value) === index); // Filtrer les doublons
  }

  private async scanDirectory(path: string, foldersWithMp3: string[]): Promise<void> {
    try {
      const result = await Filesystem.readdir({
        directory: Directory.ExternalStorage,
        path: path
      });

      for (const fileName of result.files) {
        const fullPath = path ? `${path}/${fileName}` : fileName;
        const stat = await Filesystem.stat({
          directory: Directory.ExternalStorage,
          path: fullPath
        });

        if (stat.type === 'directory') {
          // Si c'est un dossier, continuer le scan récursivement
          await this.scanDirectory(fullPath, foldersWithMp3);
        } else if (fileName.endsWith('.mp3')) {
          // Si un fichier MP3 est trouvé, ajouter le dossier parent à la liste
          if (!foldersWithMp3.includes(path)) {
            foldersWithMp3.push(path);
          }
        }
      }
    } catch (error) {
      console.error(`Erreur lors du scan du dossier ${path}:`, error);
    }
  }
}

0

There are 0 best solutions below