Générateur de playlist m3u - amélioré

Description

J'ai modifié le code bidou_01 de façon:
- à effectuer une recherche récursive à partir du répertoire à scanner afin de ne pas se limiter au niveau 1
- à pouvoir générer des playlists avec des chemins relatifs (case à cocher)
- à informer l'utilisateur sur le nombre de playlists générées par l'intermédiaire de la barre de statut
- à ajouter l'icône application.

Source / Exemple :


using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
using System.IO;

namespace GenerateurM3U
{
    public partial class MainForm : Form
    {
        //thread s'occuppant de la génération
        Thread threadGenerateur;
        //délégué pour update la progress bar
        delegate void MaJProgressBar(int pourcentage, int nb_playlists);
        //event de maj progressbar
        event MaJProgressBar UpdateProgressBar;
        //format playlist (seul M3U implémenté pour l'instant)
        static FormatPlaylist Format;
        //répertoire à scanner
        static string Repertoire_a_Scanner;
        //répertoire de sortie
        static string Repertoire_Sortie;

        //enum formt de playlist
        enum FormatPlaylist
        {
            M3U, WPL
        }

        //constructeur par défaut
        public MainForm()
        {
            try
            {
                InitializeComponent();
            }
            catch (Exception xcp)
            {
                MessageBox.Show(xcp.Message);
            }
        }

        /// <summary>
        ///     Appelée lors du clic sur le lbl url dans la status strip
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolstriplbl_url_Click(object sender, EventArgs e)
        {
            try
            {
                Process.Start("http://www.corioland.eu");
            }
            catch (Exception xcp)
            {
                MessageBox.Show(xcp.Message);
            }
        }

        /// <summary>
        ///     affiche le curseur "pointeur" lors du survol de l'url
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolstriplbl_url_MouseHover(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.Hand;
            }
            catch (Exception xcp)
            {
                MessageBox.Show(xcp.Message);
            }
        }

        /// <summary>
        ///     affiche le curseur par défaut lorsque la souris sort de la zone de l'url
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolstriplbl_url_MouseLeave(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.Default;
            }
            catch (Exception xcp)
            {
                MessageBox.Show(xcp.Message);
            }
        }
        /// <summary>
        ///     méthode appelée au chargement de la form.
        ///     initialise la combo box et le folderBrowser.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                Cbo_format.Items.Add("M3U");
                //Cbo_format.Items.Add("WPL");
                Cbo_format.SelectedIndex = 0;
                folderBrowser = new FolderBrowserDialog();
            }
            catch (Exception xcp)
            {
                MessageBox.Show(xcp.Message);
            }
        }

        /// <summary>
        ///     chois du dossier su le bouton parcourir pour choisir le dossier à scanner
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_parcourir_Click(object sender, EventArgs e)
        {
            try
            {
                if (folderBrowser.ShowDialog() == DialogResult.OK)
                {
                    Tb_dossier.Text = folderBrowser.SelectedPath;
                    errorProvider.SetError(Tb_dossier, "");
                }
            }
            catch (Exception xcp)
            {
                MessageBox.Show(xcp.Message);
            }
        }

        /// <summary>
        ///     méthode appelée lors du clic sur le bouton générer.
        ///     Vérifie les infos entrées par l'utilisateur
        ///     Lance le thread de génération si les infos sont ok!
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_generer_Click(object sender, EventArgs e)
        {
            try
            {
                switch (Cbo_format.SelectedText)
                {
                    case "M3U": Format = FormatPlaylist.M3U;
                        break;
                    case "WPL": Format = FormatPlaylist.WPL;
                        break;
                }

                bool test = true;

                if (Tb_dossier.Text.Trim().Length == 0)
                {
                    test = false;
                    errorProvider.SetError(Tb_dossier, "Merci de saisir un chemin de fichier à explorer avant de commencer la génération!");
                }
                if (textBox_chemin_gene.Text.Trim().Length == 0)
                {
                    test = false;
                    errorProvider.SetError(textBox_chemin_gene, "Merci de saisir un chemin de fichier où générer les playlists!");
                }

                if (test)
                {
                    toolstriplbl_status.Text = "Génération en cours...";
                    toolProgressBar.Minimum = 0;
                    toolProgressBar.Maximum = 100;
                    errorProvider.SetError(Tb_dossier, "");
                    Repertoire_a_Scanner = Tb_dossier.Text;
                    Repertoire_Sortie = textBox_chemin_gene.Text;
                    UpdateProgressBar += new MaJProgressBar(MainForm_UpdateProgressBar);
                    threadGenerateur = new Thread(new ThreadStart(GenerePlaylist));
                    threadGenerateur.Start();
                }
            }
            catch (Exception xcp)
            {
                MessageBox.Show(xcp.Message);
            }
        }

        /// <summary>
        ///     Méthode appelée par le délégué de maj de la progress bar.
        /// </summary>
        /// <param name="pourcentage"></param>
        void MainForm_UpdateProgressBar(int pourcentage, int nb_playlists)
        {
            try
            {
                toolProgressBar.Value = pourcentage;
                toolstriplbl_status.Text = nb_playlists.ToString() + " playlists générées.";
            }
            catch (Exception xcp)
            {
                MessageBox.Show(xcp.Message);
            }
        }

        /// <summary>
        ///     Compte le nombre de dossier contenant des fichiers audio
        /// </summary>
        private string[] TrouvePlayLists(string directory)
        {
            string[] playlists = new string[0];
            try
            {
                StringCollection paths = new StringCollection();
                string[] files = Directory.GetFiles(directory);
                string[] directories = Directory.GetDirectories(directory);
                bool canWrite = false;

                foreach (string file in files)
                {
                    string ext = Path.GetExtension(file).ToUpper();
                    if (ext == ".MP3" || ext == ".WMA" || ext == ".WAV" || ext == ".OGG")
                    {
                        canWrite = true;
                    }
                }

                if (canWrite)
                {
                    paths.Add(directory);
                }
                foreach (string rep in directories)
                {
                    paths.AddRange(TrouvePlayLists(rep));
                }
                playlists = new string[paths.Count];
                paths.CopyTo(playlists, 0);
            }
            catch (Exception xcp)
            {
                Console.WriteLine(xcp.Message);
            }
            return playlists;
        }

        /// <summary>
        ///     Méthode appelée par le thread de génération de la playlist
        /// </summary>
        private void GenerePlaylist()
        {
            try
            {
                switch(Format)
                {
                    case FormatPlaylist.M3U:
                        string[] directories = TrouvePlayLists(Repertoire_a_Scanner);
                        int nbDirectory = directories.Length;
                        int count = 0;
                        foreach (string directory in directories)
                        {
                            writeM3U(directory);
                            count++;
                            int percent = (count * 100) / nbDirectory;
                            object[] param = new object[2];
                            param[0] = percent;
                            param[1] = count;
                            Invoke(UpdateProgressBar, param);
                        }
                        object[] param2 = new object[2];
                        param2[0] = 100;
                        param2[1] = nbDirectory;
                        Invoke(UpdateProgressBar, param2);
                        break;
                }
            }
            catch (Exception xcp)
            {
                MessageBox.Show(xcp.Message);
            }
        }

        /// <summary>
        ///     Méthode chargé de l'écriture du fichier M3U
        /// </summary>
        /// <param name="directory"></param>
        private void writeM3U(string directory)
        {
            try
            {
                string[] files = Directory.GetFiles(directory);
                string[] directories = Directory.GetDirectories(directory);

                if (files.Length > 0)
                {
                    bool canWrite = false;
                    foreach (string file in files)
                    {
                        string ext = Path.GetExtension(file).ToUpper();
                        if (ext == ".MP3" || ext == ".WMA" || ext == ".WAV" || ext == ".OGG")
                        {
                            canWrite = true;
                        }
                    }

                    if (canWrite)
                    {
                        string directoryName = Path.GetFileName(directory);
                        FileStream fs = new FileStream(Repertoire_Sortie + "\\" + directoryName + ".m3u", FileMode.OpenOrCreate);
                        StreamWriter writer = new StreamWriter(fs, Encoding.Default);
                        writer.WriteLine("#EXTM3U");
                        foreach (string file in files)
                        {
                            string ext = Path.GetExtension(file).ToUpper();
                            if (ext == ".MP3" || ext == ".WMA" || ext == ".WAV" || ext == ".OGG")
                            {
                                writer.WriteLine("#EXTINF:0," + Path.GetFileName(file));
                                if (chk_Relatif.Checked == false)
                                {
                                    writer.WriteLine(Path.GetFullPath(file));
                                }
                                else
                                {
                                    writer.WriteLine(PathUtil.RelativePathTo(Repertoire_Sortie, file));
                                }
                               writer.WriteLine();
                            }
                        }
                        writer.Flush();
                        writer.Close();
                        fs.Close();
                    }

                    foreach (string rep in directories)
                    {
                        writeM3U(rep);
                    }
                    
                }
                
            }
            catch (Exception xcp)
            {
                Console.WriteLine(xcp.Message);
            }
        }

        /// <summary>
        ///     Méthode appelée lors du clic sur le bouton parcourir pour choisir le dossier de sortie des playlists
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_brows_gene_Click(object sender, EventArgs e)
        {
            try
            {
                if (folderBrowser.ShowDialog() == DialogResult.OK)
                {
                    textBox_chemin_gene.Text = folderBrowser.SelectedPath;
                    errorProvider.SetError(textBox_chemin_gene, "");
                }
            }
            catch (Exception xcp)
            {
                Console.WriteLine(xcp.Message);
            }
        }

        
    }
    public class PathUtil
    {
        /// <summary>
        /// Creates a relative path from one file
        /// or folder to another.
        /// </summary>
        /// <param name="fromDirectory">
        /// Contains the directory that defines the
        /// start of the relative path.
        /// </param>
        /// <param name="toPath">
        /// Contains the path that defines the
        /// endpoint of the relative path.
        /// </param>
        /// <returns>
        /// The relative path from the start
        /// directory to the end path.
        /// </returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static string RelativePathTo(
            string fromDirectory, string toPath)
        {
            if (fromDirectory == null)
                throw new ArgumentNullException("fromDirectory");

            if (toPath == null)
                throw new ArgumentNullException("toPath");

            bool isRooted = Path.IsPathRooted(fromDirectory)
                && Path.IsPathRooted(toPath);

            if (isRooted)
            {
                bool isDifferentRoot = string.Compare(
                    Path.GetPathRoot(fromDirectory),
                    Path.GetPathRoot(toPath), true) != 0;

                if (isDifferentRoot)
                    return toPath;
            }

            StringCollection relativePath = new StringCollection();
            string[] fromDirectories = fromDirectory.Split(
                Path.DirectorySeparatorChar);

            string[] toDirectories = toPath.Split(
                Path.DirectorySeparatorChar);

            int length = Math.Min(
                fromDirectories.Length,
                toDirectories.Length);

            int lastCommonRoot = -1;

            // find common root
            for (int x = 0; x < length; x++)
            {
                if (string.Compare(fromDirectories[x],
                    toDirectories[x], true) != 0)
                    break;

                lastCommonRoot = x;
            }
            if (lastCommonRoot == -1)
                return toPath;

            // add relative folders in from path
            for (int x = lastCommonRoot + 1; x < fromDirectories.Length; x++)
                if (fromDirectories[x].Length > 0)
                    relativePath.Add("..");

            // add to folders to path
            for (int x = lastCommonRoot + 1; x < toDirectories.Length; x++)
                relativePath.Add(toDirectories[x]);

            // create relative path
            string[] relativeParts = new string[relativePath.Count];
            relativePath.CopyTo(relativeParts, 0);

            string newPath = string.Join(
                Path.DirectorySeparatorChar.ToString(),
                relativeParts);

            return newPath;
        }

    }
}

Conclusion :


Je n'ai pas trouvé d'outils freeware ou opensource effectuant cette opération. Donc si cela peut servir ...
J'ai laissé une version release compilée dans le zip.... et créer un patch afin de pouvoir répercuter les modifs dans un projet dérivé.
Pour les utilisateurs intéressés, il suffit de copier le dossier GenerateurM3U\GenerateurM3U\bin\Release sur le disque système et d'installer .NET (évidement !) pour profiter de l'outil

Codes Sources

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.