elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: (TUTORIAL) Aprende a emular Sentinel Dongle By Yapis


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  [APORTE] Multimedia Playlist Editor (M3U y PLS)
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [APORTE] Multimedia Playlist Editor (M3U y PLS)  (Leído 2,303 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.813



Ver Perfil
[APORTE] Multimedia Playlist Editor (M3U y PLS)
« en: 22 Julio 2014, 02:04 am »

Hola

Comparto esta Class cuya finalidad es la de administrar las pistas de una lista multimedia.

Para quien no sepa lo que es una lista multimedia, son unos archivos de texto plano que utilizan los reproductores de archivos multimedia (Video/Audio) para crear listas de reproducción.

Estas son ejemplos de los tipos de listas que soporta mi Class:

M3U:
Código:
#EXTM3U

#EXTINF:330,Track1 Title
C:\Track1.avi

C:\Track2.mp4

#EXTINF:5720,Track3 Title
C:\Track3.mp3

PLS:
Código:
[playlist]
NumberOfEntries=3
Version=2

File1=C:/Track1.avi

File2=C:/Track2.mp4
Title2=My Track2 Title!
Length2=5720

File3=C:/Track3.mp3
Title3=My Track3 Title!
Length3=330

Características del código:
· Se puede trabajar con dos tipos de listas, M3U y PLS.
· Se puede añadir entradas de pistas con o sin información extendida, así como editar una entrada, eliminar, determinar si existe, o buscar para obtener la información extendida de una pista.
· La mayoría de los métodos que desarrollé tienen overloads para trabajar pasandole o bien la ruta de la pista, o el índice de la pista (primero hay que conocer el índice, claro).

El código en general no creo que me haya quedado muy optimizado, de echo tengo que evitar la recursividad de algún que otro método, pero por el momento está bien y hace su función, aunque si encuentran cualquier fallo o cualquier sugerencia que quieran hacer entonces porfavor comenten.

PD: No he añadido muchos controles de errores, ya que he supuesto que si se le da el uso correcto no debería dar errores (más hallá de los que sí están controlados).

PD2: Al principio me propuse hacerlo todo mediante FileStreams y manteniendo el archivo abierto para denegar el acceso manual al archivo, pero el formato PLS me lo puso muy complicado porque hay que hacer operaciones constantes de búsqueda y modificar un valor tras cada operación así que para no comerme mucho más la cabeza decidí usar un StringBuilder y también listas de Strings, sin más, dejando un poco de lado los permisos de lectura/escritura del archivo del playlist y tambien el rendimiento en general ...los tiempos de ejecución, pero de todas formas recordemos que se trataría de un simple archivo de texto que no debería tener muchas lineas, aunque se optimizase el código no creo que se apreciase la diferencia (en milisegundos xD)...





Estos son algunos ejemplos de uso:

Código
  1.        ' **********************************
  2.        ' Instance the PlaylistEditor Class
  3.        ' **********************************
  4.        Dim Playlist As New PlaylistEditor(PlaylistFile:="C:\Playlist.m3u",
  5.                                           PlaylistType:=PlaylistEditor.PlaylistType.M3U,
  6.                                           Append:=False,
  7.                                           FileEncoding:=System.Text.Encoding.Default)
  8.  
  9.        ' ************************************
  10.        ' Retrieve the instanced object info
  11.        ' ************************************
  12.        MessageBox.Show(Playlist.FilePath)
  13.        MessageBox.Show(Playlist.Type.ToString)
  14.        MessageBox.Show(CStr(Playlist.Append))
  15.        MessageBox.Show(String.Format("Encoding: {0}, CodePage: {1}",
  16.                                      Playlist.FileEncoding.BodyName,
  17.                                      Playlist.FileEncoding.CodePage))
  18.  
  19.        ' ***************************
  20.        ' Instance a TrackInfo Class
  21.        ' ***************************
  22.        Dim TInfo As New PlaylistEditor.TrackInfo
  23.        With TInfo
  24.            .Path = "C:\Track1.ext"
  25.            .Title = "Track1 Title"
  26.            .Length = TimeSpan.Parse("00:05:30")
  27.        End With
  28.  
  29.        ' ***************
  30.        ' Add a new track
  31.        ' ***************
  32.        Playlist.Add(TrackInfo:=TInfo)
  33.        Playlist.Add(Path:="C:\Track2.ext", AllowDuplicate:=False)
  34.        Playlist.Add(Path:="C:\Track3.ext", Title:="Track3 Title", Length:=TimeSpan.Parse("01:35:20"))
  35.  
  36.        ' *************************************************
  37.        ' Sets the extended track info of an existing track
  38.        ' *************************************************
  39.        Dim OldTrackPath As String = "C:\Track3.ext"
  40.  
  41.        Dim TInfoSet As New PlaylistEditor.TrackInfo
  42.        With TInfoSet
  43.            .Path = "C:\Modified Track3.ext"
  44.            .Title = "My modified Track3 title"
  45.            .Length = Playlist.GetTrack(OldTrackPath).Length
  46.        End With
  47.  
  48.        Playlist.Set(Path:=OldTrackPath, TrackInfo:=TInfoSet)
  49.  
  50.        ' ************************
  51.        ' Remove an existing track
  52.        ' ************************
  53.        Playlist.Remove(Path:="C:\Track3.ext")
  54.        Playlist.Remove(TrackIndex:=2I)
  55.  
  56.        ' ********************************
  57.        ' Determine whether a track exists
  58.        ' ********************************
  59.        MessageBox.Show(Playlist.Exist(Path:="C:\Track3.ext"))
  60.        MessageBox.Show(Playlist.Exist(TrackIndex:=3I))
  61.  
  62.        ' ************************************************
  63.        ' Count the total amount of tracks in the playlist
  64.        ' ************************************************
  65.        MessageBox.Show(Playlist.Count)
  66.  
  67.        ' ************************************
  68.        ' Get extended track info from a track
  69.        ' ************************************
  70.        Dim TrackInfo1 As PlaylistEditor.TrackInfo = Playlist.GetTrack(Path:="C:\Track1.ext")
  71.        Dim TrackInfo2 As PlaylistEditor.TrackInfo = Playlist.GetTrack(TrackIndex:=2I)
  72.  
  73.        ' ******************************************
  74.        ' Get all tracks and its extended track info
  75.        ' ******************************************
  76.        Dim sb As New System.Text.StringBuilder
  77.        Dim Tracks As List(Of PlaylistEditor.TrackInfo) = Playlist.GetTracks()
  78.  
  79.        For Each Track As PlaylistEditor.TrackInfo In Tracks
  80.  
  81.            With sb
  82.                .Clear()
  83.                .AppendLine(String.Format("Track Index : {0}", CStr(Track.Index)))
  84.                .AppendLine(String.Format("Track Path  : {0}", Track.Path))
  85.                .AppendLine(String.Format("Track Title : {0}", Track.Title))
  86.                .AppendLine(String.Format("Track Length: {0}", Convert.ToString(Track.Length)))
  87.            End With
  88.  
  89.            MessageBox.Show(sb.ToString)
  90.  
  91.        Next Track


« Última modificación: 22 Julio 2014, 02:25 am por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.813



Ver Perfil
Re: [APORTE] Multimedia Playlist Editor (M3U y PLS)
« Respuesta #1 en: 22 Julio 2014, 02:04 am »

Aquí tienen la Class:

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 07-21-2014
  4. ' ***********************************************************************
  5. ' <copyright file="PlaylistEditor.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Imports "
  11.  
  12. Imports System.ComponentModel
  13. Imports System.IO
  14. Imports System.Text
  15.  
  16. #End Region
  17.  
  18. #Region " PlaylistEditor "
  19.  
  20. ''' <summary>
  21. ''' Contains methods to manage the contents of a multimedia playlist file.
  22. ''' This class cannot be inherited.
  23. ''' </summary>
  24. Public NotInheritable Class PlaylistEditor
  25.  
  26. #Region " Properties "
  27.  
  28.    ''' <summary>
  29.    ''' Gets the playlist filepath.
  30.    ''' </summary>
  31.    ''' <value>The playlist filepath.</value>
  32.    Public ReadOnly Property FilePath As String
  33.        Get
  34.            Return Me._FilePath
  35.        End Get
  36.    End Property
  37.    Private _FilePath As String
  38.  
  39.    ''' <summary>
  40.    ''' Gets the playlist type.
  41.    ''' </summary>
  42.    ''' <value>The playlist type.</value>
  43.    Public ReadOnly Property Type
  44.        Get
  45.            Return Me._Type
  46.        End Get
  47.    End Property
  48.    Private _Type As PlaylistType
  49.  
  50.    ''' <summary>
  51.    ''' Gets the playlist file encoding.
  52.    ''' </summary>
  53.    ''' <value>The playlist file encoding.</value>
  54.    Public ReadOnly Property FileEncoding As Encoding
  55.        Get
  56.            Return Me._Encoding
  57.        End Get
  58.    End Property
  59.    Private _Encoding As Encoding
  60.  
  61.    ''' <summary>
  62.    ''' Gets a value indicating whether the append mode is activated.
  63.    ''' </summary>
  64.    ''' <value><c>true</c> if append mode is activated; otherwise, <c>false</c>.</value>
  65.    Public ReadOnly Property Append As Boolean
  66.        Get
  67.            Return Me._Append
  68.        End Get
  69.    End Property
  70.    Private _Append As Boolean
  71.  
  72. #End Region
  73.  
  74. #Region " Enumerations "
  75.  
  76.    ''' <summary>
  77.    ''' Indicates the type of a playlist.
  78.    ''' </summary>
  79.    <Description("Enumeration used as 'PlaylistType' parameter of 'New' constructor.")>
  80.    Public Enum PlaylistType As Integer
  81.  
  82.        ''' <summary>
  83.        ''' M3U Playlist.
  84.        ''' Documentation: http://en.wikipedia.org/wiki/M3U
  85.        ''' </summary>
  86.        M3U = 0I
  87.  
  88.        ''' <summary>
  89.        ''' PLS Playlist.
  90.        ''' Documentation: http://en.wikipedia.org/wiki/PLS_%28file_format%29
  91.        ''' </summary>
  92.        PLS = 1I
  93.  
  94.    End Enum
  95.  
  96. #End Region
  97.  
  98. #Region " Types "
  99.  
  100.    ''' <summary>
  101.    ''' Contains extended info of a playlist track.
  102.    ''' </summary>
  103.    Public Class TrackInfo
  104.  
  105. #Region " Properties "
  106.  
  107.        ''' <summary>
  108.        ''' Gets the track index.
  109.        ''' Don't set this value manually.
  110.        ''' This value is automatically set by some of the <see cref="PlaylistEditor"/> methods,
  111.        ''' and has any effect for other purposes.
  112.        ''' </summary>
  113.        ''' <value>The track index.</value>
  114.        Public Property Index As Integer
  115.  
  116.        ''' <summary>
  117.        ''' Gets or sets the track filepath.
  118.        ''' </summary>
  119.        ''' <value>The track filepath.</value>
  120.        Public Property Path As String
  121.  
  122.        ''' <summary>
  123.        ''' Gets or sets the track title.
  124.        ''' </summary>
  125.        ''' <value>The track title.</value>
  126.        Public Property Title As String
  127.  
  128.        ''' <summary>
  129.        ''' Gets or sets the track length.
  130.        ''' </summary>
  131.        ''' <value>The track length.</value>
  132.        Public Property Length As TimeSpan
  133.  
  134. #End Region
  135.  
  136. #Region " Hidden Methods "
  137.  
  138.        ''' <summary>
  139.        ''' Serves as a hash function for a particular type.
  140.        ''' </summary>
  141.        <EditorBrowsable(EditorBrowsableState.Never)>
  142.        Public Shadows Sub GetHashCode()
  143.        End Sub
  144.  
  145.        ''' <summary>
  146.        ''' Determines whether the specified System.Object instances are considered equal.
  147.        ''' </summary>
  148.        <EditorBrowsable(EditorBrowsableState.Never)>
  149.        Public Shadows Sub Equals()
  150.        End Sub
  151.  
  152.        ''' <summary>
  153.        ''' Determines whether the specified System.Object instances are the same instance.
  154.        ''' </summary>
  155.        <EditorBrowsable(EditorBrowsableState.Never)>
  156.        Private Shadows Sub ReferenceEquals()
  157.        End Sub
  158.  
  159.        ''' <summary>
  160.        ''' Returns a String that represents the current object.
  161.        ''' </summary>
  162.        <EditorBrowsable(EditorBrowsableState.Never)>
  163.        Public Shadows Sub ToString()
  164.        End Sub
  165.  
  166. #End Region
  167.  
  168.    End Class
  169.  
  170. #End Region
  171.  
  172. #Region " Constructors "
  173.  
  174.    ''' <summary>
  175.    ''' Prevents a default instance of the <see cref="PlaylistEditor"/> class from being created.
  176.    ''' </summary>
  177.    Private Sub New()
  178.    End Sub
  179.  
  180.    ''' <summary>
  181.    ''' Initializes a new instance of the <see cref="PlaylistEditor"/> class.
  182.    ''' </summary>
  183.    ''' <param name="PlaylistFile">Indicates the playlist filepath.</param>
  184.    ''' <param name="PlaylistType">Indicates the type of the playlist.</param>
  185.    ''' <param name="Append">
  186.    ''' If set to <c>true</c> the <see cref="PlaylistEditor"/> instance will assume that the playlist file already exist,
  187.    ''' and will append any new entries in the existing file.
  188.    ''' If set to <c>false</c> the <see cref="PlaylistEditor"/> instance will assume that the playlist file does not exist,
  189.    ''' and will create the file.
  190.    ''' </param>
  191.    ''' <param name="FileEncoding">
  192.    ''' Optionally indicates the file encoding to write/read the playlist content.
  193.    ''' The default value is <see cref="Encoding.Default"/>
  194.    ''' </param>
  195.    Public Sub New(ByVal PlaylistFile As String,
  196.                   ByVal PlaylistType As PlaylistType,
  197.                   ByVal Append As Boolean,
  198.                   Optional ByVal FileEncoding As Encoding = Nothing)
  199.  
  200.        Me._FilePath = PlaylistFile
  201.        Me._Type = PlaylistType
  202.        Me._Encoding = If(FileEncoding IsNot Nothing, FileEncoding, Encoding.Default)
  203.        Me._Append = Append
  204.  
  205.        If Not _Append Then
  206.            Me.AddHeaders()
  207.        End If
  208.  
  209.    End Sub
  210.  
  211. #End Region
  212.  
  213. #Region " Hidden Methods "
  214.  
  215.    ''' <summary>
  216.    ''' Serves as a hash function for a particular type.
  217.    ''' </summary>
  218.    <EditorBrowsable(EditorBrowsableState.Never)>
  219.    Public Shadows Sub GetHashCode()
  220.    End Sub
  221.  
  222.    ''' <summary>
  223.    ''' Determines whether the specified System.Object instances are considered equal.
  224.    ''' </summary>
  225.    <EditorBrowsable(EditorBrowsableState.Never)>
  226.    Public Shadows Sub Equals()
  227.    End Sub
  228.  
  229.    ''' <summary>
  230.    ''' Determines whether the specified System.Object instances are the same instance.
  231.    ''' </summary>
  232.    <EditorBrowsable(EditorBrowsableState.Never)>
  233.    Private Shadows Sub ReferenceEquals()
  234.    End Sub
  235.  
  236.    ''' <summary>
  237.    ''' Returns a String that represents the current object.
  238.    ''' </summary>
  239.    <EditorBrowsable(EditorBrowsableState.Never)>
  240.    Public Shadows Sub ToString()
  241.    End Sub
  242.  
  243. #End Region
  244.  
  245. #Region " Private Methods "
  246.  
  247.    ''' <summary>
  248.    ''' Adds the playlist headers in the playlist file.
  249.    ''' This method should be called first before add any entry in the playlist.
  250.    ''' </summary>
  251.    Private Sub AddHeaders()
  252.  
  253.        Dim sb As New StringBuilder
  254.  
  255.        Select Case Me._Type
  256.  
  257.            Case PlaylistType.M3U
  258.                sb.AppendLine("#EXTM3U")
  259.  
  260.            Case PlaylistType.PLS
  261.                With sb
  262.                    .AppendLine("[playlist]")
  263.                    .AppendLine("NumberOfEntries=0")
  264.                    .AppendLine("Version=2")
  265.                End With
  266.  
  267.        End Select
  268.  
  269.        File.WriteAllText(Me._FilePath, sb.ToString, Me._Encoding)
  270.        sb.Clear()
  271.  
  272.    End Sub
  273.  
  274.    ''' <summary>
  275.    ''' Gets the amount of total entries of a PLS playlist file.
  276.    ''' </summary>
  277.    ''' <returns>The current number of total entries.</returns>
  278.    Private Function GetPLSNumberOfEntries() As Integer
  279.  
  280.        Dim PlaylistContent As String = File.ReadAllText(Me._FilePath, Me._Encoding)
  281.  
  282.        Dim StartIndex As Integer =
  283.            PlaylistContent.IndexOf("=") + 1I
  284.  
  285.        Dim EndIndex As Integer =
  286.            PlaylistContent.IndexOf(ControlChars.NewLine, StartIndex) - StartIndex
  287.  
  288.        Return PlaylistContent.Substring(StartIndex, PlaylistContent.IndexOf(String.Empty, EndIndex))
  289.  
  290.    End Function
  291.  
  292.    ''' <summary>
  293.    ''' Fixes the track index count of a PLS playlist file.
  294.    ''' This method shoould be called after remove a track from the playlist.
  295.    ''' </summary>
  296.    Private Sub FixPLSTrackIndex()
  297.  
  298.        Dim PlaylistContent As List(Of String) = File.ReadAllLines(Me._FilePath, Me._Encoding).ToList
  299.        Dim TrackCount As Integer = 0I
  300.  
  301.        For Index As Integer = 0 To (PlaylistContent.Count - 1I)
  302.  
  303.            If PlaylistContent(Index).StartsWith("File", StringComparison.OrdinalIgnoreCase) Then
  304.  
  305.                TrackCount += 1I
  306.  
  307.                PlaylistContent(Index) = String.Format("File{0}={1}",
  308.                                                       CStr(TrackCount),
  309.                                                       PlaylistContent(Index).Substring(PlaylistContent(Index).IndexOf("="c) + 1I))
  310.  
  311.            ElseIf PlaylistContent(Index).StartsWith("Title", StringComparison.OrdinalIgnoreCase) Then
  312.                PlaylistContent(Index) = String.Format("Title{0}={1}",
  313.                                                       CStr(TrackCount),
  314.                                                       PlaylistContent(Index).Substring(PlaylistContent(Index).IndexOf("="c) + 1I))
  315.  
  316.            ElseIf PlaylistContent(Index).StartsWith("Length", StringComparison.OrdinalIgnoreCase) Then
  317.                PlaylistContent(Index) = String.Format("Length{0}={1}",
  318.                                                       CStr(TrackCount),
  319.                                                       PlaylistContent(Index).Substring(PlaylistContent(Index).IndexOf("="c) + 1I))
  320.  
  321.            End If
  322.  
  323.        Next Index
  324.  
  325.        Dim NumberOfEntriesEntryIndex As Integer =
  326.            PlaylistContent.FindIndex(Function(Item As String)
  327.                                          Return Item.ToLower Like "numberofentries=#*"
  328.                                      End Function)
  329.  
  330.        PlaylistContent(NumberOfEntriesEntryIndex) =
  331.            String.Format("NumberOfEntries={0}", CStr(TrackCount))
  332.  
  333.        File.WriteAllLines(Me._FilePath, PlaylistContent, Me._Encoding)
  334.  
  335.    End Sub
  336.  
  337. #End Region
  338.  
  339. #Region " Public Methods "
  340.  
  341.    ''' <summary>
  342.    ''' Adds a new track entry in the playlist.
  343.    ''' </summary>
  344.    ''' <param name="Path">Indicates the track path to add.</param>
  345.    ''' <param name="AllowDuplicate">
  346.    ''' If set to <c>true</c> an exception will be thrown if the track already exists in the playlist.
  347.    ''' </param>
  348.    ''' <exception cref="System.Exception">The TrackPath already exist in the playlist.</exception>
  349.    Public Sub Add(ByVal [Path] As String,
  350.                   Optional ByVal AllowDuplicate As Boolean = False)
  351.  
  352.        If Not AllowDuplicate AndAlso Me.Exist([Path]) Then
  353.            Throw New Exception("The TrackPath already exist in the playlist.") With {.Source = [Path]}
  354.        End If
  355.  
  356.        Dim sb As New StringBuilder
  357.  
  358.        Select Case Me._Type
  359.  
  360.            Case PlaylistType.M3U
  361.  
  362.                With sb
  363.                    .AppendLine()
  364.                    .AppendLine([Path])
  365.                    File.AppendAllText(Me._FilePath, .ToString, Me._Encoding)
  366.                    .Clear()
  367.  
  368.                End With
  369.  
  370.            Case PlaylistType.PLS
  371.  
  372.                Dim EntryCount As Integer = Me.GetPLSNumberOfEntries()
  373.  
  374.                With sb
  375.  
  376.                    .AppendLine(File.ReadAllText(Me._FilePath, Me._Encoding).
  377.                                     Replace("NumberOfEntries=" & CStr(EntryCount),
  378.                                             "NumberOfEntries=" & CStr(EntryCount + 1I)))
  379.  
  380.                    .AppendLine(String.Format("File{0}={1}", CStr(EntryCount + 1I), [Path].Replace("\", "/")))
  381.  
  382.                    File.WriteAllText(Me._FilePath, .ToString, Me._Encoding)
  383.                    .Clear()
  384.  
  385.                End With
  386.  
  387.        End Select
  388.  
  389.    End Sub
  390.  
  391.    ''' <summary>
  392.    ''' Adds a new track entry in the playlist, with extended track information.
  393.    ''' </summary>
  394.    ''' <param name="Path">Indicates the track to add.</param>
  395.    ''' <param name="Title">Indicates the track title.</param>
  396.    ''' <param name="Length">Indicates the track length.</param>
  397.    Public Sub Add(ByVal [Path] As String,
  398.                   ByVal Title As String,
  399.                   ByVal Length As TimeSpan,
  400.                   Optional ByVal AllowDuplicate As Boolean = False)
  401.  
  402.        If Not AllowDuplicate AndAlso Me.Exist([Path]) Then
  403.            Throw New Exception("The TrackPath already exist in the playlist.") With {.Source = [Path]}
  404.        End If
  405.  
  406.        Dim sb As New StringBuilder
  407.  
  408.        Select Case Me._Type
  409.  
  410.            Case PlaylistType.M3U
  411.  
  412.                With sb
  413.  
  414.                    .AppendLine()
  415.                    .AppendLine(String.Format("#EXTINF:{0},{1}",
  416.                                                CStr(Math.Truncate(Length.TotalSeconds)),
  417.                                                Title))
  418.                    .AppendLine([Path])
  419.  
  420.                    File.AppendAllText(Me._FilePath, .ToString, Me._Encoding)
  421.                    .Clear()
  422.  
  423.                End With
  424.  
  425.            Case PlaylistType.PLS
  426.  
  427.                Dim EntryCount As Integer = Me.GetPLSNumberOfEntries()
  428.  
  429.                With sb
  430.  
  431.                    .AppendLine(File.ReadAllText(Me._FilePath, Me._Encoding).
  432.                                     Replace("NumberOfEntries=" & CStr(EntryCount),
  433.                                             "NumberOfEntries=" & CStr(EntryCount + 1I)))
  434.  
  435.                    .AppendLine(String.Format("File{0}={1}", CStr(EntryCount + 1I), [Path].Replace("\", "/")))
  436.                    .AppendLine(String.Format("Title{0}={1}", CStr(EntryCount + 1I), Title))
  437.                    .AppendLine(String.Format("Length{0}={1}", CStr(EntryCount + 1I), CStr(Math.Truncate(Length.TotalSeconds))))
  438.  
  439.                    File.WriteAllText(Me._FilePath, .ToString, Me._Encoding)
  440.                    .Clear()
  441.  
  442.                End With
  443.  
  444.        End Select
  445.  
  446.    End Sub
  447.  
  448.    ''' <summary>
  449.    ''' Adds a new track entry in the playlist, with extended track information.
  450.    ''' </summary>
  451.    ''' <param name="TrackInfo">A <see cref="TrackInfo"/> instance containing the extended track information.</param>
  452.    Public Sub Add(ByVal TrackInfo As TrackInfo,
  453.                   Optional ByVal AllowDuplicate As Boolean = False)
  454.  
  455.        Me.Add(TrackInfo.Path, TrackInfo.Title, TrackInfo.Length, AllowDuplicate)
  456.  
  457.    End Sub
  458.  
  459.    ''' <summary>
  460.    ''' Removes the specified track entry from the playlist.
  461.    ''' </summary>
  462.    ''' <param name="Path">Indicates the track path to remove it's entry.</param>
  463.    ''' <exception cref="System.Exception">The TrackPath was not found in the playlist.</exception>
  464.    Public Sub Remove(ByVal [Path] As String)
  465.  
  466.        If Not Me.Exist([Path]) Then
  467.            Throw New Exception("The TrackPath was not found in the playlist.") With {.Source = [Path]}
  468.        End If
  469.  
  470.        Dim PlaylistContent As List(Of String) = File.ReadAllLines(Me._FilePath, Me._Encoding).ToList
  471.  
  472.        Select Case Me._Type
  473.  
  474.            Case PlaylistType.M3U
  475.  
  476.                Dim EntryIndex As Integer =
  477.                    PlaylistContent.FindIndex(Function(Item As String)
  478.                                                  Return Item.Equals([Path], StringComparison.OrdinalIgnoreCase)
  479.                                              End Function)
  480.  
  481.                PlaylistContent.RemoveAt(EntryIndex)
  482.  
  483.                If PlaylistContent(EntryIndex - 1).StartsWith("#EXTINF", StringComparison.OrdinalIgnoreCase) Then
  484.                    PlaylistContent.RemoveAt(EntryIndex - 1)
  485.                End If
  486.  
  487.                File.WriteAllLines(Me._FilePath, PlaylistContent, Me._Encoding)
  488.  
  489.            Case PlaylistType.PLS
  490.  
  491.                Dim EntryIndex As Integer =
  492.                    PlaylistContent.FindIndex(Function(Item As String)
  493.                                                  Return Item.ToLower Like "file#*" & [Path].Replace("\", "/").ToLower
  494.                                              End Function)
  495.  
  496.                Dim TrackIndexDelimStartIndex As Integer =
  497.                    PlaylistContent(EntryIndex).IndexOf("e", StringComparison.OrdinalIgnoreCase) + 1I
  498.  
  499.                Dim TrackIndexDelimEndIndex As Integer =
  500.                    PlaylistContent(EntryIndex).IndexOf("=", StringComparison.OrdinalIgnoreCase)
  501.  
  502.                Dim TrackIndex As Integer =
  503.                    PlaylistContent(EntryIndex).Substring(TrackIndexDelimStartIndex,
  504.                                                          TrackIndexDelimEndIndex - TrackIndexDelimStartIndex)
  505.  
  506.                PlaylistContent.RemoveAt(EntryIndex)
  507.  
  508.                Dim TitleEntryIndex As Integer =
  509.                    PlaylistContent.FindIndex(Function(Item As String)
  510.                                                  Return Item.ToLower Like String.Format("title{0}=*", CStr(TrackIndex))
  511.                                              End Function)
  512.  
  513.                If TitleEntryIndex <> -1I Then
  514.                    PlaylistContent.RemoveAt(TitleEntryIndex)
  515.                End If
  516.  
  517.                Dim LengthEntryIndex As Integer =
  518.                    PlaylistContent.FindIndex(Function(Item As String)
  519.                                                  Return Item.ToLower Like String.Format("length{0}=*", CStr(TrackIndex))
  520.                                              End Function)
  521.  
  522.                If LengthEntryIndex <> -1I Then
  523.                    PlaylistContent.RemoveAt(LengthEntryIndex)
  524.                End If
  525.  
  526.                Dim NumberOfEntriesEntryIndex As Integer =
  527.                    PlaylistContent.FindIndex(Function(Item As String)
  528.                                                  Return Item.ToLower Like "numberofentries=#*"
  529.                                              End Function)
  530.  
  531.                PlaylistContent(NumberOfEntriesEntryIndex) =
  532.                    String.Format("NumberOfEntries={0}", CStr(Me.GetPLSNumberOfEntries() - 1I))
  533.  
  534.                File.WriteAllLines(Me._FilePath, PlaylistContent, Me._Encoding)
  535.  
  536.                Me.FixPLSTrackIndex()
  537.  
  538.        End Select
  539.  
  540.    End Sub
  541.  
  542.    ''' <summary>
  543.    ''' Removes the specified track entry from the playlist.
  544.    ''' </summary>
  545.    ''' <param name="TrackIndex">Indicates the track index to remove it's entry.</param>
  546.    ''' <exception cref="System.IndexOutOfRangeException">TrackIndex is out of range</exception>
  547.    Public Sub Remove(ByVal TrackIndex As Integer)
  548.  
  549.        Dim Track = Me.GetTrack(TrackIndex)
  550.  
  551.        If Track IsNot Nothing Then
  552.            Me.Remove(Track.Path)
  553.        Else
  554.            Throw New IndexOutOfRangeException("TrackIndex is out of range") With {.Source = TrackIndex}
  555.        End If
  556.  
  557.    End Sub
  558.  
  559.    ''' <summary>
  560.    ''' Sets the extended track info of the specified track.
  561.    ''' </summary>
  562.    ''' <param name="Path">Indicates the track path to set its extended track info.</param>
  563.    ''' <param name="TrackInfo">A <see cref="TrackInfo" /> instance containing the extended info to set.</param>
  564.    ''' <exception cref="System.Exception">The TrackPath was not found in the playlist.</exception>
  565.    Public Sub [Set](ByVal [Path] As String,
  566.                     ByVal TrackInfo As TrackInfo)
  567.  
  568.        If Not Me.Exist([Path]) Then
  569.            Throw New Exception("The TrackPath was not found in the playlist.") With {.Source = [Path]}
  570.        End If
  571.  
  572.        Dim Track As TrackInfo = Me.GetTrack([Path])
  573.        With Track
  574.            .Path = TrackInfo.Path
  575.            .Title = TrackInfo.Title
  576.            .Length = TrackInfo.Length
  577.        End With
  578.  
  579.        Dim PlaylistContent As List(Of String) = File.ReadAllLines(Me._FilePath, Me._Encoding).ToList
  580.  
  581.        Select Case Me._Type
  582.  
  583.            Case PlaylistType.M3U
  584.  
  585.                Dim EntryIndex As Integer =
  586.                    PlaylistContent.FindIndex(Function(Item As String)
  587.                                                  Return Item.Equals([Path], StringComparison.OrdinalIgnoreCase)
  588.                                              End Function)
  589.  
  590.                PlaylistContent(EntryIndex) = String.Format("#EXTINF:{0},{1}",
  591.                                                            CStr(Math.Truncate(Track.Length.TotalSeconds)),
  592.                                                            Track.Title) & Environment.NewLine & Track.Path
  593.  
  594.                If PlaylistContent(EntryIndex - 1I).StartsWith("#EXTINF", StringComparison.OrdinalIgnoreCase) Then
  595.                    PlaylistContent.RemoveAt(EntryIndex - 1I)
  596.                End If
  597.  
  598.                File.WriteAllLines(Me._FilePath, PlaylistContent, Me._Encoding)
  599.  
  600.            Case PlaylistType.PLS
  601.  
  602.                Track.Path = Track.Path.Replace("\", "/")
  603.  
  604.                Dim EntryIndex As Integer =
  605.                    PlaylistContent.FindIndex(Function(Item As String)
  606.                                                  Return Item.ToLower Like "file#*" & [Path].Replace("\", "/").ToLower
  607.                                              End Function)
  608.  
  609.                PlaylistContent(EntryIndex) = String.Format("File{0}={1}", CStr(Track.Index), Track.Path) & Environment.NewLine &
  610.                                              String.Format("Title{0}={1}", CStr(Track.Index), Track.Title) & Environment.NewLine &
  611.                                              String.Format("Length{0}={1}", CStr(Track.Index), CStr(Math.Truncate(Track.Length.TotalSeconds)))
  612.  
  613.                If PlaylistContent.Count > (EntryIndex + 1) Then
  614.  
  615.                    If PlaylistContent(EntryIndex + 2I).StartsWith("Title", StringComparison.OrdinalIgnoreCase) _
  616.                    OrElse PlaylistContent(EntryIndex + 2I).StartsWith("Length", StringComparison.OrdinalIgnoreCase) Then
  617.  
  618.                        PlaylistContent.RemoveAt(EntryIndex + 2I)
  619.  
  620.                    End If
  621.  
  622.                End If
  623.  
  624.                If PlaylistContent.Count > EntryIndex Then
  625.  
  626.                    If PlaylistContent(EntryIndex + 1I).StartsWith("Title", StringComparison.OrdinalIgnoreCase) _
  627.                    OrElse PlaylistContent(EntryIndex + 1I).StartsWith("Length", StringComparison.OrdinalIgnoreCase) Then
  628.  
  629.                        PlaylistContent.RemoveAt(EntryIndex + 1I)
  630.  
  631.                    End If
  632.  
  633.                End If
  634.  
  635.                File.WriteAllLines(Me._FilePath, PlaylistContent, Me._Encoding)
  636.  
  637.        End Select
  638.  
  639.    End Sub
  640.  
  641.    ''' <summary>
  642.    ''' Sets the extended track info of the specified track.
  643.    ''' </summary>
  644.    ''' <param name="TrackIndex">Indicates the track index to set its extended track info.</param>
  645.    ''' <param name="TrackInfo">A <see cref="TrackInfo" /> instance containing the extended info to set.</param>
  646.    ''' <exception cref="System.IndexOutOfRangeException">TrackIndex is out of range</exception>
  647.    Public Sub [Set](ByVal TrackIndex As Integer,
  648.                     ByVal TrackInfo As TrackInfo)
  649.  
  650.        If Not Me.Exist(TrackIndex) Then
  651.            Throw New IndexOutOfRangeException("TrackIndex is out of range") With {.Source = TrackIndex}
  652.        End If
  653.  
  654.        Me.[Set](Me.GetTrack(TrackIndex).Path, TrackInfo)
  655.  
  656.    End Sub
  657.  
  658.    ''' <summary>
  659.    ''' Gets the extended track information (if any) of the specified track in the playlist.
  660.    ''' </summary>
  661.    ''' <param name="Path">Indicates the track path.</param>
  662.    ''' <returns>
  663.    ''' If the track contains extended iformation,
  664.    ''' the return value is a <see cref="TrackInfo"/> instance containing the track info.
  665.    ''' Otherwise, the return value is an emptiness <see cref="TrackInfo"/> instance.
  666.    ''' </returns>
  667.    Public Function GetTrack(ByVal Path As String) As TrackInfo
  668.  
  669.        Dim PlaylistContent As List(Of String) = File.ReadAllLines(Me._FilePath, Me._Encoding).ToList
  670.        Dim TInfo As New TrackInfo
  671.  
  672.        Select Case Me._Type
  673.  
  674.            Case PlaylistType.M3U
  675.  
  676.                Dim EntryIndex As Integer = PlaylistContent.FindIndex(Function(Item As String)
  677.                                                                          Return Item.Equals([Path], StringComparison.OrdinalIgnoreCase)
  678.                                                                      End Function) - 1I
  679.  
  680.                If PlaylistContent(EntryIndex).StartsWith("#EXTINF", StringComparison.OrdinalIgnoreCase) Then
  681.  
  682.                    Dim TitleDelimIndex As Integer = PlaylistContent(EntryIndex).IndexOf(","c) + 1I
  683.                    Dim LengthDelimIndex As Integer = PlaylistContent(EntryIndex).IndexOf(":"c) + 1I
  684.  
  685.                    With TInfo
  686.  
  687.                        '.Index = EntryIndex
  688.                        .Path = [Path]
  689.                        .Title = PlaylistContent(EntryIndex).Substring(TitleDelimIndex)
  690.                        .Length = TimeSpan.FromSeconds(PlaylistContent(EntryIndex).Substring(LengthDelimIndex,
  691.                                                                                             (TitleDelimIndex - LengthDelimIndex)))
  692.                    End With
  693.  
  694.                End If
  695.  
  696.            Case PlaylistType.PLS
  697.  
  698.                [Path] = [Path].Replace("\", "/")
  699.  
  700.                Dim Entry As String = (From Item As String In PlaylistContent
  701.                                       Where Item.ToLower Like String.Format("file#*={0}", [Path].ToLower)).FirstOrDefault
  702.  
  703.                If Not String.IsNullOrEmpty(Entry) Then
  704.  
  705.                    Dim IndexDelimStartIndex As Integer =
  706.                        Entry.IndexOf("e", StringComparison.OrdinalIgnoreCase) + 1I
  707.  
  708.                    Dim IndexDelimEndIndex As Integer =
  709.                        Entry.IndexOf("=", StringComparison.OrdinalIgnoreCase)
  710.  
  711.                    Dim EntryIndex As Integer = Entry.Substring(IndexDelimStartIndex,
  712.                                                                IndexDelimEndIndex - IndexDelimStartIndex)
  713.  
  714.                    Dim TitleEntry As String = (From Item As String In PlaylistContent
  715.                                                Where Item.StartsWith(String.Format("Title{0}=", CStr(EntryIndex)), StringComparison.OrdinalIgnoreCase)).
  716.                                                FirstOrDefault
  717.  
  718.                    Dim LengthEntry As String = (From Item As String In PlaylistContent
  719.                                                 Where Item.StartsWith(String.Format("Length{0}=", CStr(EntryIndex)), StringComparison.OrdinalIgnoreCase)).
  720.                                                 FirstOrDefault
  721.  
  722.                    With TInfo
  723.  
  724.                        .Index = EntryIndex
  725.  
  726.                        .Path = [Path]
  727.  
  728.                        .Title = If(Not String.IsNullOrEmpty(TitleEntry),
  729.                                    TitleEntry.Substring(TitleEntry.IndexOf("=") + 1I),
  730.                                    Nothing)
  731.  
  732.                        .Length = If(Not String.IsNullOrEmpty(TitleEntry),
  733.                                     TimeSpan.FromSeconds(LengthEntry.Split("=").LastOrDefault),
  734.                                     Nothing)
  735.  
  736.                    End With
  737.  
  738.                End If
  739.  
  740.        End Select
  741.  
  742.        Return TInfo
  743.  
  744.    End Function
  745.  
  746.    ''' <summary>
  747.    ''' Gets the track path and its extended track information (if any) of the specified track index in the playlist.
  748.    ''' </summary>
  749.    ''' <param name="TrackIndex">Indicates the track index.</param>
  750.    ''' <returns>
  751.    ''' If the track index exist,
  752.    ''' the return value is a <see cref="TrackInfo"/> instance containing the track path and its extended info (if any).
  753.    ''' Otherwise, the return value is <c>Nothing</c>.
  754.    ''' </returns>
  755.    Public Function GetTrack(ByVal TrackIndex As Integer) As TrackInfo
  756.  
  757.        Dim PlaylistContent As List(Of String) = File.ReadAllLines(Me._FilePath, Me._Encoding).ToList
  758.  
  759.        Select Case Me._Type
  760.  
  761.            Case PlaylistType.M3U
  762.  
  763.                Dim TrackCount As Integer = 0I
  764.  
  765.                For Index As Integer = 0I To (PlaylistContent.Count - 1I)
  766.  
  767.                    If Not String.IsNullOrEmpty(PlaylistContent(Index)) _
  768.                       AndAlso Not PlaylistContent(Index).StartsWith("#EXT", StringComparison.OrdinalIgnoreCase) Then
  769.  
  770.                        TrackCount += 1I
  771.  
  772.                        If TrackCount = TrackIndex Then
  773.  
  774.                            Dim TInfo As TrackInfo = Me.GetTrack(PlaylistContent(Index))
  775.                            With TInfo
  776.                                .Index = TrackIndex
  777.                                .Path = PlaylistContent(Index)
  778.                            End With
  779.  
  780.                            Return TInfo
  781.  
  782.                        End If
  783.  
  784.                    End If
  785.  
  786.                Next Index
  787.  
  788.            Case PlaylistType.PLS
  789.  
  790.                For Index As Integer = 0I To (PlaylistContent.Count - 1I)
  791.  
  792.                    If PlaylistContent(Index).StartsWith(String.Format("File{0}=", CStr(TrackIndex)),
  793.                                                         StringComparison.OrdinalIgnoreCase) Then
  794.  
  795.                        Return Me.GetTrack(PlaylistContent(Index).Substring(PlaylistContent(Index).IndexOf("="c) + 1I))
  796.  
  797.                    End If
  798.  
  799.                Next Index
  800.  
  801.        End Select
  802.  
  803.        Return Nothing
  804.  
  805.    End Function
  806.  
  807.    ''' <summary>
  808.    ''' Gets all the tracks and its extended track information (if any) in the playlist.
  809.    ''' </summary>
  810.    ''' <returns>
  811.    ''' A <see cref="List(Of TrackInfo)"/> object containing the track entries and its extended info (if any).
  812.    ''' </returns>
  813.    Public Function GetTracks() As List(Of TrackInfo)
  814.  
  815.        Dim PlaylistContent As List(Of String) = File.ReadAllLines(Me._FilePath, Me._Encoding).ToList
  816.        Dim TInfo As New List(Of TrackInfo)
  817.        Dim TrackCount As Integer = 0I
  818.  
  819.        Select Case Me._Type
  820.  
  821.            Case PlaylistType.M3U
  822.  
  823.                For Index As Integer = 0I To (PlaylistContent.Count - 1I)
  824.  
  825.                    If Not String.IsNullOrEmpty(PlaylistContent(Index)) _
  826.                       AndAlso Not PlaylistContent(Index).StartsWith("#EXT", StringComparison.OrdinalIgnoreCase) Then
  827.  
  828.                        TrackCount += 1
  829.                        TInfo.Add(Me.GetTrack(TrackCount))
  830.  
  831.                    End If
  832.  
  833.                Next
  834.  
  835.            Case PlaylistType.PLS
  836.  
  837.                For Index As Integer = 0I To (PlaylistContent.Count - 1I)
  838.  
  839.                    If PlaylistContent(Index).StartsWith("File", StringComparison.OrdinalIgnoreCase) Then
  840.  
  841.                        TrackCount += 1I
  842.                        TInfo.Add(Me.GetTrack(TrackCount))
  843.  
  844.                    End If
  845.  
  846.                Next Index
  847.  
  848.        End Select
  849.  
  850.        Return TInfo
  851.  
  852.    End Function
  853.  
  854.    ''' <summary>
  855.    ''' Determines whether the specified track exists in the playlist.
  856.    ''' </summary>
  857.    ''' <param name="Path">Indicates the track path.</param>
  858.    ''' <returns>
  859.    ''' <c>true</c> if the track already exists in the playlist, <c>false</c> otherwise.
  860.    ''' </returns>
  861.    Public Function Exist(ByVal [Path] As String) As Boolean
  862.  
  863.        Dim ReturnValue As Boolean = False
  864.  
  865.        Select Case Me._Type
  866.  
  867.            Case PlaylistType.M3U
  868.  
  869.                ReturnValue = (From Item As String In File.ReadAllLines(Me._FilePath, Me._Encoding)
  870.                               Where Item.StartsWith([Path], StringComparison.OrdinalIgnoreCase)).
  871.                               Any()
  872.  
  873.            Case PlaylistType.PLS
  874.  
  875.                ReturnValue = (From Item As String In File.ReadAllLines(Me._FilePath, Me._Encoding)
  876.                               Where Item.ToLower Like "file#*" & [Path].Replace("\", "/").ToLower).
  877.                               Any()
  878.  
  879.        End Select
  880.  
  881.        Return ReturnValue
  882.  
  883.    End Function
  884.  
  885.    ''' <summary>
  886.    ''' Determines whether the specified track exists in the playlist.
  887.    ''' </summary>
  888.    ''' <param name="TrackIndex">Indicates the track index.</param>
  889.    ''' <returns><c>true</c> if the track already exists in the playlist, <c>false</c> otherwise.</returns>
  890.    ''' <exception cref="System.IndexOutOfRangeException">TrackIndex should be greater than 0.</exception>
  891.    Public Function Exist(ByVal TrackIndex As Integer) As Boolean
  892.  
  893.        If TrackIndex <= 0 Then
  894.            Throw New IndexOutOfRangeException("TrackIndex should be greater than 0.") With {.Source = TrackIndex}
  895.        End If
  896.  
  897.        Return (Me.Count >= TrackIndex)
  898.  
  899.    End Function
  900.  
  901.    ''' <summary>
  902.    ''' Counts the amount of track entries in the playlist.
  903.    ''' </summary>
  904.    ''' <returns>
  905.    ''' The amount of track entries in the playlist.
  906.    ''' </returns>
  907.    Public Function Count() As Integer
  908.  
  909.        Return Me.GetTracks.Count
  910.  
  911.    End Function
  912.  
  913. #End Region
  914.  
  915. End Class
  916.  
  917. #End Region
  918.  


« Última modificación: 22 Julio 2014, 02:26 am por Eleкtro » En línea

XresH


Desconectado Desconectado

Mensajes: 384



Ver Perfil WWW
Re: [APORTE] Multimedia Playlist Editor (M3U y PLS)
« Respuesta #2 en: 22 Julio 2014, 20:41 pm »

Se ve bastante completo, aunque creo que hay cosas que podrias reducir, hace años hice un reproductor y me hubiera venido bien este code, gracias por el aporte.

Saludos.
En línea

[ - Si eres programador y quieres que tus proyectos esten en mi blog(con o sin source), consúltame! - ]
Entra A Mi Blog De Programación | | Dudas en este post :| | >>Clic para ir al Post<<
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Como transformar archivos extension m3u de playlist a mp3
Multimedia
cerebral 5 9,180 Último mensaje 3 Agosto 2004, 02:29 am
por cerebral
Grabar un cd multimedia protegido (Mecanografia Multimedia)
Software
napaji 1 2,570 Último mensaje 18 Febrero 2005, 09:51 am
por Ner0n
aporte - Editor de codigo fuente de varios lenguaje « 1 2 »
Programación Visual Basic
d(-_-)b 13 5,912 Último mensaje 18 Julio 2007, 02:09 am
por Freeze.
pequeño aporte(proxy),pero aporte al fin.:D
Programación Visual Basic
Tengu 0 2,398 Último mensaje 22 Julio 2007, 17:33 pm
por Tengu
(APORTE) Sublime Text Editor 2 (El mejor editor que he conocido)
Software
Eleкtro 8 9,166 Último mensaje 22 Febrero 2012, 02:28 am
por raul338
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines