Générateur de playlist m3u

Description

Cet outils permet de générer des playlist en M3U. On précise un répertoire à scanner, un répertoire de sortie et on lance la génération. Le programme va alors scanner récursivement les dossiers et créer un fichier M3U contenant vos fichier musicaux pour chaque dossier trouvé !

Source / Exemple :


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
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
        protected internal Thread threadGenerateur;
        //délégué pour update la progress bar
        protected internal delegate void MaJProgressBar(int pourcentage);
        //event de maj progressbar
        protected internal event MaJProgressBar UpdateProgressBar;
        //format playlist (seul M3U implémenté pour l'instant)
        protected internal static FormatPlaylist Format;
        //répertoire à scanner
        protected internal static string Repertoire_a_Scanner;
        //répertoire de sortie
        protected internal static string Repertoire_Sortie;

        //enum formt de playlist
        protected internal enum FormatPlaylist
        {
            M3U, WPL
        }
        //liste contenant les formats
        protected internal List<FormatPlaylist> listeFormat;

        //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
            {
                /* OLD
                Cbo_format.Items.Add("M3U");
                //Cbo_format.Items.Add("WPL");
                Cbo_format.SelectedIndex = 0;*/

                /* NEW */
                listeFormat = new List<FormatPlaylist>();
                listeFormat.Add(FormatPlaylist.M3U);
                Cbo_format.DataSource = listeFormat;

                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
            {
                /* OLD
                switch (Cbo_format.SelectedText)
                {
                    case "M3U": Format = FormatPlaylist.M3U;
                        break;
                    case "WPL": Format = FormatPlaylist.WPL;
                        break;
                } */

                /* NEW */
                Format = (FormatPlaylist)Cbo_format.SelectedItem;
                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)
        {
            try
            {
                if (pourcentage != 100)
                {
                    toolProgressBar.Value = pourcentage;
                }
                else
                {
                    toolProgressBar.Value = pourcentage;
                    toolstriplbl_status.Text = "Génération terminée!";
                }
            }
            catch (Exception xcp)
            {
                MessageBox.Show(xcp.Message);
            }
        }

        /// <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 = Directory.GetDirectories(Repertoire_a_Scanner);
                        int nbDirectory = directories.Length;
                        int count = 0;
                        writeM3U(Repertoire_a_Scanner);
                        foreach (string directory in directories)
                        {
                            writeM3U(directory);
                            count++;
                            int percent = (count * 100) / nbDirectory;
                            object[] param = new object[1];
                            param[0] = percent;
                            Invoke(UpdateProgressBar, param);
                        }
                        object[] param2 = new object[1];
                        param2[0] = 100;
                        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));
                                writer.WriteLine(Path.GetFullPath(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);
            }
        }

        
    }
}

Conclusion :


Bref, un outil sans grand exploit technique, mais pratique pour les fénéant comme moi qui n'ont pas envie de Drag n Drop leurs fichiers pour créer leur playlist une par une !

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.