begin process at 2008 05 17 08:15:10
1 173 920 membres
52 nouveaux aujourd'hui
13 973 membres club

Vous ne trouvez pas de réponse à votre problème ? Alors posez la question dans le forum.
Souvenez-vous qu'il n'y a jamais de question bête, mais rester dans l'ignorance parce que l'on n'ose pas poser une question, ça c'est une erreur !

GÉNÉRATEUR DE PLAYLIST M3U


Information sur la source

Catégorie :Applications Source .NET ( DotNet ) Classé sous : géneréteur, playlist, generator, fichier-M3U Niveau : Débutant Date de création : 20/10/2007 Date de mise à jour : 26/10/2007 19:22:14 Vu / téléchargé: 5 082 / 150

Note :
4 / 10 - par 1 personne
4,00 / 10

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

Commentaire sur cette source (8)
Ajouter un commentaire et/ou une note

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

  • 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);
  • }
  • }
  • }
  • }
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 !
Pour les "Membres Club", vous pouvez télécharger directement un fichier contenu dans le zip sans télécharger le zip en entier !

Télécharger le zip

20 octobre 2007 11:44:59 :
J'ai juste retiré la ligne suivant qui était totalement inutile : using System.Linq;
26 octobre 2007 19:22:15 :
Ajout des portées des variables de classe. Mise en place du DataBinding sur la Cbo_Format.
  • signaler à un administrateur
    Commentaire de sebmafate le 22/10/2007 10:12:45 administrateur CS

    Bien mais... (y a toujours un mais avec moi :p)
    - Pourquoi ne pas avoir déporté le traitement dans une classe dédiée ?
    - Il me semblait que j'avais posté une source pour les Enums dans les ComboBoxes... mais je ne la retrouve pas... fait une recherche sur le forum, je l'ai fournit à moultes reprises... l'idée est d'éviter les lignes :
                    switch (Cbo_format.SelectedText)
                    {
                        case "M3U": Format = FormatPlaylist.M3U;
                            break;
                        case "WPL": Format = FormatPlaylist.WPL;
                            break;
                    }
    - Il manque les "portées" dans la déclaration de tes variables de classe...

  • signaler à un administrateur
    Commentaire de Arthenius le 22/10/2007 14:22:03

    sympa jeune padawan ;)

  • signaler à un administrateur
    Commentaire de bidou_01 le 22/10/2007 16:16:51

    Merci pour les critiques Sebmafate ;)
    Je corrige ça dès que j'ai un peu de temps :)

  • signaler à un administrateur
    Commentaire de bidou_01 le 26/10/2007 19:26:13

    Sebmafate :

    - Pourquoi ne pas avoir déporté le traitement dans une classe dédiée ?
    Honnêtement, je n'ai pas de réponse spéciale à cette question.

    Sinon les portées sont ajoutés, et j'ai utilisé le databinding pour la Cbo, mais je ne sais pas si c'est vraiment la meilleur solution. Je me suis inspriré d'une de tes sources ou tu utilisais une ArrayList.

  • signaler à un administrateur
    Commentaire de sebmafate le 26/10/2007 19:31:38 administrateur CS

    Bien les modifications...
    Quand je disais "déporté", c'était dédié une classe pour la génération de la liste... en gros, normalement un formulaire ne doit faire qu'afficher les données... pas les traiter ;)

  • signaler à un administrateur
    Commentaire de bidou_01 le 26/10/2007 20:15:53

    J'avais bien compris la question :) Mais, je ne vois pas vraiment quoi y répondre. Quand tu dis " normalement un formulaire ne doit faire qu'afficher les données" est-ce une convention à prendre, ou y a-t-il réellement un gain au niveau du programme à part, c'est vrai, une meilleur clarté dans le dev ;)

  • signaler à un administrateur
    Commentaire de ricklekebekoi le 02/11/2007 04:22:12 4/10

    En fait, c'est la base de tout.
    Imagine que tu cré ensuite une 2e form dans lequel tu doivent aussi gerer des playlist, forcement, le code sera dédoublé pour certaine partie, chose évitée si tu fait appel a une classe commune

  • signaler à un administrateur
    Commentaire de soldier8514 le 17/01/2008 19:44:02

    tkt po bidou_01 , ton code est une très bonne source d'info

Ajouter un commentaire

Discussions en rapport avec ce code source

Appels d'offres

Pub



CalendriCode

Mai 2008
LMMJVSD
   1234
567891011
12131415161718
19202122232425
262728293031 

VS Express FR Gratuit !

VS Express en français et 100% gratuit !

Téléchargements

Boutique

Boutique de goodies CodeS-SourceS