Foro de elhacker.net

Programación => .NET (C#, VB.NET, ASP) => Mensaje iniciado por: TickTack en 12 Octubre 2017, 09:51 am



Título: C# - No puedo reproducir la siguiente cancion
Publicado por: TickTack en 12 Octubre 2017, 09:51 am
Hola,

hice un listBox en donde se ponen todos los nombres de las canciones que agrego mediante el control button. Pero cuando termina la cancion no se reproduce la siguiente.

Les muestro como trate de que se reproduciera la siguiente cancion cuando termine una con este codigo:

Código:
private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
        {
            if (e.newState == 8)
            {
                index = index + 1;

                if (index - 1 < listBox1.Items.Count)
                {
                    axWindowsMediaPlayer1.URL = list2[list1.IndexOf(listBox1.Items[index].ToString())];
                }
            }
        }

Se supone que deberia funcionar. Pero para evitar confusiones les mostrare todo el codigo:

Código:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Player
{
    public partial class Form1 : Form
    {
        List<string> list1 = new List<string>();
        List<string> list2 = new List<string>();
        List<string> list3 = new List<string>();
        Timer timer1 = new Timer();
        int index = 0;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
            ofd.Multiselect = true;
            ofd.ShowDialog();

            foreach (var file in ofd.SafeFileNames)
            {
                listBox1.Items.Add(file);
                list1.Add(file);
                listBox1.Sorted = true;
            }

            foreach (var file in ofd.FileNames)
            {
                list2.Add(file);
            }


        }

        private void Form1_Load(object sender, EventArgs e)
        {
           
        }

        private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            index = listBox1.SelectedIndex;
            axWindowsMediaPlayer1.URL = list2[list1.IndexOf(listBox1.GetItemText(listBox1.SelectedItem))];
        }

        private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
        {
            if (e.newState == 8)
            {
                index = index + 1;

                if (index - 1 < listBox1.Items.Count)
                {
                    axWindowsMediaPlayer1.URL = list2[list1.IndexOf(listBox1.Items[index].ToString())];
                }
            }
        }
    }
}

Alguien me puede ayudar por favor?


Gracias y saludos


Título: Re: C# - No puedo reproducir la siguiente cancion
Publicado por: Eleкtro en 12 Octubre 2017, 13:50 pm
1.
No estás liberando la instancia de una clase que implementa la interfaz IDisposable...
Citar
Código
  1. OpenFileDialog ofd = new OpenFileDialog();

2.
Estás usando una colección genérica de tipo List para almacenar las rutas absolutas de unos archivos, y luego otra lista adicional para almacenar los nombres de archivo. Tener dos colecciones distintas para practicamente la misma finalidad (puesto que los nombres de archivo son parte de la ruta absoluta del archivo) es algo completamente innecesario con lo que solo conseguirás escribir un código espagueti (confuso y destructurado) más si les asignas nombres como "list1", "list2" y "list3"...

Hay que mejorar las nomenclaturas de los miembros.

3.
Debido a que estás representando una colección de elementos (nombres de archivos), en lugar de utilizar el método ListBox.Add() deberías utilizar el método ListBox.AddRange() para mejorar el rendimiento de la aplicación y la respuesta de la UI. Con cada llamada individual que haces a ListBox.Add() el control envia mensajes de ventana para redibujarse, y eso para añadir 20 canciones no pasa nada, pero si fuesen muchas más pues...acabarías bloqueando la UI por momentos.

4.
Estás reasignando el mismo valor a la propiedad ListBox.Sorted en el controlador button1_Click, esto son instrucciones de más, algo innecesario. Con asignarle el valor a la propiedad una única vez al cargar el control es suficiente.

5..
No estás comprobando el resultado del diálogo cuando seleccionas archivos... ¿qué ocurre si el usuario cancela la selección?. debes comprobarlo...

6..
cuando termina la cancion no se reproduce la siguiente.

Prueba a invocar la funcionalidad de reproducir...
Código
  1. this.axWindowsMediaPlayer1.Ctlcontrols.play();

  • AxWindowsMediaPlayer.URL property (https://msdn.microsoft.com/en-us/library/windows/desktop/dd562470(v=vs.85).aspx)
  • AxWindowsMediaPlayer.Ctlcontrols property (https://msdn.microsoft.com/en-us/library/windows/desktop/dd562401(v=vs.85).aspx)

7..
Citar
Código
  1. int index = 0;
  2. ...
  3. void ... {
  4.    index = index + 1;
  5.    if (index - 1 < listBox1.Items.Count) {
  6.        axWindowsMediaPlayer1.URL = list2[list1.IndexOf(listBox1.Items[index].ToString())];
  7.    }
  8. }

En lugar de la necesidad de declarar un contador y comprobar el estado del reproductor e ir reasignando a cada rato el valor de la propiedad URL para reproducir la siguiente canción, en lugar de todo eso algo más simple sería que añadieses los elementos del ListBox (las rutas completas de los archivos a reproducir) en una lista de reproducción ( playlist.m3u ) para que el WMP las vaya reproduciendo una tras otra y no tengas que hacer más...

Tienes dos opciones para ello, puedes escribir un archivo de lista de reproducción m3u (no es complicado, es un formato muy sencillo):
  • https://en.wikipedia.org/wiki/M3U (https://en.wikipedia.org/wiki/M3U)

O bien puedes puedes crear una lista de manera guiada para usarlo en la instancia actual del WMP mediante la interfáz IWMPPlaylist
  • AxWindowsMediaPlayer.newPlaylist method | MSDN (https://msdn.microsoft.com/en-us/library/windows/desktop/dd562448(v=vs.85).aspx)
  • IWMPPlaylist interface | MSDN (https://msdn.microsoft.com/en-us/library/windows/desktop/dd563581(v=vs.85).aspx)

8..  
Citar
Código:
if (e.newState == 8)

¿Has verificado que el valor de la propiedad NewState sea realmente 8 al terminar de reproducir la canción?. La documentación oficial en la MSDN no recomienda que un algoritmo se base en la "predicción" de los estados del reproductor debido a que al parecer son un poco...impredecibles.

Cita de: MSDN
Remarks

Windows Media Player states are not guaranteed to occur in any particular order. Furthermore, not every state necessarily occurs during a sequence of events. You should not write code that relies upon state order.

  • AxWindowsMediaPlayer.PlayStateChange Event | MSDN (https://msdn.microsoft.com/en-us/library/windows/desktop/dd562460(v=vs.85).aspx)

Nota: En la página de la MSDN tienes un ejemplo extendido para depurar/testear el estado actual del reproductor.



En general todo el código que tienes ahora mismo lo puedes mejorar y simplificar / refactorizar a algo parecido a esto:

Código
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Windows.Forms;
  6.  
  7. public sealed class Form1 : Form {
  8.  
  9.    const int WMP_MediaEnded = 0x8;
  10.    private readonly SortedList<string, string> files; // { Key=file_name, Value=full_path }
  11.  
  12.    private void Form_Load(object sender, EventArgs e) {
  13.        this.files = new SortedList<string, string>(StringComparer.Ordinal);
  14.        this.listBox1.ValueMember = "key"; // file names
  15.    }
  16.  
  17.    private void Button1_Click(object sender, EventArgs e) {
  18.        using (OpenFileDialog ofd = new OpenFileDialog { Multiselect = true }) {
  19.            ofd.ShowDialog();
  20.  
  21.            DialogResult result = ofd.ShowDialog();
  22.            if (result == DialogResult.OK) {
  23.                foreach (string filepath in ofd.FileNames) {
  24.                    this.files.Add(Path.GetFileName(filepath), filepath);
  25.                }
  26.                this.listBox1.BeginUpdate();
  27.                this.listBox1.DataSource = this.files.ToList();
  28.                this.listBox1.EndUpdate();
  29.            } // if
  30.        } // using
  31.    }
  32.  
  33.    private void ListBox1_DoubleClick(object sender, EventArgs e) {
  34.        this.PlaySongFile(((ListBox)sender).SelectedIndex);
  35.    }
  36.  
  37.    private void PlaySongFile(int fileIndex) {
  38.        ListBox lb = this.listBox1;
  39.        lb.SetSelected(fileIndex, true); // Select the item/song name that is being played.
  40.  
  41.        KeyValuePair<string, string> file = (KeyValuePair<string, string>)lb.SelectedItem;
  42.        this.axWindowsMediaPlayer1.URL = file.Value; // full file path
  43.        this.axWindowsMediaPlayer1.Ctlcontrols.play();
  44.    }
  45.  
  46.    private void AxWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e) {
  47.  
  48.        if (e.newState == WMP_MediaEnded) {
  49.            int selectedIndex = this.listBox1.SelectedIndex;
  50.            if (this.files.Count < (selectedIndex - 1)) {
  51.                this.PlaySongFile(selectedIndex + 1); // Play next item/song file.
  52.            }
  53.        }
  54.    }
  55.  
  56. }

Nota: Es solo un código de ejemplo para que lo adaptes a tus necesidades, falta que asocies los controladores de evento en el código, no he comprobado que funcione lo de reproducir canciones en el WMP, y tampoco he implementado la funcionalidad de la lista de reproducción ya que lo he propuesto como una mejora opcional y bueno... no voy a hacer yo todo el trabajo, jeje.

Saludos.


Título: Re: C# - No puedo reproducir la siguiente cancion
Publicado por: TickTack en 12 Octubre 2017, 18:31 pm
Hola Elektro,

1. No es lo mismo OpenFileDialog ofd = new OpenFileDialog(); que System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();?

2. Es necesario que lo que haga de esta manera ya que necesito por un lado mostrar los nombres de las canciones en el listBox y por el otro lado guardar las rutas para reproducir esas canciones. Y aunque los nombres sean partes de las rutas... separarlos, segun yo, lleva mas tiempo que el codigo espagueti.

3. Bueno eso tendre que cambiarlo. Gracias por la informacion. :)

4. Yo no veo ninguna instruccion de mas. Solamente le asigne una vez una valor a ListBox.Sorted.

5. Ay si... eso me olvide... jeje

6. Ya lo probe antes de hacer este post.

7. Ok. Quiero ir por ese camino...

8. Eso tampoco lo supe. Pero no se me da la posibilidad de escribir if (e.newState == WMP_MediaEnded) { ya que me larga error con WMP_MediaEnded. Me dice que no existe.


Si te diste cuenta del error por favor informame. Te estare my agradecido


Gracias y saludos

PD.: Tu codigo se me hizo dificil de harmonizarlo con el mio pero igual muchas gracias. (Es que tienes una forma complicada de escribir codigos, quiza por los grandes programas o codigos comerciales que ya hiciste, osea esa por esa experiencia).


Título: Re: C# - No puedo reproducir la siguiente cancion
Publicado por: Eleкtro en 12 Octubre 2017, 20:13 pm
1. No es lo mismo OpenFileDialog ofd = new OpenFileDialog(); que System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();?

Si, por supuesto, simplemente borré el nombre del namespace al citar tu código, y lo cité solamente para hacer referencia a la instrucción de tú código a la que me estaba refiriendo, pero a lo que me refería es a que debes utilizar la sentencia using para asegurarte de que el GC (Garbage Collector) libere cualquier recurso administrado y no administrado que haya sido utilizado por "X" instancia IDisposable... y así tener (o al menos intentarlo) una aplicación libre de las indeseadas fugas de consumo RAM.

Es decir:
Código
  1. using ( OpenFileDialog ofd = new OpenFileDialog() ) {
  2. // ...
  3. }
  • using Statement (C# Reference) | docs.microsoft.com (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement)

...o en su defecto puedes usar el método IDisposable.Dispose() ( OpenFileDialog.Dispose() ).
  • IDisposable.Dispose Method | MSDN (https://msdn.microsoft.com/en-us/library/system.idisposable.dispose(v=vs.110).aspx)



2. Es necesario que lo que haga de esta manera ya que necesito por un lado mostrar los nombres de las canciones en el listBox y por el otro lado guardar las rutas para reproducir esas canciones. Y aunque los nombres sean partes de las rutas... separarlos, segun yo, lleva mas tiempo que el codigo espagueti.

No, no es necesario ni tampoco lleva más tiempo en términos de esfuerzo. En mi última respuesta te mostré un código en el que utilizo una colección genérica de tipo SortedList para almacenar ambos datos... y cuyos elementos se mantienen ordenados por orden alfabético según el nombre de cada archivo agregado en o eliminado de la colección...

Como ves, es una mejora que simplifica tres funcionalidades del código original, en una sola.



3. Bueno eso tendre que cambiarlo. Gracias por la informacion. :)

Si sigues la solución que te indiqué (vease el código que compartí en mi última respuesta) entonces no necesitas usar el método Add / AddRange ya que en su lugar se utiliza la colección SortedList como datasource. Pero de todos modos la utilización del método AddRange es una mejora significativa que siempre deberías tener en cuenta cuando necesites agregar elementos manualmente a un control de tipo Lista (ListBox, ListView, DataGridView, etc).



4. Yo no veo ninguna instruccion de mas. Solamente le asigne una vez una valor a ListBox.Sorted.

Citar
Código
  1.            foreach (var file in ofd.SafeFileNames)
  2.            {
  3.                listBox1.Items.Add(file);
  4.                list1.Add(file);
  5.                listBox1.Sorted = true;
  6.            }

Fíjate bien, le estás reasignando el valor en cada iteración del búcle foreach, es decir, 'listBox1.Sorted = true' por cada elemento en 'ofd.SafeFileNames'.


Título: Re: C# - No puedo reproducir la siguiente cancion
Publicado por: Eleкtro en 12 Octubre 2017, 20:19 pm
6. Ya lo probe antes de hacer este post.

7. Ok. Quiero ir por ese camino...

De acuerdo, entonces por si te sirve de algo te muestro un algoritmo que desarrollé hace un par de años para construir listas de reproducción en formato M3U y PLS de forma sencilla. El código es un poco feo, lo escribí hace varios años, se puede refactorizar para perfeccionarlo de muchas formas para representarlo de forma más abstracta y llevar a cabo todas las modificaciones en la memoria sin realizar operaciones de lectura/escritura en el archivo, pero bueno, así lo escribí en su día cuando todavía no dominaba muchas cosas en la progamación .NET, y el caso es que funciona, que es lo importante...

NOTA INFORMATIVA:
--- EL SIGUIENTE CÓDIGO HA SIDO EXTRAIDO Y OFRECIDO DE FORMA GRATUITA A PARTIR DE MI FRAMEWORK COMERCIAL
ELEKTROKIT FRAMEWORK , EL CUAL CONTIENE UNA INFINIDAD DE UTILIDADES ENFOCADAS A UNA AMPLIA VARIEDAD DE TEMÁTICAS Y ESCENARIOS EN LA PROGRAMACIÓN .NET, COMO ÉSTE. SI QUIEREN CONOCER MÁS ACERCA DEL PRODUCTO, MIREN MI FIRMA DE USUARIO EN EL FORO. ---
---
ESTE CÓDIGO SE PUEDE USAR DE FORMA LIBRE COMO DESEEN.


Nota: Debido a que el foro tiene un límite muy reducido de caracteres, me he visto obligado a eliminar gran parte de la documentación XML ( descripciones de parámetros, etc).

Código
  1. #Region " Playlist Type "
  2.  
  3. Namespace ElektroKit.Core.Multimedia.Enums
  4.  
  5.    ''' <summary>
  6.    ''' Specifies the type of a multimedia playlist.
  7.    ''' </summary>
  8.    Public Enum PlaylistType As Integer
  9.  
  10.        ''' <summary>
  11.        ''' M3U Playlist.
  12.        ''' <para></para>
  13.        ''' <see href="http://en.wikipedia.org/wiki/M3U"/>
  14.        ''' </summary>
  15.        M3U = 0I
  16.  
  17.        ''' <summary>
  18.        ''' PLS Playlist.
  19.        ''' <para></para>
  20.        ''' <see href="http://en.wikipedia.org/wiki/PLS_%28file_format%29"/>
  21.        ''' </summary>
  22.        PLS = 1I
  23.  
  24.    End Enum
  25.  
  26. End Namespace
  27.  
  28. #End Region

Código
  1. #Region " Playlist TrackInfo "
  2.  
  3. Namespace ElektroKit.Core.Multimedia.Types
  4.  
  5.    ''' <summary>
  6.    ''' Represents a track of a multimedia playlist.
  7.    ''' </summary>
  8.    Public Structure PlaylistTrackInfo
  9.  
  10. #Region " Properties "
  11.  
  12.        ''' <summary>
  13.        ''' Gets the track index.
  14.        ''' <para></para>
  15.        ''' This value is automatically set by some of the <see cref="PlaylistEditor"/> class members,
  16.        ''' and has none effect if you change it manually.
  17.        ''' </summary>
  18.        Public Property Index As Integer
  19.  
  20.        ''' <summary>
  21.        ''' Gets or sets the file path.
  22.        ''' </summary>
  23.        Public Property Path As String
  24.  
  25.        ''' <summary>
  26.        ''' Gets or sets the track title.
  27.        ''' </summary>
  28.        Public Property Title As String
  29.  
  30.        ''' <summary>
  31.        ''' Gets or sets the track length.
  32.        ''' </summary>
  33.        Public Property Length As TimeSpan
  34.  
  35. #End Region
  36.  
  37.    End Structure
  38.  
  39. End Namespace
  40.  
  41. #End Region

Código
  1. #Region " Imports "
  2.  
  3. Imports System.Collections.ObjectModel
  4. Imports System.IO
  5. Imports System.Text
  6.  
  7. Imports ElektroKit.Core.Multimedia.Enums
  8.  
  9. #End Region
  10.  
  11. #Region " Playlist Editor "
  12.  
  13. Namespace ElektroKit.Core.Multimedia.Types
  14.  
  15.    ''' <summary>
  16.    ''' Contains methods to create and or manage the tracks defined in a multimedia playlist file.
  17.    ''' </summary>
  18.    Public NotInheritable Class PlaylistEditor
  19.  
  20. #Region " Properties "
  21.  
  22.        ''' <summary>
  23.        ''' Gets the playlist filepath.
  24.        ''' </summary>
  25.        Public ReadOnly Property FilePath As String
  26.            <DebuggerStepThrough>
  27.            Get
  28.                Return Me.filepathB
  29.            End Get
  30.        End Property
  31.        ''' ----------------------------------------------------------------------------------------------------
  32.        ''' <summary>
  33.        ''' ( Backing field )
  34.        ''' The playlist filepath.
  35.        ''' </summary>
  36.        ''' ----------------------------------------------------------------------------------------------------
  37.        Private ReadOnly filepathB As String
  38.  
  39.        ''' <summary>
  40.        ''' Gets the playlist type.
  41.        ''' </summary>
  42.        Public ReadOnly Property PlaylistType As PlaylistType
  43.            Get
  44.                Return Me.playlistTypeB
  45.            End Get
  46.        End Property
  47.        Private ReadOnly playlistTypeB As PlaylistType
  48.  
  49.        ''' <summary>
  50.        ''' Gets the text encoding of the playlist file.
  51.        ''' </summary>
  52.        Public ReadOnly Property FileEncoding As Encoding
  53.            Get
  54.                Return Me.encodingB
  55.            End Get
  56.        End Property
  57.        Private ReadOnly encodingB As Encoding
  58.  
  59.        ''' <summary>
  60.        ''' Gets a value indicating whether the text will be appended at the bottom of the playlist file.
  61.        ''' </summary>
  62.        Public ReadOnly Property Append As Boolean
  63.            <DebuggerStepThrough>
  64.            Get
  65.                Return Me.appendB
  66.            End Get
  67.        End Property
  68.        Private ReadOnly appendB As Boolean
  69.  
  70.        ''' <summary>
  71.        ''' Gets a collection that represents the tracks defined (if any) in the playlist.
  72.        ''' </summary>
  73.        Public ReadOnly Property Tracks As ReadOnlyCollection(Of PlaylistTrackInfo)
  74.            <DebuggerStepThrough>
  75.            Get
  76.                Return New ReadOnlyCollection(Of PlaylistTrackInfo)(Me.GetTracks)
  77.            End Get
  78.        End Property
  79.  
  80.        ''' <summary>
  81.        ''' Gets the amount of tracks defined in the playlist.
  82.        ''' </summary>
  83.        Public ReadOnly Property Count As Integer
  84.            <DebuggerStepThrough>
  85.            Get
  86.                Return Me.GetTracks.Count
  87.            End Get
  88.        End Property
  89.  
  90. #End Region
  91.  
  92. #Region " Constructors "
  93.  
  94.        <DebuggerNonUserCode>
  95.        Private Sub New()
  96.        End Sub
  97.  
  98.        ''' <summary>
  99.        ''' Initializes a new instance of the <see cref="PlaylistEditor"/> class.
  100.        ''' </summary>
  101.        '''
  102.        ''' <param name="playlistFile">
  103.        ''' The playlist file path.
  104.        ''' </param>
  105.        ''' <param name="playlistType">
  106.        ''' The type of the playlist.
  107.        ''' </param>
  108.        ''' <param name="createNew">
  109.        ''' If set to <see langword="True"/>,
  110.        ''' the <see cref="PlaylistEditor"/> instance will assume that the playlist file already exist,
  111.        ''' and it will append any new track entries to the bottom of the playlist file.
  112.        ''' <para></para>
  113.        ''' If set to <see langword="False"/>,
  114.        ''' the <see cref="PlaylistEditor"/> instance will assume that the playlist file does not exist,
  115.        ''' so then it will create a new playlist file.
  116.        ''' </param>
  117.        ''' <param name="fileEncoding">
  118.        ''' Optionally indicates the file encoding to perform write and read operations to the playlist file.
  119.        ''' <para></para>
  120.        ''' Default value is: <see cref="Encoding.Default"/>
  121.        ''' </param>
  122.        <DebuggerStepThrough>
  123.        Public Sub New(ByVal playlistFile As String,
  124.                       ByVal playlistType As PlaylistType,
  125.                       ByVal createNew As Boolean,
  126.                       Optional ByVal fileEncoding As Encoding = Nothing)
  127.  
  128.            Me.filepathB = playlistFile
  129.            Me.playlistTypeB = playlistType
  130.            Me.encodingB = If(fileEncoding IsNot Nothing, fileEncoding, Encoding.Default)
  131.            Me.appendB = Not createNew
  132.  
  133.            If Not (appendB) Then
  134.                Me.AddHeaders()
  135.            End If
  136.  
  137.        End Sub
  138.  
  139. #End Region
  140.  
  141. #Region " Public Methods "
  142.  
  143.        ''' <summary>
  144.        ''' Adds a new track entry in the playlist.
  145.        ''' </summary>
  146.        <DebuggerStepThrough>
  147.        Public Sub Add(ByVal filepath As String,
  148.                       Optional ByVal throwOnDuplicate As Boolean = False)
  149.  
  150.            If Not (throwOnDuplicate) AndAlso Me.Exist(filepath) Then
  151.                Throw New ArgumentException("The specified file path already exists in the playlist.",
  152.                                            paramName:="filepath")
  153.            End If
  154.  
  155.            Dim sb As New StringBuilder
  156.  
  157.            Select Case Me.playlistTypeB
  158.  
  159.                Case PlaylistType.M3U
  160.                    sb.AppendLine()
  161.                    sb.AppendLine(filepath)
  162.                    File.AppendAllText(Me.filepathB, sb.ToString(), Me.encodingB)
  163.  
  164.                Case PlaylistType.PLS
  165.                    Dim tacksCount As Integer = Me.GetPlsTrackCount()
  166.                    sb.AppendLine(File.ReadAllText(Me.filepathB, Me.encodingB).
  167.                                    Replace("NumberOfEntries=" & CStr(tacksCount),
  168.                                            "NumberOfEntries=" & CStr(tacksCount + 1)))
  169.  
  170.                    sb.AppendLine(String.Format("File{0}={1}", CStr(tacksCount + 1), filepath.Replace("\", "/")))
  171.                    File.WriteAllText(Me.filepathB, sb.ToString(), Me.encodingB)
  172.  
  173.            End Select
  174.  
  175.            sb.Clear()
  176.        End Sub
  177.  
  178.        ''' <summary>
  179.        ''' Adds a new track in the playlist, with extended track information.
  180.        ''' </summary>
  181.        <DebuggerStepThrough>
  182.        Public Sub Add(ByVal filepath As String, ByVal title As String, ByVal length As TimeSpan,
  183.                       Optional ByVal throwOnDuplicate As Boolean = False)
  184.  
  185.            If Not (throwOnDuplicate) AndAlso Me.Exist(filepath) Then
  186.                Throw New ArgumentException("The specified file path already exists in the playlist.",
  187.                                            paramName:="filepath")
  188.            End If
  189.  
  190.            Dim sb As New StringBuilder
  191.  
  192.            Select Case Me.playlistTypeB
  193.  
  194.                Case PlaylistType.M3U
  195.                    sb.AppendLine()
  196.                    sb.AppendLine(String.Format("#EXTINF:{0},{1}", CStr(Math.Truncate(length.TotalSeconds)), title))
  197.                    sb.AppendLine(filepath)
  198.                    File.AppendAllText(Me.filepathB, sb.ToString(), Me.encodingB)
  199.  
  200.                Case PlaylistType.PLS
  201.                    Dim tacksCount As Integer = Me.GetPlsTrackCount()
  202.                    sb.AppendLine(File.ReadAllText(Me.filepathB, Me.encodingB).
  203.                                         Replace("NumberOfEntries=" & CStr(tacksCount),
  204.                                                 "NumberOfEntries=" & CStr(tacksCount + 1I)))
  205.  
  206.                    sb.AppendLine(String.Format("File{0}={1}", CStr(tacksCount + 1I), filepath.Replace("\", "/")))
  207.                    sb.AppendLine(String.Format("Title{0}={1}", CStr(tacksCount + 1I), title))
  208.                    sb.AppendLine(String.Format("Length{0}={1}", CStr(tacksCount + 1I), CStr(Math.Truncate(length.TotalSeconds))))
  209.                    File.WriteAllText(Me.filepathB, sb.ToString(), Me.encodingB)
  210.  
  211.            End Select
  212.  
  213.            sb.Clear()
  214.        End Sub
  215.  
  216.        ''' <summary>
  217.        ''' Adds a new track in the playlist, with extended track information.
  218.        ''' </summary>
  219.        <DebuggerStepThrough>
  220.        Public Sub Add(ByVal trackInfo As PlaylistTrackInfo,
  221.                       Optional ByVal throwOnDuplicate As Boolean = False)
  222.  
  223.            Me.Add(trackInfo.Path, trackInfo.Title, trackInfo.Length, throwOnDuplicate)
  224.  
  225.        End Sub
  226.  
  227.        ''' <summary>
  228.        ''' Removes the specified track from the playlist.
  229.        ''' </summary>
  230.        <DebuggerStepThrough>
  231.        Public Sub RemoveTrack(ByVal filepath As String)
  232.  
  233.            If Not Me.Exist(filepath) Then
  234.                Throw New ArgumentException("The specified file path does not exists in the playlist.",
  235.                                            paramName:="filepath")
  236.            End If
  237.  
  238.            Dim playlistContent As List(Of String) = File.ReadLines(Me.filepathB, Me.encodingB).ToList()
  239.  
  240.            Select Case Me.playlistTypeB
  241.                Case PlaylistType.M3U
  242.                    Dim entryIndex As Integer =
  243.                        playlistContent.FindIndex(
  244.                        Function(item As String)
  245.                            Return item.Equals(filepath, StringComparison.OrdinalIgnoreCase)
  246.                        End Function)
  247.  
  248.                    playlistContent.RemoveAt(entryIndex)
  249.                    If playlistContent(entryIndex - 1).StartsWith("#EXTINF", StringComparison.OrdinalIgnoreCase) Then
  250.                        playlistContent.RemoveAt(entryIndex - 1)
  251.                    End If
  252.                    File.WriteAllLines(Me.filepathB, playlistContent, Me.encodingB)
  253.  
  254.                Case PlaylistType.PLS
  255.                    Dim entryIndex As Integer =
  256.                        playlistContent.FindIndex(
  257.                        Function(item As String)
  258.                            Return item.ToLower Like "file#*" & filepath.Replace("\", "/").ToLower
  259.                        End Function)
  260.  
  261.                    Dim trackIndexDelimStartIndex As Integer =
  262.                        playlistContent(entryIndex).IndexOf("e", StringComparison.OrdinalIgnoreCase) + 1I
  263.  
  264.                    Dim trackIndexDelimEndIndex As Integer =
  265.                        playlistContent(entryIndex).IndexOf("=", StringComparison.OrdinalIgnoreCase)
  266.  
  267.                    Dim trackIndex As Integer =
  268.                        CInt(playlistContent(entryIndex).Substring(trackIndexDelimStartIndex,
  269.                                                              trackIndexDelimEndIndex - trackIndexDelimStartIndex))
  270.  
  271.                    playlistContent.RemoveAt(entryIndex)
  272.  
  273.                    Dim titleEntryIndex As Integer =
  274.                        playlistContent.FindIndex(Function(item As String)
  275.                                                      Return item.ToLower Like String.Format("title{0}=*", CStr(trackIndex))
  276.                                                  End Function)
  277.  
  278.                    If titleEntryIndex <> -1 Then
  279.                        playlistContent.RemoveAt(titleEntryIndex)
  280.                    End If
  281.  
  282.                    Dim lengthEntryIndex As Integer =
  283.                        playlistContent.FindIndex(Function(item As String)
  284.                                                      Return item.ToLower Like String.Format("length{0}=*", CStr(trackIndex))
  285.                                                  End Function)
  286.  
  287.                    If lengthEntryIndex <> -1I Then
  288.                        playlistContent.RemoveAt(lengthEntryIndex)
  289.                    End If
  290.  
  291.                    Dim numberOfEntriesEntryIndex As Integer =
  292.                        playlistContent.FindIndex(Function(item As String)
  293.                                                      Return item.ToLower Like "numberofentries=#*"
  294.                                                  End Function)
  295.  
  296.                    playlistContent(numberOfEntriesEntryIndex) =
  297.                        String.Format("NumberOfEntries={0}", CStr(Me.GetPlsTrackCount() - 1))
  298.  
  299.                    File.WriteAllLines(Me.filepathB, playlistContent, Me.encodingB)
  300.  
  301.                    Me.FixPlsTrackIndices()
  302.  
  303.            End Select
  304.        End Sub
  305.  
  306.        ''' <summary>
  307.        ''' Removes the specified track from the playlist.
  308.        ''' </summary>
  309.        <DebuggerStepThrough>
  310.        Public Sub RemoveTrack(ByVal trackIndex As Integer)
  311.            Dim track As PlaylistTrackInfo = Me.GetTrackInfo(trackIndex)
  312.  
  313.            If track IsNot Nothing Then
  314.                Me.RemoveTrack(track.Path)
  315.            Else
  316.                Throw New IndexOutOfRangeException("Track index is out of range") With {.Source = "trackIndex"}
  317.            End If
  318.        End Sub
  319.  
  320.        ''' <summary>
  321.        ''' Sets the track info of the specified track.
  322.        ''' </summary>
  323.        <DebuggerStepThrough>
  324.        Public Sub SetTrackInfo(ByVal filepath As String, ByVal trackInfo As PlaylistTrackInfo)
  325.  
  326.            If Not Me.Exist(filepath) Then
  327.                Throw New ArgumentException("The specified file path does not exists in the playlist.",
  328.                                            paramName:="filepath")
  329.            End If
  330.  
  331.            Dim track As PlaylistTrackInfo = Me.GetTrackInfo(filepath)
  332.            With track
  333.                .Path = trackInfo.Path
  334.                .Title = trackInfo.Title
  335.                .Length = trackInfo.Length
  336.            End With
  337.  
  338.            Dim playlistContent As List(Of String) = File.ReadLines(Me.filepathB, Me.encodingB).ToList()
  339.  
  340.            Select Case Me.playlistTypeB
  341.                Case PlaylistType.M3U
  342.                    Dim trackIndex As Integer =
  343.                        playlistContent.FindIndex(
  344.                        Function(item As String)
  345.                            Return item.Equals(filepath, StringComparison.OrdinalIgnoreCase)
  346.                        End Function)
  347.  
  348.                    playlistContent(trackIndex) = String.Format("#EXTINF:{0},{1}",
  349.                                                                CStr(Math.Truncate(track.Length.TotalSeconds)),
  350.                                                                track.Title) & Environment.NewLine & track.Path
  351.  
  352.                    If playlistContent(trackIndex - 1I).StartsWith("#EXTINF", StringComparison.OrdinalIgnoreCase) Then
  353.                        playlistContent.RemoveAt(trackIndex - 1I)
  354.                    End If
  355.  
  356.                    File.WriteAllLines(Me.filepathB, playlistContent, Me.encodingB)
  357.  
  358.                Case PlaylistType.PLS
  359.                    track.Path = track.Path.Replace("\", "/")
  360.  
  361.                    Dim trackIndex As Integer =
  362.                        playlistContent.FindIndex(
  363.                        Function(item As String)
  364.                            Return item.ToLower Like "file#*" & filepath.Replace("\", "/").ToLower
  365.                        End Function)
  366.  
  367.                    playlistContent(trackIndex) = String.Format("File{0}={1}", CStr(track.Index), track.Path) & Environment.NewLine &
  368.                                                  String.Format("Title{0}={1}", CStr(track.Index), track.Title) & Environment.NewLine &
  369.                                                  String.Format("Length{0}={1}", CStr(track.Index), CStr(Math.Truncate(track.Length.TotalSeconds)))
  370.  
  371.                    If playlistContent.Count > (trackIndex + 1) Then
  372.                        If playlistContent(trackIndex + 2).StartsWith("Title", StringComparison.OrdinalIgnoreCase) _
  373.                        OrElse playlistContent(trackIndex + 2).StartsWith("Length", StringComparison.OrdinalIgnoreCase) Then
  374.                            playlistContent.RemoveAt(trackIndex + 2)
  375.                        End If
  376.                    End If
  377.  
  378.                    If playlistContent.Count > trackIndex Then
  379.                        If playlistContent(trackIndex + 1).StartsWith("Title", StringComparison.OrdinalIgnoreCase) _
  380.                        OrElse playlistContent(trackIndex + 1).StartsWith("Length", StringComparison.OrdinalIgnoreCase) Then
  381.                            playlistContent.RemoveAt(trackIndex + 1)
  382.                        End If
  383.                    End If
  384.  
  385.                    File.WriteAllLines(Me.filepathB, playlistContent, Me.encodingB)
  386.            End Select
  387.  
  388.        End Sub
  389.  
  390.        ''' <summary>
  391.        ''' Sets the track info of the specified track.
  392.        ''' </summary>
  393.        <DebuggerStepThrough>
  394.        Public Sub SetTrackInfo(ByVal trackIndex As Integer, ByVal trackInfo As PlaylistTrackInfo)
  395.            If Not Me.Exist(trackIndex) Then
  396.                Throw New IndexOutOfRangeException("Track index is out of range.") With {.Source = "trackIndex"}
  397.            End If
  398.  
  399.            Me.SetTrackInfo(Me.GetTrackInfo(trackIndex).Path, trackInfo)
  400.        End Sub
  401.  
  402.        ''' <summary>
  403.        ''' Finds the specified track in the playlist and returns a
  404.        ''' <see cref="PlaylistTrackInfo"/> instance that represents the track.
  405.        ''' </summary>
  406.        <DebuggerStepThrough>
  407.        Public Function GetTrackInfo(ByVal filepath As String) As PlaylistTrackInfo
  408.  
  409.            Dim playlistContent As List(Of String) = File.ReadLines(Me.filepathB, Me.encodingB).ToList()
  410.            Dim tInfo As New PlaylistTrackInfo
  411.  
  412.            Select Case Me.playlistTypeB
  413.  
  414.                Case PlaylistType.M3U
  415.                    Dim trackIndex As Integer = playlistContent.FindIndex(
  416.                        Function(item As String)
  417.                            Return item.Equals(filepath, StringComparison.OrdinalIgnoreCase)
  418.                        End Function) - 1
  419.  
  420.                    If playlistContent(trackIndex).StartsWith("#EXTINF", StringComparison.OrdinalIgnoreCase) Then
  421.                        Dim titleDelimIndex As Integer = playlistContent(trackIndex).IndexOf(","c) + 1
  422.                        Dim lengthDelimIndex As Integer = playlistContent(trackIndex).IndexOf(":"c) + 1
  423.  
  424.                        With tInfo
  425.                            .Index = trackIndex
  426.                            .Path = filepath
  427.                            .Title = playlistContent(trackIndex).Substring(titleDelimIndex)
  428.                            .Length = TimeSpan.FromSeconds(CDbl(playlistContent(trackIndex).Substring(lengthDelimIndex, (titleDelimIndex - lengthDelimIndex))))
  429.                        End With
  430.                    End If
  431.  
  432.                Case PlaylistType.PLS
  433.                    filepath = filepath.Replace("\", "/")
  434.  
  435.                    Dim entry As String = (From Item As String In playlistContent
  436.                                           Where Item.ToLower Like String.Format("file#*={0}", filepath.ToLower())).SingleOrDefault
  437.  
  438.                    If Not String.IsNullOrEmpty(entry) Then
  439.  
  440.                        Dim indexDelimStartIndex As Integer =
  441.                            entry.IndexOf("e", StringComparison.OrdinalIgnoreCase) + 1I
  442.  
  443.                        Dim indexDelimEndIndex As Integer =
  444.                            entry.IndexOf("=", StringComparison.OrdinalIgnoreCase)
  445.  
  446.                        Dim trackIndex As Integer = CInt(entry.Substring(indexDelimStartIndex,
  447.                                                                    indexDelimEndIndex - indexDelimStartIndex))
  448.  
  449.                        Dim titleEntry As String = (From Item As String In playlistContent
  450.                                                    Where Item.StartsWith(String.Format("Title{0}=", CStr(trackIndex)), StringComparison.OrdinalIgnoreCase)).
  451.                                                    FirstOrDefault
  452.  
  453.                        Dim lengthEntry As String = (From Item As String In playlistContent
  454.                                                     Where Item.StartsWith(String.Format("Length{0}=", CStr(trackIndex)), StringComparison.OrdinalIgnoreCase)).
  455.                                                     FirstOrDefault
  456.  
  457.                        With tInfo
  458.                            .Index = trackIndex
  459.                            .Path = filepath
  460.                            .Title = If(Not String.IsNullOrEmpty(titleEntry),
  461.                                        titleEntry.Substring(titleEntry.IndexOf("=") + 1),
  462.                                        Nothing)
  463.                            .Length = If(Not String.IsNullOrEmpty(titleEntry),
  464.                                         TimeSpan.FromSeconds(CDbl(lengthEntry.Split("="c).LastOrDefault)),
  465.                                         Nothing)
  466.                        End With
  467.  
  468.                    End If
  469.  
  470.            End Select
  471.  
  472.            Return tInfo
  473.  
  474.        End Function
  475.  
  476.        ''' <summary>
  477.        ''' Finds the specified track in the playlist and returns a
  478.        ''' <see cref="PlaylistTrackInfo"/> instance that represents the track.
  479.        ''' </summary>
  480.        <DebuggerStepThrough>
  481.        Public Function GetTrackInfo(ByVal trackIndex As Integer) As PlaylistTrackInfo
  482.  
  483.            Dim playlistContent As List(Of String) = File.ReadLines(Me.filepathB, Me.encodingB).ToList()
  484.  
  485.            Select Case Me.playlistTypeB
  486.  
  487.                Case PlaylistType.M3U
  488.                    Dim trackCount As Integer = 0
  489.  
  490.                    For index As Integer = 0 To (playlistContent.Count - 1)
  491.                        If Not String.IsNullOrEmpty(playlistContent(index)) _
  492.                           AndAlso Not playlistContent(index).StartsWith("#EXT", StringComparison.OrdinalIgnoreCase) Then
  493.  
  494.                            trackCount += 1
  495.                            If (trackCount = trackIndex) Then
  496.                                Dim tInfo As PlaylistTrackInfo = Me.GetTrackInfo(playlistContent(index))
  497.                                With tInfo
  498.                                    .Index = trackIndex
  499.                                    .Path = playlistContent(index)
  500.                                End With
  501.                                Return tInfo
  502.                            End If
  503.  
  504.                        End If
  505.                    Next index
  506.  
  507.                Case PlaylistType.PLS
  508.                    For index As Integer = 0 To (playlistContent.Count - 1)
  509.                        If playlistContent(index).StartsWith(String.Format("File{0}=", CStr(trackIndex)),
  510.                                                             StringComparison.OrdinalIgnoreCase) Then
  511.                            Return Me.GetTrackInfo(playlistContent(index).Substring(playlistContent(index).IndexOf("="c) + 1I))
  512.                        End If
  513.                    Next index
  514.  
  515.            End Select
  516.  
  517.            Return Nothing
  518.        End Function
  519.  
  520.        ''' <summary>
  521.        ''' Determines whether the specified track exists in the playlist.
  522.        ''' </summary>
  523.        <DebuggerStepThrough>
  524.        Public Function Exist(ByVal filepath As String) As Boolean
  525.            Dim returnValue As Boolean = False
  526.  
  527.            Select Case Me.playlistTypeB
  528.                Case PlaylistType.M3U
  529.                    returnValue = (From Item As String In File.ReadLines(Me.filepathB, Me.encodingB)
  530.                                   Where Item.StartsWith(filepath, StringComparison.OrdinalIgnoreCase)).
  531.                                   Any()
  532.  
  533.                Case PlaylistType.PLS
  534.                    returnValue = (From Item As String In File.ReadLines(Me.filepathB, Me.encodingB)
  535.                                   Where Item.ToLower() Like "file#*" & filepath.Replace("\", "/").ToLower()).
  536.                                   Any()
  537.            End Select
  538.  
  539.            Return returnValue
  540.        End Function
  541.  
  542.        ''' <summary>
  543.        ''' Determines whether the specified track exists in the playlist.
  544.        ''' </summary>
  545.        <DebuggerStepThrough>
  546.        Public Function Exist(ByVal trackIndex As Integer) As Boolean
  547.            If (trackIndex <= 0) Then
  548.                Throw New IndexOutOfRangeException("TrackIndex should be greater than 0.") With {.Source = "trackIndex"}
  549.            End If
  550.  
  551.            Return (Me.Count >= trackIndex)
  552.        End Function
  553.  
  554. #End Region
  555.  
  556. #Region " Private Methods "
  557.  
  558.        ''' <summary>
  559.        ''' Collects all the tracks defined in a playlist file and returns a <see cref="List(Of PlaylistTrackInfo)"/>.
  560.        ''' </summary>
  561.        <DebuggerStepThrough>
  562.        Private Function GetTracks() As List(Of PlaylistTrackInfo)
  563.  
  564.            Dim playlistContent As List(Of String) = File.ReadLines(Me.filepathB, Me.encodingB).ToList()
  565.            Dim tInfo As New List(Of PlaylistTrackInfo)
  566.            Dim trackCount As Integer = 0
  567.  
  568.            Select Case Me.playlistTypeB
  569.  
  570.                Case PlaylistType.M3U
  571.                    For index As Integer = 0 To (playlistContent.Count - 1)
  572.                        If Not String.IsNullOrEmpty(playlistContent(index)) _
  573.                           AndAlso Not playlistContent(index).StartsWith("#EXT", StringComparison.OrdinalIgnoreCase) Then
  574.                            trackCount += 1
  575.                            tInfo.Add(Me.GetTrackInfo(trackCount))
  576.                        End If
  577.                    Next
  578.  
  579.                Case PlaylistType.PLS
  580.                    For index As Integer = 0 To (playlistContent.Count - 1)
  581.                        If playlistContent(index).StartsWith("File", StringComparison.OrdinalIgnoreCase) Then
  582.                            trackCount += 1
  583.                            tInfo.Add(Me.GetTrackInfo(trackCount))
  584.                        End If
  585.                    Next index
  586.  
  587.            End Select
  588.  
  589.            Return tInfo
  590.        End Function
  591.  
  592.        ''' <summary>
  593.        ''' Adds the playlist headers at the top of the playlist file.
  594.        ''' <para></para>
  595.        ''' This method should always be called before adding the very first entry in a new (empty) playlist.
  596.        ''' </summary>
  597.        <DebuggerStepThrough>
  598.        Private Sub AddHeaders()
  599.            Dim sb As New StringBuilder
  600.  
  601.            Select Case Me.playlistTypeB
  602.                Case PlaylistType.M3U
  603.                    sb.AppendLine("#EXTM3U")
  604.  
  605.                Case PlaylistType.PLS
  606.                    With sb
  607.                        .AppendLine("[playlist]")
  608.                        .AppendLine("NumberOfEntries=0")
  609.                        .AppendLine("Version=2")
  610.                    End With
  611.            End Select
  612.  
  613.            File.WriteAllText(Me.filepathB, sb.ToString(), Me.encodingB)
  614.            sb.Clear()
  615.        End Sub
  616.  
  617.        ''' <summary>
  618.        ''' Gets the amount of total tracks defined in a PLS playlist file.
  619.        ''' </summary>
  620.        <DebuggerStepThrough>
  621.        Private Function GetPlsTrackCount() As Integer
  622.            Dim playlistContent As String = File.ReadAllText(Me.filepathB, Me.encodingB)
  623.  
  624.            Dim startIndex As Integer =
  625.                playlistContent.IndexOf("=") + 1I
  626.  
  627.            Dim endIndex As Integer =
  628.                playlistContent.IndexOf(ControlChars.NewLine, startIndex) - startIndex
  629.  
  630.            Return CInt(playlistContent.Substring(startIndex, playlistContent.IndexOf(String.Empty, endIndex)))
  631.        End Function
  632.  
  633.        ''' <summary>
  634.        ''' Fixes the track indices of a PLS playlist file.
  635.        ''' <para></para>
  636.        ''' This method shoould always be called after removing a track from the playlist.
  637.        ''' </summary>
  638.        <DebuggerStepThrough>
  639.        Private Sub FixPlsTrackIndices()
  640.  
  641.            Dim playlistContent As List(Of String) = File.ReadLines(Me.filepathB, Me.encodingB).ToList()
  642.            Dim trackCount As Integer = 0I
  643.  
  644.            For index As Integer = 0 To (playlistContent.Count - 1I)
  645.  
  646.                If playlistContent(index).StartsWith("File", StringComparison.OrdinalIgnoreCase) Then
  647.                    trackCount += 1I
  648.                    playlistContent(index) = String.Format("File{0}={1}",
  649.                                                           CStr(trackCount),
  650.                                                           playlistContent(index).Substring(playlistContent(index).IndexOf("="c) + 1I))
  651.  
  652.                ElseIf playlistContent(index).StartsWith("Title", StringComparison.OrdinalIgnoreCase) Then
  653.                    playlistContent(index) = String.Format("Title{0}={1}",
  654.                                                           CStr(trackCount),
  655.                                                           playlistContent(index).Substring(playlistContent(index).IndexOf("="c) + 1I))
  656.  
  657.                ElseIf playlistContent(index).StartsWith("Length", StringComparison.OrdinalIgnoreCase) Then
  658.                    playlistContent(index) = String.Format("Length{0}={1}",
  659.                                                           CStr(trackCount),
  660.                                                           playlistContent(index).Substring(playlistContent(index).IndexOf("="c) + 1I))
  661.  
  662.                End If
  663.            Next index
  664.  
  665.            Dim numberOfEntriesEntryIndex As Integer =
  666.                playlistContent.FindIndex(Function(item As String)
  667.                                              Return item.ToLower Like "numberofentries=#*"
  668.                                          End Function)
  669.  
  670.            playlistContent(numberOfEntriesEntryIndex) =
  671.                String.Format("NumberOfEntries={0}", CStr(trackCount))
  672.  
  673.            File.WriteAllLines(Me.filepathB, playlistContent, Me.encodingB)
  674.        End Sub
  675.  
  676. #End Region
  677.  
  678.    End Class
  679.  
  680. End Namespace
  681.  
  682. #End Region



El código de arriba puedes tomarlo como ejemplo y nada más para saber como sería una posible manera de poder hacerlo, o bien puedes copiar y pegarlo en una nueva clase de VB.NET para compilarlo en una dll y usarlo en C#, o también puedes convertir directamente el código a C# por ejemplo usando mi conversor de código gratuito ( todos los créditos y copyright para Telerik xD ):

  • [SOURCE-CODE] Telerik Code Converter Client for Windows - by Elektro Studios (http://foro.elhacker.net/net/sourcecode_telerik_code_converter_client_for_windows_by_elektro_studios-t474580.0.html)



Modo de empleo:
Código
  1. PlaylistEditor editor = new PlaylistEditor(@"C:\playlist.m3u", PlaylistType.M3U, createNew: true);
  2. editor.Add("C:\\File 1.mp3");
  3. editor.Add("C:\\File 2.mp3");

O bien:
Código
  1. PlaylistEditor editor = new PlaylistEditor(@"C:\playlist.m3u", PlaylistType.M3U, createNew: true);
  2.  
  3. PlaylistTrackInfo trackInfo = new PlaylistTrackInfo();
  4. trackInfo.Path = "C:\\File.mp3";
  5. trackInfo.Title = {Track Title or Display Name};
  6. trackInfo.Length = {Track Duration};
  7.  
  8. editor.Add(trackInfo);

Saludos


Título: Re: C# - No puedo reproducir la siguiente cancion
Publicado por: TickTack en 13 Octubre 2017, 11:16 am
Hola Elektro,

1. Muchas gracias por tu consejo. Ya lo hize. Pero me gustaria saber como es que estas siempre
informado de que esto produce fugas de consume RAM y lo otro envia mensajes de ventana para
redibujarse y que este otro produce esto? Es increible tu conocimiento!!

2. Ahh si. De esto queria hablar. Es que tu codigo que mostraste se complica con mi proyecto
porque para empezar me da problemas con public souled class. Me dice que no se puede dejarlo
asi porque hay otra clase que ya esta asi. Ni idea? Luego me dice que no se puede acceder
a files por motivos de seguridad y son todas cosas con las que nunca me tope por la falta de
experiencia.....

4. Noooooooooooooooo. Que idiota que soy. Ni me di cuenta. Perdon por lo bruto que soy.. jejej.

5. Pero entonces cual me dices que es mas recomendable usar? Tu codigo 1 o tu codigo 2
(posteaste dos codigos tuyos aca). Porque si me dices codigo 1 entonces vere que puedo hacer
con el problema de public souled class y lo demas. Pero si me dices codigo 2 entonces
podre pegar el codigo en una nueva clase de VB.NET para compilarlo en una dll y
posteriormente usarlo en C#. Finalmente si me dices que investigue los dos codigos lo hare
(por supuesto, solamente si me lo recomiendas).

Para terminar te muestro como quedo el codigo hasta ahora segun tu:

Código:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WMPLib;

namespace Player
{
    public partial class Form1 : Form
    {
        List<string> list1 = new List<string>();
        List<string> list2 = new List<string>();
        List<string> list3 = new List<string>();
        Timer timer1 = new Timer();
        int index = 0;
       
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.Multiselect = true;

                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    listBox1.Sorted = true;

                    foreach (var file in ofd.SafeFileNames)
                    {
                        listBox1.Items.Add(file);
                        list1.Add(file);
                    }

                    foreach (var file in ofd.FileNames)
                    {
                        list2.Add(file);
                    }
                }
            }     
        }

        private void Form1_Load(object sender, EventArgs e)
        {
           
        }

        private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            index = listBox1.SelectedIndex;
            axWindowsMediaPlayer1.URL = list2[list1.IndexOf(listBox1.GetItemText(listBox1.SelectedItem))];
        }

        private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
        {
            if (e.newState == 8)
            {
                index = index + 1;

                if (index - 1 < listBox1.Items.Count)
                {
                    axWindowsMediaPlayer1.URL = list2[list1.IndexOf(listBox1.Items[index].ToString())];
                }
            }
        }
    }
}

Gracias y saludos


Título: Re: C# - No puedo reproducir la siguiente cancion
Publicado por: Eleкtro en 13 Octubre 2017, 12:13 pm
1. me gustaria saber como es que estas siempre informado de que esto produce fugas de consume RAM y lo otro envia mensajes de ventana para
redibujarse y que este otro produce esto? Es increible tu conocimiento!!

Te agradezco el reconocimiento pero en realidad en mi opinión no son cosas avanzadas que se merezcan " "admiración" " hacia alguien, o al menos yo creo que deberían ser cosas básicas que se deben aprender estudiando el lenguaje, documentándose sobre como se administran los recursos, o como trabaja el sistema de mensajería, GDI/GDI+, WinForms, etc...

Siempre he sostenido que no hay mejor manera de aprender .NET que leyendo la MSDN (aunque sea un coñazo), por que en los libros suelen explicar los conceptos más "internos" de forma superficial, y luego pasa lo que pasa, que uno aprende a manejar C#/VB.NET pero eso no es suficiente ya que no aprende como funciona el sistema operativo (Windows) ni la tecnología que esté usando (WinForms, WPF, etc).

Te dejo unos enlaces de interés:

Administración de recursos:
  • Cleaning Up Unmanaged Resources |  docs.microsoft.com (https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/unmanaged)
  • Using objects that implement IDisposable |  docs.microsoft.com (https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/using-objects)
  • Garbage Collection |  docs.microsoft.com (https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/)
  • Garbage Collector Basics and Performance Hints |  MSDN (https://msdn.microsoft.com/en-us/library/ms973837.aspx)

Mensajería
  • About Messages and Message Queues | MSDN (https://msdn.microsoft.com/en-us/library/windows/desktop/ms644927(v=vs.85).aspx)
  • Window Messages | MSDN (https://msdn.microsoft.com/en-us/library/windows/desktop/ms644927(v=vs.85).aspx)

Painting
  • About Painting and Drawing | MSDN (https://msdn.microsoft.com/en-us/library/dd183315(v=VS.85).aspx)

ListBox
  • ListBox.BeginUpdate() Method | MSDN (https://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.beginupdate(v=vs.110).aspx)
Con respecto a lo que te expliqué de usar el método AddRange, en ese último enlace está documentado también:
Cita de: MSDN
Remarks
The preferred way to add multiple items to the ListBox is to use the AddRange method of the ListBox.ObjectCollection class (through the Items property of the ListBox). This enables you to add an array of items to the list in a single operation. However, if you want to add items one at a time using the Add method of the ListBox.ObjectCollection class, you can use the BeginUpdate method to prevent the control from repainting the ListBox each time an item is added to the list. Once you have completed the task of adding items to the list, call the EndUpdate method to enable the ListBox to repaint. This way of adding items can prevent flickered drawing of the ListBox when a large number of items are being added to the list.

En fin, si llegas a leer todos los enlaces que voy poniendo a la MSDN y docs.microsoft.com (no me refiero solo a los que he compartido ahora, sino en general), aprenderías mucho sobre .NET a "nivel gurú" o casi xD. :P

  • Manuales de .NET (http://foro.elhacker.net/net/manuales_de_net-t122607.0.html;msg1960666#msg1960666)

Analizar el código fuente de .NET Framework también ayuda mucho a comprender como funciona a nivel "interno":
  • https://referencesource.microsoft.com/



2. tu codigo que mostraste se complica con mi proyecto
porque para empezar me da problemas con public souled class. Me dice que no se puede dejarlo
asi porque hay otra clase que ya esta asi. Ni idea?

En general todo el código que tienes ahora mismo lo puedes mejorar y simplificar / refactorizar a algo parecido a esto:

Código
  1. public sealed class Form1 : Form {
  2.    // código relevante aquí ...
  3. }

Lo de "public sealed class Form1 : Form" es así por que yo escribí el código en un nuevo proyecto, pero te dije que lo tienes que adaptar, no tienes que copiar los modificadores (sealed) ni tampoco el nombre de la clase (Form1), sino el resto del código (código relevante) que está definido dentro de esa clase.

En tu código imagino que lo tendrás escrito así:
Código
  1. public partial class Form1
...no necesitas cambiarlo.



5. Pero entonces cual me dices que es mas recomendable usar? Tu codigo 1 o tu codigo 2
(posteaste dos codigos tuyos aca).

Porque si me dices codigo 1 entonces vere que puedo hacer
con el problema de public souled class y lo demas. Pero si me dices codigo 2 entonces
podre pegar el codigo en una nueva clase de VB.NET para compilarlo en una dll y
posteriormente usarlo en C#. Finalmente si me dices que investigue los dos codigos lo hare
(por supuesto, solamente si me lo recomiendas).

Son códigos para cosas distintas.

El primer código que puse en C# es una refactorización del primer código que tu compartiste, es un fix por así decirlo que corrige varios malos hábitos de programación en .NET ( los que te estuve explicando y enumerando 1., 2., 3. etc... ) y que en teoría debería servirte para corregir el problema de no poder reproducir la siguiente canción (solo en teoría, ya que como dije no probé lo del WMP).
La idea era que reemplazases (todo) tú código por el que yo te mostré y decir si con esos cambios arreglaste por fin el problema. Pero sin lo de "public sealed class Form1 : Form", eso déjalo como lo tengas escrito en tu clase Form1.

El segundo código en VB.NET es una implementación para administrar listas de reproducción en formato m38 o pls, eso lo puedes usar si quieres o no usarlo xD, puedes hacer basicamente lo mismo con la interfáz COM que te dije de WMP (IWMPPlaylist). Ese código te lo puse por que tú dijiste que "querías ir por ese camino" y pues... con ese código te estaba dando "el camino hecho".

saludos