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

 

 


Tema destacado: Rompecabezas de Bitcoin, Medio millón USD en premios


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
0 Usuarios y 2 Visitantes están viendo este tema.
Páginas: 1 ... 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 [31] 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 ... 60 Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 529,366 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.878



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #300 en: 20 Septiembre 2013, 16:45 pm »

· Detectar la codificación de un archivo de texto

(Para quien no entienda de BOM's y codificaciones, no existe una manera 100% fiable de detectar la codificación y puede dar falsos positivos)


Código
  1. #Region " Detect Text Encoding "
  2.  
  3.    ' [ Detect Text Encoding Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' MsgBox(Detect_Text_Encoding("C:\ANSI File.txt").ToString) ' Result: System.Text.SBCSCodePageEncoding
  8.    ' MsgBox(Detect_Text_Encoding("C:\UTF8 File.txt").ToString) ' Result: System.Text.UTF8Encoding
  9.  
  10.  
  11.    Public Function Detect_Text_Encoding(TextFile As String) As System.Text.Encoding
  12.  
  13.        Dim Bytes() As Byte = IO.File.ReadAllBytes(TextFile)
  14.  
  15.        Dim detectedEncoding As System.Text.Encoding = Nothing
  16.  
  17.        For Each info As System.Text.EncodingInfo In System.Text.Encoding.GetEncodings()
  18.  
  19.            Dim currentEncoding As System.Text.Encoding = info.GetEncoding()
  20.            Dim preamble() As Byte = currentEncoding.GetPreamble()
  21.            Dim match As Boolean = True
  22.  
  23.            If (preamble.Length > 0) And (preamble.Length <= Bytes.Length) Then
  24.  
  25.                For i As Integer = 0 To preamble.Length - 1
  26.  
  27.                    If preamble(i) <> Bytes(i) Then
  28.                        match = False
  29.                        Exit For
  30.                    End If
  31.  
  32.                Next i
  33.  
  34.            Else
  35.  
  36.                match = False
  37.  
  38.            End If
  39.  
  40.            If match Then
  41.                detectedEncoding = currentEncoding
  42.                Exit For
  43.            End If
  44.  
  45.        Next info
  46.  
  47.        If detectedEncoding Is Nothing Then
  48.            Return System.Text.Encoding.Default
  49.        Else
  50.            Return detectedEncoding
  51.        End If
  52.  
  53.    End Function
  54.  
  55. #End Region


En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.878



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #301 en: 26 Septiembre 2013, 12:18 pm »

Permitir la escritura de 1 solo caracter en un textbox y deshabilitar el menú contextual, tiene algunas diferencias de la propiedad "MaxLength", no pega el primer caracter de una palabra del clipboards si la longitud de la palabra es de 1 caracter (es un code un poco "custom", util para especificar delimitadores de texto de un solo caracter, o cosas parecidas)

Código
  1. #Region " [TextBox] Allow only 1 Character "
  2.  
  3.    ' By Elektro H@cker
  4.  
  5.  
  6.    ' TextBox [Enter]
  7.    Private Sub TextBox_Enter(sender As Object, e As EventArgs) ' Handles TextBox1.MouseEnter
  8.  
  9.        ' Allign the character in the TextBox space
  10.        ' If Not TextBox_Separator.TextAlign = HorizontalAlignment.Center Then TextBox_Separator.TextAlign = HorizontalAlignment.Center Then
  11.  
  12.        ' Disable Copy/Paste contextmenu by creating a new one
  13.        If sender.ContextMenuStrip Is Nothing Then sender.ContextMenuStrip = New ContextMenuStrip
  14.  
  15.    End Sub
  16.  
  17.    ' TextBox [KeyPress]
  18.    Private Sub TextBox_KeyPress(sender As Object, e As KeyPressEventArgs) ' Handles TextBox1.KeyPress
  19.  
  20.        Select Case sender.TextLength
  21.  
  22.            Case 0 ' TextLength = 0
  23.  
  24.                Select Case e.KeyChar
  25.  
  26.                    Case Chr(22) ' CTRL+V is pressed
  27.  
  28.                        ' If Clipboard contains 0 or 1 character then paste the character.
  29.                        e.Handled = IIf(Clipboard.GetText.Length <= 1, False, True)
  30.  
  31.                    Case Else ' Other key is pressed
  32.                        e.Handled = False ' Print the character.
  33.  
  34.                End Select ' e.KeyChar when TextLength = 0
  35.  
  36.            Case 1 ' TextLength = 1
  37.  
  38.                Select Case e.KeyChar
  39.  
  40.                    Case Convert.ToChar(Keys.Back) ' Backspace is pressed
  41.                        e.Handled = False ' Delete the character
  42.  
  43.                    Case Chr(22) ' CTRL+V is pressed
  44.  
  45.                        Select Case sender.SelectionLength
  46.  
  47.                            Case 1 ' If 1 character is selected
  48.                                ' If Clipboard contains 0 or 1 character then paste the character.
  49.                                e.Handled = IIf(Clipboard.GetText.Length <= 1, False, True)
  50.  
  51.                            Case Else ' If any text is selected
  52.                                e.Handled = True ' Don't paste the characters.
  53.  
  54.                        End Select
  55.  
  56.                    Case Else ' Other key is pressed
  57.                        ' If any text is selected then don't print the character.
  58.                        e.Handled = IIf(sender.SelectionLength = 1, False, True)
  59.  
  60.                End Select ' e.KeyChar when TextLength = 1
  61.  
  62.        End Select ' TextLength
  63.  
  64.    End Sub
  65.  
  66.    ' TextBox [TextChanged]
  67.    Private Sub TextBox_TextChanged(sender As Object, e As EventArgs) ' Handles TextBox1.TextChanged
  68.  
  69.        ' // If NOT Text is empty then Save the character:
  70.        '
  71.        ' If Not String.IsNullOrEmpty(sender.text) _
  72.        ' Then My.Settings.User_Character = Convert.ToChar(sender.text)
  73.  
  74.    End Sub
  75.  
  76.    ' TextBox [Leave]
  77.    Private Sub TextBox_Leave(sender As Object, e As EventArgs) ' Handles TextBox1.Leave
  78.  
  79.        ' // If Text is empty then restore the last saved character:
  80.        '
  81.        ' If String.IsNullOrEmpty(sender.text) _
  82.        ' Then sender.text = My.Settings.User_Character
  83.  
  84.    End Sub
  85.  
  86. #End Region


« Última modificación: 29 Septiembre 2013, 18:41 pm por EleKtro H@cker » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.878



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #302 en: 30 Septiembre 2013, 17:10 pm »

Listar por el método Burbuja un Array de String o una Lista de String:

Código
  1. #Region " BubbleSort Array "
  2.  
  3.    ' BubbleSort Array
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' Dim MyArray As String() = {"10", "333", "2", "45"}
  8.    ' For Each item In BubbleSort_Array(myarray) : MsgBox(item) : Next ' Result: {"2", "10", "45", "333"}
  9.  
  10.    Private Function BubbleSort_Array(list As String()) As String()
  11.  
  12.        Return list.Select(Function(s) New With { _
  13.            Key .OrgStr = s, _
  14.            Key .SortStr = System.Text.RegularExpressions.Regex.Replace( _
  15.                           s, "(\d+)|(\D+)", _
  16.                           Function(m) m.Value.PadLeft(list.Select(Function(y) y.Length).Max, _
  17.                           If(Char.IsDigit(m.Value(0)), " "c, Char.MaxValue))) _
  18.        }).OrderBy(Function(x) x.SortStr).Select(Function(x) x.OrgStr).ToArray
  19.  
  20.    End Function
  21.  
  22. #End Region

Código
  1. #Region " BubbleSort IEnumerable(Of String) "
  2.  
  3.  
  4.    ' BubbleSort IEnumerable(Of String)
  5.    '
  6.    ' Examples :
  7.    '
  8.    ' Dim MyIEnumerable As IEnumerable(Of String) = {"10", "333", "2", "45"}
  9.    ' For Each item In BubbleSort_IEnumerable(MyIEnumerable) : MsgBox(item) : Next ' Result: {"2", "10", "45", "333"}
  10.  
  11.    Private Function BubbleSort_IEnumerable(list As IEnumerable(Of String)) As IEnumerable(Of String)
  12.  
  13.        Return list.Select(Function(s) New With { _
  14.            Key .OrgStr = s, _
  15.            Key .SortStr = System.Text.RegularExpressions.Regex.Replace( _
  16.                           s, "(\d+)|(\D+)", _
  17.                           Function(m) m.Value.PadLeft(list.Select(Function(y) y.Length).Max, _
  18.                           If(Char.IsDigit(m.Value(0)), " "c, Char.MaxValue))) _
  19.        }).OrderBy(Function(x) x.SortStr).Select(Function(x) x.OrgStr)
  20.  
  21.    End Function
  22.  
  23. #End Region

Código
  1. #Region " BubbleSort List(Of String) "
  2.  
  3.  
  4.    ' BubbleSort List(Of String)
  5.    '
  6.    ' Examples :
  7.    '
  8.    ' Dim MyList As New List(Of String) From {"10", "333", "2", "45"}
  9.    ' For Each item In BubbleSort_List(MyList) : MsgBox(item) : Next ' Result: {"2", "10", "45", "333"}
  10.  
  11.    Private Function BubbleSort_List(list As List(Of String)) As List(Of String)
  12.  
  13.        Return list.Select(Function(s) New With { _
  14.            Key .OrgStr = s, _
  15.            Key .SortStr = System.Text.RegularExpressions.Regex.Replace( _
  16.                           s, "(\d+)|(\D+)", _
  17.                           Function(m) m.Value.PadLeft(list.Select(Function(x) x.Length).Max, _
  18.                           If(Char.IsDigit(m.Value(0)), " "c, Char.MaxValue))) _
  19.        }).OrderBy(Function(x) x.SortStr).Select(Function(x) x.OrgStr).ToList
  20.  
  21.    End Function
  22.  
  23. #End Region





Listar por el  método Burbuja una Lista de DirectoryInfo o de FileInfo especificando la propiedad que se evaluará (por el momento solo funciona con propiedades "TopLevel"):

Código
  1. #Region " BubbleSort List(Of DirectoryInfo) "
  2.  
  3.    ' BubbleSort List(Of DirectoryInfo)
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' Dim Folders As List(Of IO.DirectoryInfo) = IO.Directory.GetDirectories("C:\Windows", "*").Select(Function(p) New IO.DirectoryInfo(p)).ToList()
  8.    '
  9.    ' For Each folder In Bubble_Sort_List_DirectoryInfo(Folders, Function() New IO.DirectoryInfo("").Name)
  10.    '     MsgBox(folder.Name)
  11.    ' Next
  12.  
  13.    Private Shared Function Bubble_Sort_List_DirectoryInfo(list As List(Of IO.DirectoryInfo), _
  14.                                                         exp As Linq.Expressions.Expression(Of Func(Of Object))) _
  15.                                                         As List(Of IO.DirectoryInfo)
  16.  
  17.        Dim member As Linq.Expressions.MemberExpression = _
  18.            If(TypeOf exp.Body Is Linq.Expressions.UnaryExpression, _
  19.               DirectCast(DirectCast(exp.Body, Linq.Expressions.UnaryExpression).Operand, Linq.Expressions.MemberExpression), _
  20.               DirectCast(exp.Body, Linq.Expressions.MemberExpression))
  21.  
  22.        Return list.Select(Function(s) New With { _
  23.        Key .OrgStr = s, _
  24.        Key .SortStr = System.Text.RegularExpressions.Regex.Replace( _
  25.                       s.Name, "(\d+)|(\D+)", _
  26.                       Function(m) m.Value.PadLeft( _
  27.                                   list.Select(Function(folder) DirectCast(DirectCast(member.Member, System.Reflection.PropertyInfo) _
  28.                                                                .GetValue(folder, Nothing), Object).ToString.Length).Max(), _
  29.                                                                If(Char.IsDigit(m.Value(0)), " "c, Char.MaxValue))) _
  30.        }).OrderBy(Function(x) x.SortStr).Select(Function(x) x.OrgStr).ToList
  31.  
  32.    End Function
  33.  
  34. #End Region

Código
  1. #Region " BubbleSort List(Of FileInfo) "
  2.  
  3.    ' BubbleSort List(Of FileInfo)
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' Dim Files As List(Of IO.FileInfo) = IO.Directory.GetFiles("C:\Windows", "*").Select(Function(p) New IO.FileInfo(p)).ToList()
  8.    '
  9.    ' For Each file In Bubble_Sort_List_FileInfo(Files, Function() New IO.FileInfo("").Name)
  10.    '     MsgBox(file.Name)
  11.    ' Next
  12.  
  13.    Private Shared Function Bubble_Sort_List_FileInfo(list As List(Of IO.FileInfo), _
  14.                                                         exp As Linq.Expressions.Expression(Of Func(Of Object))) _
  15.                                                         As List(Of IO.FileInfo)
  16.  
  17.        Dim member As Linq.Expressions.MemberExpression = _
  18.            If(TypeOf exp.Body Is Linq.Expressions.UnaryExpression, _
  19.               DirectCast(DirectCast(exp.Body, Linq.Expressions.UnaryExpression).Operand, Linq.Expressions.MemberExpression), _
  20.               DirectCast(exp.Body, Linq.Expressions.MemberExpression))
  21.  
  22.        Return list.Select(Function(s) New With { _
  23.        Key .OrgStr = s, _
  24.        Key .SortStr = System.Text.RegularExpressions.Regex.Replace( _
  25.                       s.Name, "(\d+)|(\D+)", _
  26.                       Function(m) m.Value.PadLeft( _
  27.                                   list.Select(Function(file) DirectCast(DirectCast(member.Member, System.Reflection.PropertyInfo) _
  28.                                                                .GetValue(file, Nothing), Object).ToString.Length).Max(), _
  29.                                                                If(Char.IsDigit(m.Value(0)), " "c, Char.MaxValue))) _
  30.        }).OrderBy(Function(x) x.SortStr).Select(Function(x) x.OrgStr).ToList
  31.  
  32.    End Function
  33.  
  34. #End Region
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.878



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #303 en: 30 Septiembre 2013, 17:13 pm »

Varias maneras de Activar/Desactivar una serie de contorles:

Código
  1. #Region " Disable Controls "
  2.  
  3.    ' [ Disable Controls ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' Disable_Controls(Button1)
  10.    ' Disable_Controls({Button1, Button2})
  11.    ' Disable_Controls(Of Button)(GroupBox1, False)
  12.    ' Disable_Controls(Of Button)(GroupBox1.Controls, False)
  13.  
  14.    ' Disable Control(Control)
  15.    Private Sub Disable_Control(ByVal [control] As Control)
  16.        [control].Enabled = If([control].Enabled, False, True)
  17.    End Sub
  18.  
  19.    ' Disable Controls({Control})
  20.    Private Sub Disable_Controls(ByVal Controls() As Control)
  21.        For Each [control] As Control In Controls
  22.            [control].Enabled = If([control].Enabled, False, True)
  23.        Next
  24.    End Sub
  25.  
  26.    ' Disable Controls(Of Type)(Control)
  27.    Public Sub Disable_Controls(Of T As Control)(ByVal Container As Control)
  28.        For Each [control] As T In Container.Controls.OfType(Of T).Where(Function(ctrl) ctrl.Enabled)
  29.            [control].Enabled = False
  30.        Next
  31.    End Sub
  32.  
  33.    ' Disable Controls(Of Type)(ControlCollection)
  34.    Public Sub Disable_Controls(Of T As Control)(ByVal Collection As ControlCollection)
  35.        For Each [control] As T In Collection.OfType(Of T).Where(Function(ctrl) ctrl.Enabled)
  36.            [control].Enabled = False
  37.        Next
  38.    End Sub
  39.  
  40. #End Region

Código
  1. #Region " Enable Controls "
  2.  
  3.    ' [ Enable Controls ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' Enable_Control(Button1)
  10.    ' Enable_Controls({Button1, Button2})
  11.    ' Enable_Controls(Of Button)(GroupBox1, False)
  12.    ' Enable_Controls(Of Button)(GroupBox1.Controls, False)
  13.  
  14.    ' Enable Control(Control)
  15.    Private Sub Enable_Control(ByVal [control] As Control)
  16.        [control].Enabled = If(Not [control].Enabled, True, False)
  17.    End Sub
  18.  
  19.    ' Enable Controls({Control})
  20.    Private Sub Enable_Controls(ByVal Controls() As Control)
  21.        For Each [control] As Control In Controls
  22.            [control].Enabled = If(Not [control].Enabled, True, False)
  23.        Next
  24.    End Sub
  25.  
  26.    ' Enable Controls(Of Type)(Control)
  27.    Public Sub Enable_Controls(Of T As Control)(ByVal Container As Control)
  28.        For Each [control] As T In Container.Controls.OfType(Of T).Where(Function(ctrl) Not ctrl.Enabled)
  29.            [control].Enabled = True
  30.        Next
  31.    End Sub
  32.  
  33.    ' Enable Controls(Of Type)(ControlCollection)
  34.    Public Sub Enable_Controls(Of T As Control)(ByVal Collection As ControlCollection)
  35.        For Each [control] As T In Collection.OfType(Of T).Where(Function(ctrl) Not ctrl.Enabled)
  36.            [control].Enabled = True
  37.        Next
  38.    End Sub
  39.  
  40. #End Region
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.878



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #304 en: 3 Octubre 2013, 10:43 am »

Una Class para manejar la aplicación mp3gain.

Sirve para aplicar una ganancia NO destructiva a archivos MP3.

http://mp3gain.sourceforge.net/

EDITO: Código mejorado.
Código
  1. #Region " mp3gain Helper "
  2.  
  3.  
  4.  
  5. ' [ mp3gain Helper ]
  6. '
  7. ' // By Elektro H@cker
  8. '
  9. '
  10. ' Instructions:
  11. '
  12. ' 1. Add the "mp3gain.exe" into the project.
  13. '
  14. '
  15. ' Examples :
  16. '
  17. ' MsgBox(mp3gain.Is_Avaliable) ' Checks if mp3gain executable is avaliable.
  18. '
  19. ' MsgBox(mp3gain.File_Has_MP3Gain_Tag("File.mp3")) ' Checks if file contains mp3gain APE tag
  20. '
  21. ' mp3gain.Set_Gain("File.mp3", 95) ' Set the db Gain of file to 95 db (In a scale of "0/100" db)
  22. ' mp3gain.Set_Gain("File.mp3", 95, True) ' Set the db Gain of file to -95 db and preserve the datetime of file.
  23. '
  24. ' mp3gain.Apply_Gain("File.mp3", +5) ' Apply a change of +5 db in the curent gain of file.
  25. ' mp3gain.Apply_Gain("File.mp3", -5) ' Apply a change of -5 db in the curent gain of file.
  26. '
  27. ' mp3gain.Apply_Channel_Gain("File.mp3", mp3gain.Channels.Left, +10) ' Apply a change of +10 db in the curent Left channel gain of file.
  28. ' mp3gain.Apply_Channel_Gain("File.mp3", mp3gain.Channels.Right, -10) ' Apply a change of -10 db in the curent Right channel gain of file.
  29. '
  30. ' mp3gain.Undo_Gain("File.mp3") ' Undo all MP3Gain db changes made in file.
  31. '
  32. '
  33. ' ------
  34. ' EVENTS
  35. ' ------
  36. ' Public WithEvents mp3gain As New mp3gain
  37. '
  38. ' Sub mp3gain_Progress(Progress As Integer, e As EventArgs) Handles mp3gain.PercentDone
  39. '     ProgressBar1.Maximum = 100
  40. '     ProgressBar1.Value = Progress
  41. ' End Sub
  42. '
  43. ' Sub mp3gain_Exited(Message As String, e As EventArgs) Handles mp3gain.Exited
  44. '     ProgressBar1.Value = 0
  45. '     MessageBox.Show(Message)
  46. ' End Sub
  47.  
  48.  
  49.  
  50. Public Class mp3gain
  51.  
  52. #Region " CommandLine parametter legend "
  53.  
  54.    ' MP3Gain Parametter Legend:
  55.    '
  56.    ' /c   - Ignore clipping warning when applying gain.
  57.    ' /d   - Set global gain.
  58.    ' /e   - Skip Album analysis, even if multiple files listed.
  59.    ' /g   - apply gain
  60.    ' /p   - Preserve original file timestamp.
  61.    ' /r   - apply Track gain automatically (all files set to equal loudness)
  62.    ' /t   - Writes modified data to temp file, then deletes original instead of modifying bytes in original file.
  63.    ' /u   - Undo changes made (based on stored tag info).
  64.    ' /s c - Check stored tag info.
  65.  
  66. #End Region
  67.  
  68. #Region " Variables "
  69.  
  70.    ' <summary>
  71.    ' Gets or sets the mp3gain.exe executable path.
  72.    ' </summary>
  73.    Public Shared mp3gain_Location As String = "c:\mp3gain.exe"
  74.  
  75.    ' Stores the MP3Gain process ErrorOutput.
  76.    Private Shared ErrorOutput As String = String.Empty
  77.  
  78.    ' Stores the MP3Gain process StandardOutput.
  79.    Private Shared StandardOutput As String = String.Empty ' Is not needed
  80.  
  81.    ' Sets a Flag to know if file has MP3Gain APE tag.
  82.    Private Shared HasTag As Boolean = False
  83.  
  84. #End Region
  85.  
  86. #Region " Enumerations "
  87.  
  88.    Enum Channels As Short
  89.        Left = 0  ' /l 0
  90.        Right = 1 ' /l 1
  91.    End Enum
  92.  
  93. #End Region
  94.  
  95. #Region " Events "
  96.  
  97.    ' <summary>
  98.    ' Event raised when process progress changes.
  99.    ' </summary>
  100.    Public Shared Event PercentDone As EventHandler(Of PercentDoneEventArgs)
  101.    Public Class PercentDoneEventArgs : Inherits EventArgs
  102.        Public Property Progress As Integer
  103.    End Class
  104.  
  105.    ' <summary>
  106.    ' Event raised when MP3Gain process has exited.
  107.    ' </summary>
  108.    Public Shared Event Exited As EventHandler(Of ExitedEventArgs)
  109.    Public Class ExitedEventArgs : Inherits EventArgs
  110.        Public Property Message As String
  111.    End Class
  112.  
  113. #End Region
  114.  
  115. #Region " Processes Info "
  116.  
  117.    Private Shared Process_TagCheck As New Process() With { _
  118.    .StartInfo = New ProcessStartInfo With { _
  119.                .CreateNoWindow = True, _
  120.                .UseShellExecute = False, _
  121.                .RedirectStandardError = False, _
  122.                .RedirectStandardOutput = True _
  123.    }}
  124.  
  125.    Private Shared Process_For_Tag As New Process() With { _
  126.    .StartInfo = New ProcessStartInfo With { _
  127.                .CreateNoWindow = True, _
  128.                .UseShellExecute = False, _
  129.                .RedirectStandardError = False, _
  130.                .RedirectStandardOutput = True _
  131.    }}
  132.  
  133.    Private Shared Process_For_NonTag As New Process() With { _
  134.    .StartInfo = New ProcessStartInfo With { _
  135.                .CreateNoWindow = True, _
  136.                .UseShellExecute = False, _
  137.                .RedirectStandardError = True, _
  138.                .RedirectStandardOutput = True _
  139.    }}
  140.  
  141. #End Region
  142.  
  143. #Region " Miscellaneous functions "
  144.  
  145.    ' <summary>
  146.    ' Checks if mp3gain.exe process is avaliable.
  147.    ' </summary>
  148.    Public Shared Function Is_Avaliable() As Boolean
  149.        Return IO.File.Exists(mp3gain_Location)
  150.    End Function
  151.  
  152.    ' Checks if a file exist.
  153.    Private Shared Sub CheckFileExists(ByVal File As String)
  154.  
  155.        If Not IO.File.Exists(File) Then
  156.            ' Throw New Exception("File doesn't exist: " & File)
  157.            MessageBox.Show("File doesn't exist: " & File, "MP3Gain", MessageBoxButtons.OK, MessageBoxIcon.Error)
  158.        End If
  159.  
  160.    End Sub
  161.  
  162. #End Region
  163.  
  164. #Region " Gain Procedures "
  165.  
  166.    ' <summary>
  167.    ' Checks if mp3gain APE tag exists in file.
  168.    ' </summary>
  169.    Public Shared Function File_Has_MP3Gain_Tag(ByVal MP3_File As String) As Boolean
  170.  
  171.        CheckFileExists(MP3_File)
  172.  
  173.        Process_TagCheck.StartInfo.FileName = mp3gain_Location
  174.        Process_TagCheck.StartInfo.Arguments = String.Format("/s c ""{0}""", MP3_File)
  175.        Process_TagCheck.Start()
  176.        Process_TagCheck.WaitForExit()
  177.  
  178.        Return Process_TagCheck.StandardOutput.ReadToEnd.Trim.Split(Environment.NewLine).Count - 1
  179.  
  180.        ' Process_TagCheck.Close()
  181.  
  182.    End Function
  183.  
  184.    ' <summary>
  185.    ' Set global db Gain in file.
  186.    ' </summary>
  187.    Public Shared Sub Set_Gain(ByVal MP3_File As String, _
  188.                               ByVal Gain As Integer, _
  189.                               Optional ByVal Preserve_Datestamp As Boolean = True)
  190.  
  191.        Run_MP3Gain(MP3_File, String.Format("/c /e /r /t {1} /d {2} ""{0}""", _
  192.                                            MP3_File, _
  193.                                            If(Preserve_Datestamp, "/p", ""), _
  194.                                            If(Gain < 0, Gain + 89.0, Gain - 89.0)))
  195.  
  196.    End Sub
  197.  
  198.    ' <summary>
  199.    ' Apply db Gain change in file.
  200.    ' </summary>
  201.    Public Shared Sub Apply_Gain(ByVal MP3_File As String, _
  202.                                 ByVal Gain As Integer, _
  203.                                 Optional ByVal Preserve_Datestamp As Boolean = True)
  204.  
  205.        Run_MP3Gain(MP3_File, String.Format("/c /e /r /t {1} /g {2} ""{0}""", _
  206.                                            MP3_File, _
  207.                                            If(Preserve_Datestamp, "/p", ""), _
  208.                                            Gain))
  209.  
  210.    End Sub
  211.  
  212.    ' <summary>
  213.    ' Apply db Gain change of desired channel in file.
  214.    ' Only works for Stereo MP3 files.
  215.    ' </summary>
  216.    Public Shared Sub Apply_Channel_Gain(ByVal MP3_File As String, _
  217.                                         ByVal Channel As Channels, _
  218.                                         ByVal Gain As Integer, _
  219.                                         Optional ByVal Preserve_Datestamp As Boolean = True)
  220.  
  221.        Run_MP3Gain(MP3_File, String.Format("/c /e /r /l {2} {3} ""{0}""", _
  222.                                            MP3_File, _
  223.                                            If(Preserve_Datestamp, "/p", ""), _
  224.                                            If(Channel = Channels.Left, 0, 1), _
  225.                                            Gain))
  226.  
  227.    End Sub
  228.  
  229.    ' <summary>
  230.    ' Undo all MP3Gain db changes made in file (based on stored tag info).
  231.    ' </summary>
  232.    Public Shared Sub Undo_Gain(ByVal MP3_File As String, _
  233.                                Optional ByVal Preserve_Datestamp As Boolean = True)
  234.  
  235.        Run_MP3Gain(MP3_File, String.Format("/c /t {1} /u ""{0}""", _
  236.                                            MP3_File, _
  237.                                            If(Preserve_Datestamp, "/p", "")))
  238.  
  239.    End Sub
  240.  
  241. #End Region
  242.  
  243. #Region " Run MP3Gain Procedures "
  244.  
  245.    Private Shared Sub Run_MP3Gain(ByVal MP3_File As String, ByVal Parametters As String)
  246.  
  247.        CheckFileExists(MP3_File)
  248.  
  249.        HasTag = File_Has_MP3Gain_Tag(MP3_File)
  250.  
  251.        Process_For_Tag.StartInfo.FileName = mp3gain_Location
  252.        Process_For_Tag.StartInfo.Arguments = Parametters
  253.  
  254.        Process_For_NonTag.StartInfo.FileName = mp3gain_Location
  255.        Process_For_NonTag.StartInfo.Arguments = Parametters
  256.  
  257.        If HasTag Then
  258.            Run_MP3Gain_For_Tag()
  259.        Else
  260.            Run_MP3Gain_For_NonTag()
  261.        End If
  262.  
  263.    End Sub
  264.  
  265.    Private Shared Sub Run_MP3Gain_For_Tag()
  266.  
  267.        Process_For_Tag.Start()
  268.        Process_For_Tag.WaitForExit()
  269.  
  270.        RaiseEvent Exited(Process_For_Tag.StandardOutput.ReadToEnd.Trim.Split(Environment.NewLine).LastOrDefault, Nothing)
  271.  
  272.        StandardOutput = Nothing
  273.        ' Process_For_Tag.Close()
  274.  
  275.    End Sub
  276.  
  277.    Private Shared Sub Run_MP3Gain_For_NonTag()
  278.  
  279.        Process_For_NonTag.Start()
  280.  
  281.        While Not Process_For_NonTag.HasExited
  282.  
  283.            Try
  284.  
  285.                ErrorOutput = Process_For_NonTag.StandardError.ReadLine.Trim.Split("%").First
  286.                If CInt(ErrorOutput) < 101 Then
  287.                    RaiseEvent PercentDone(ErrorOutput, Nothing)
  288.                End If
  289.  
  290.            Catch : End Try
  291.  
  292.        End While
  293.  
  294.        StandardOutput = Process_For_NonTag.StandardOutput.ReadToEnd.Trim.Split(Environment.NewLine).Last
  295.  
  296.        RaiseEvent Exited(StandardOutput, Nothing)
  297.  
  298.        ErrorOutput = Nothing
  299.        StandardOutput = Nothing
  300.        ' Process_For_Tag.Close()
  301.  
  302.    End Sub
  303.  
  304. #End Region
  305.  
  306. End Class
  307.  
  308. #End Region
« Última modificación: 11 Octubre 2013, 18:26 pm por EleKtro H@cker » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.878



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #305 en: 5 Octubre 2013, 22:23 pm »

Un ayudante para manejar la librería TabLig Sharp: https://github.com/mono/taglib-sharp

La librería sirve para editar los metadatos de archivos de música, entre otros formatos como imágenes png, etc...

Mi Class está pensada para usarse con archivos MP3.

Código
  1. #Region " TagLib Sharp Helper "
  2.  
  3.  
  4. ' [ TagLib Sharp Helper ]
  5. '
  6. ' // By Elektro H@cker
  7. '
  8. '
  9. ' Instructions:
  10. ' 1. Add a reference to "taglib-sharp.dll" into the project.
  11. '
  12. '
  13. ' Examples:
  14. '
  15. ' MsgBox(TagLibSharp.FileIsCorrupt("C:\File.mp3")) ' Result: True or False
  16. ' MsgBox(TagLibSharp.FileIsWriteable("C:\File.mp3")) ' Result: True or False
  17. ' MsgBox(TagLibSharp.Get_Title("C:\File.mp3"))
  18. ' MsgBox(TagLibSharp.Get_Artist("C:\File.mp3"))
  19. ' MsgBox(TagLibSharp.Get_Album("C:\File.mp3"))
  20. ' MsgBox(TagLibSharp.Get_Genre("C:\File.mp3"))
  21. ' MsgBox(TagLibSharp.Get_Year("C:\File.mp3"))
  22. ' MsgBox(TagLibSharp.Get_Basic_TagInfo("C:\File.mp3"))
  23. ' TagLibSharp.RemoveTag("C:\File.mp3", TagLib.TagTypes.Id3v1 Or TagLib.TagTypes.Id3v2) ' Removes ID3v1 + ID3v2 Tags
  24. ' TagLibSharp.Set_Tag_Fields("C:\Test.mp3", Sub(x) x.Tag.Title = "Title Test"})
  25. ' TagLibSharp.Set_Tag_Fields("C:\Test.mp3", {Sub(x) x.Tag.Title = "Title Test", Sub(x) x.Tag.Performers = {"Artist Test"}})
  26.  
  27.  
  28. Public Class TagLibSharp
  29.  
  30.    ''' <summary>
  31.    ''' Stores the Taglib object.
  32.    ''' </summary>
  33.    Private Shared TagFile As TagLib.File = Nothing
  34.  
  35.    ''' <summary>
  36.    ''' Checks if file is possibly corrupted.
  37.    ''' </summary>
  38.    Public Shared Function FileIsCorrupt(ByVal File As String) As Boolean
  39.  
  40.        Try
  41.            Return TagLib.File.Create(File).PossiblyCorrupt
  42.  
  43.        Catch ex As Exception
  44.            Throw New Exception(ex.Message)
  45.            Return True
  46.  
  47.        Finally
  48.            If TagFile IsNot Nothing Then TagFile.Dispose()
  49.  
  50.        End Try
  51.  
  52.    End Function
  53.  
  54. ''' <summary>
  55. ''' Checks if file can be written.
  56. ''' </summary>
  57. Public Shared Function FileIsWriteable(ByVal File As String) As Boolean
  58.  
  59.    Try
  60.        Return TagLib.File.Create(File).Writeable
  61.  
  62.    Catch ex As Exception
  63.        Throw New Exception(ex.Message)
  64.        Return True
  65.  
  66.    Finally
  67.        If TagFile IsNot Nothing Then TagFile.Dispose()
  68.  
  69.    End Try
  70.  
  71. End Function
  72.  
  73. ''' <summary>
  74. ''' Get TagTypes of file.
  75. ''' </summary>
  76. Public Shared Function Get_Tags(ByVal File As String) As String
  77.  
  78.    Try
  79.        Return TagLib.File.Create(File).TagTypes.ToString
  80.  
  81.    Catch ex As Exception
  82.        Throw New Exception(ex.Message)
  83.        Return String.Empty
  84.  
  85.    Finally
  86.        If TagFile IsNot Nothing Then TagFile.Dispose()
  87.  
  88.    End Try
  89.  
  90. End Function
  91.  
  92. ''' <summary>
  93. ''' Remove a entire Tag from file.
  94. ''' </summary>
  95. Public Shared Sub RemoveTag(ByVal File As String, ByVal TagTypes As TagLib.TagTypes)
  96.  
  97.    Try
  98.        TagFile = TagLib.File.Create(File)
  99.    Catch ex As Exception
  100.        Throw New Exception(ex.Message)
  101.        Exit Sub
  102.    End Try
  103.  
  104.    Try
  105.  
  106.        If Not TagFile.PossiblyCorrupt _
  107.        AndAlso TagFile.Writeable Then
  108.  
  109.            TagFile.RemoveTags(TagTypes)
  110.            TagFile.Save()
  111.  
  112.        End If
  113.  
  114.    Catch ex As Exception
  115.        Throw New Exception(ex.Message)
  116.  
  117.    Finally
  118.        If TagFile IsNot Nothing Then TagFile.Dispose()
  119.  
  120.    End Try
  121.  
  122. End Sub
  123.  
  124. ''' <summary>
  125. ''' Gets the Title tag field of file.
  126. ''' </summary>
  127. Public Shared Function Get_Title(ByVal File As String) As String
  128.  
  129.    Try
  130.        Return TagLib.File.Create(File).Tag.Title
  131.  
  132.    Catch ex As Exception
  133.        Throw New Exception(ex.Message)
  134.        Return String.Empty
  135.  
  136.    Finally
  137.        If TagFile IsNot Nothing Then TagFile.Dispose()
  138.  
  139.    End Try
  140.  
  141. End Function
  142.  
  143. ''' <summary>
  144. ''' Gets the Artist tag field of file.
  145. ''' </summary>
  146. Public Shared Function Get_Artist(ByVal File As String) As String
  147.  
  148.    Try
  149.        Return TagLib.File.Create(File).Tag.Performers(0)
  150.  
  151.    Catch ex As Exception
  152.        Throw New Exception(ex.Message)
  153.        Return String.Empty
  154.  
  155.    Finally
  156.        If TagFile IsNot Nothing Then TagFile.Dispose()
  157.  
  158.    End Try
  159.  
  160. End Function
  161.  
  162. ''' <summary>
  163. ''' Gets the Album tag field of file.
  164. ''' </summary>
  165. Public Shared Function Get_Album(ByVal File As String) As String
  166.  
  167.    Try
  168.        Return TagLib.File.Create(File).Tag.Album
  169.  
  170.    Catch ex As Exception
  171.        Throw New Exception(ex.Message)
  172.        Return String.Empty
  173.  
  174.    Finally
  175.        If TagFile IsNot Nothing Then TagFile.Dispose()
  176.  
  177.    End Try
  178.  
  179. End Function
  180.  
  181. ''' <summary>
  182. ''' Gets the Genre tag field of file.
  183. ''' </summary>
  184. Public Shared Function Get_Genre(ByVal File As String) As String
  185.  
  186.    Try
  187.        Return TagLib.File.Create(File).Tag.Genres(0)
  188.  
  189.    Catch ex As Exception
  190.        Throw New Exception(ex.Message)
  191.        Return String.Empty
  192.  
  193.    Finally
  194.        If TagFile IsNot Nothing Then TagFile.Dispose()
  195.  
  196.    End Try
  197.  
  198. End Function
  199.  
  200. ''' <summary>
  201. ''' Gets the Year tag field of file.
  202. ''' </summary>
  203. Public Shared Function Get_Year(ByVal File As String) As String
  204.  
  205.    Try
  206.        Return TagLib.File.Create(File).Tag.Year
  207.  
  208.    Catch ex As Exception
  209.        Throw New Exception(ex.Message)
  210.        Return String.Empty
  211.  
  212.    Finally
  213.        If TagFile IsNot Nothing Then TagFile.Dispose()
  214.  
  215.    End Try
  216.  
  217. End Function
  218.  
  219. ''' <summary>
  220. ''' Gets the basic tag fields of file.
  221. ''' </summary>
  222. Public Shared Function Get_Basic_TagInfo(ByVal File As String) As String
  223.  
  224.    Try
  225.        TagFile = TagLib.File.Create(File)
  226.  
  227.        Return String.Format("Title: {1}{0}Artist: {2}{0}Album: {3}{0}Genre: {4}{0}Year: {5}", Environment.NewLine, _
  228.                             TagFile.Tag.Title, _
  229.                             TagFile.Tag.Performers(0), _
  230.                             TagFile.Tag.Album, _
  231.                             TagFile.Tag.Genres(0), _
  232.                             TagFile.Tag.Year)
  233.  
  234.    Catch ex As Exception
  235.        Throw New Exception(ex.Message)
  236.        Return String.Empty
  237.  
  238.    Finally
  239.        If TagFile IsNot Nothing Then TagFile.Dispose()
  240.  
  241.    End Try
  242.  
  243. End Function
  244.  
  245. ''' <summary>
  246. ''' Sets a Tag field.
  247. ''' </summary>
  248. Public Shared Sub Set_Tag_Fields(ByVal File As String, _
  249.                                   ByVal FieldSetter As Action(Of TagLib.File))
  250.  
  251.    Try
  252.        TagFile = TagLib.File.Create(File)
  253.    Catch ex As Exception
  254.        Throw New Exception(ex.Message)
  255.        Exit Sub
  256.    End Try
  257.  
  258.    Try
  259.  
  260.        If Not TagFile.PossiblyCorrupt _
  261.        AndAlso TagFile.Writeable Then
  262.  
  263.            FieldSetter(TagFile)
  264.            TagFile.Save()
  265.  
  266.        End If
  267.  
  268.    Catch ex As Exception
  269.        Throw New Exception(ex.Message)
  270.  
  271.    Finally
  272.        If TagFile IsNot Nothing Then TagFile.Dispose()
  273.  
  274.    End Try
  275.  
  276. End Sub
  277.  
  278. ''' <summary>
  279. ''' Sets multiple Tag fields.
  280. ''' </summary>
  281. Public Shared Sub Set_Tag_Fields(ByVal File As String, _
  282.                                   ByVal FieldSetter() As Action(Of TagLib.File))
  283.  
  284.    Try
  285.        TagFile = TagLib.File.Create(File)
  286.    Catch ex As Exception
  287.        Throw New Exception(ex.Message)
  288.        Exit Sub
  289.    End Try
  290.  
  291.    Try
  292.  
  293.        If Not TagFile.PossiblyCorrupt _
  294.        AndAlso TagFile.Writeable Then
  295.  
  296.            For Each Field In FieldSetter
  297.                Field(TagFile)
  298.            Next
  299.  
  300.            TagFile.Save()
  301.  
  302.        End If
  303.  
  304.    Catch ex As Exception
  305.        Throw New Exception(ex.Message)
  306.  
  307.    Finally
  308.        If TagFile IsNot Nothing Then TagFile.Dispose()
  309.  
  310.    End Try
  311.  
  312. End Sub
  313.  
  314. End Class
  315.  
  316. #End Region
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.878



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #306 en: 5 Octubre 2013, 23:53 pm »

Un ayudante de la librería UltraId3Lib: http://home.fuse.net/honnert/UltraID3Lib/UltraID3Lib0968.zip

La diferencia entre esta librería y TagLib Sharp es que UltraID3Lib trabaja sólamente metadatos de tipo ID3v1 e ID3v2 (y las variantes de ID3v2, y los Covers)

Esta librería está optimizada para trabajar archivos MP3, de hecho sólamente trabaja archivos mp3, además hice un pequeño test de velocidad y estos fueron los resultados:

Citar
                                                                                              TagLib Sharp        UltraId3Lib
Tiempo transcurrido para eliminar los tags ID3v1 + ID3v2 de 1.000 archivos mp3 (5,2 GB)       05:40 minutos       03:10 minutos

Ahora... si tuviera que elegir entre la lógica interna que usa cada librería, lo cierto es que no sabría por cual decidirme, por eso hice un ayudante para las dos librerías xD.

EDITO: He extendido la Class para manejar las carátulas de los mp3.

EDITO: He vuelto ha extender la Class para exprimir un poco más la librería.

Código
  1. #Region " UltraID3Lib "
  2.  
  3.  
  4.  
  5. ' [ UltraID3Lib Helper ]
  6. '
  7. ' // By Elektro H@cker
  8. '
  9. '
  10. ' Instructions:
  11. ' 1. Add a reference to "UltraID3Lib.dll" into the project.
  12. '
  13. '
  14. ' Examples:
  15. '
  16. ' MsgBox(UltraID3Lib.FileIsCorrupt("C:\File.mp3")) ' Result: True or False
  17. ' MsgBox(UltraID3Lib.ID3v1_Exist("C:\File.mp3"))   ' Result: True or False
  18. ' MsgBox(UltraID3Lib.ID3v2_Exist("C:\File.mp3"))   ' Result: True or False
  19. ' MsgBox(UltraID3Lib.IsVBR("C:\File.mp3"))         ' Result: True or False
  20. ' MsgBox(UltraID3Lib.Get_Metadata_Errors("C:\File.mp3"))
  21. ' MsgBox(UltraID3Lib.Get_Metadata_Warnings("C:\File.mp3"))
  22. '
  23. ' MsgBox(UltraID3Lib.Get_ID3_Tags("C:\File.mp3"))
  24. ' MsgBox(UltraID3Lib.Get_Title("C:\File.mp3"))
  25. ' MsgBox(UltraID3Lib.Get_Artist("C:\File.mp3"))
  26. ' MsgBox(UltraID3Lib.Get_Album("C:\File.mp3"))
  27. ' MsgBox(UltraID3Lib.Get_Genre("C:\File.mp3"))
  28. ' MsgBox(UltraID3Lib.Get_Year("C:\File.mp3"))
  29. ' MsgBox(UltraID3Lib.Get_Basic_Tag_Fields("C:\File.mp3"))
  30. '
  31. ' UltraID3Lib.Remove_ID3v1_Tag("C:\File.mp3") ' Removes ID3v1 Tag
  32. ' UltraID3Lib.Remove_ID3v2_Tag("C:\File.mp3") ' Removes ID3v2 Tag
  33. ' UltraID3Lib.Remove_ID3v1_ID3v2_Tags("C:\File.mp3") ' Removes ID3v1 + ID3v2 Tags
  34. '
  35. ' UltraID3Lib.Set_Tag_Field("C:\File.mp3", Sub(x) x.ID3v2Tag.Title = "Title Test")
  36. ' UltraID3Lib.Set_Tag_Fields("C:\File.mp3", {Sub(x) x.ID3v2Tag.Title = "Title Test", Sub(x) x.ID3v2Tag.Artist = "Artist Test"})
  37. '
  38. ' UltraID3Lib.Set_Main_Cover("C:\File.mp3", "C:\Image.jpg")
  39. ' UltraID3Lib.Add_Cover("C:\File.mp3", "C:\Image.jpg")
  40. ' UltraID3Lib.Delete_Covers("C:\File.mp3")
  41. ' PictureBox1.BackgroundImage = UltraID3Lib.Get_Main_Cover("C:\File.mp3")
  42. '
  43. ' For Each Genre As String In UltraID3Lib.Get_Generic_ID3_Genres() : MsgBox(Genre) : Next
  44. '
  45. ' MsgBox(UltraID3Lib.Get_Bitrate("C:\File.mp3")) ' Result: 320
  46. ' MsgBox(UltraID3Lib.Get_Duration("C:\File.mp3")) ' Result: 00:00:00:000
  47. ' MsgBox(UltraID3Lib.Get_Frequency("C:\File.mp3")) ' Result: 44100
  48. ' MsgBox(UltraID3Lib.Get_Channels("C:\File.mp3")) ' Result: JointStereo
  49. ' MsgBox(UltraID3Lib.Get_Layer("C:\File.mp3")) ' Result: MPEGLayer3
  50. ' MsgBox(UltraID3Lib.Get_Filesize("C:\File.mp3")) ' Result: 6533677
  51.  
  52.  
  53.  
  54. Imports HundredMilesSoftware.UltraID3Lib
  55.  
  56. Public Class UltraID3Lib
  57.  
  58.    ''' <summary>
  59.    ''' Stores the UltraID3Lib object.
  60.    ''' </summary>
  61.    Private Shared [UltraID3] As New UltraID3
  62.  
  63.    ' ''' <summary>
  64.    ' ''' Stores the Picture things.
  65.    ' ''' </summary>
  66.    ' Private Shared CurrentPictureFrame As ID3v2PictureFrame ' Not used in this Class
  67.    ' Private Shared PictureTypes As ArrayList ' Not used in this Class
  68.    ' Private Shared PictureFrames As ID3FrameCollection ' Not used in this Class
  69.    ' Private Shared PictureIndex As Integer ' Not used in this Class
  70.  
  71.    ''' <summary>
  72.    ''' Checks if file is possibly corrupt.
  73.    ''' </summary>
  74.    Public Shared Function FileIsCorrupt(ByVal File As String) As Boolean
  75.  
  76.        Try
  77.            [UltraID3].Read(File)
  78.            Return Convert.ToBoolean( _
  79.                       [UltraID3].GetExceptions(ID3ExceptionLevels.Error).Length _
  80.                     + [UltraID3].GetExceptions(ID3ExceptionLevels.Warning).Length)
  81.  
  82.        Catch ex As Exception
  83.            Throw New Exception(ex.Message)
  84.        End Try
  85.  
  86.    End Function
  87.  
  88.    ''' <summary>
  89.    ''' Checks for errors inside file metadata.
  90.    ''' </summary>
  91.    Public Shared Function Get_Metadata_Errors(ByVal File As String) As String
  92.  
  93.        Try
  94.            [UltraID3].Read(File)
  95.            Return String.Join(Environment.NewLine, _
  96.                               [UltraID3].GetExceptions(ID3ExceptionLevels.Error) _
  97.                               .Select(Function(ex) ex.Message))
  98.  
  99.        Catch ex As Exception
  100.            Throw New Exception(ex.Message)
  101.        End Try
  102.  
  103.    End Function
  104.  
  105.    ''' <summary>
  106.    ''' Checks for warnings inside file metadata.
  107.    ''' </summary>
  108.    Public Shared Function Get_Metadata_Warnings(ByVal File As String) As String
  109.  
  110.        Try
  111.            [UltraID3].Read(File)
  112.            Return String.Join(Environment.NewLine, _
  113.                               [UltraID3].GetExceptions(ID3ExceptionLevels.Warning) _
  114.                               .Select(Function(ex) ex.Message))
  115.  
  116.        Catch ex As Exception
  117.            Throw New Exception(ex.Message)
  118.        End Try
  119.  
  120.    End Function
  121.  
  122.    ''' <summary>
  123.    ''' Checks if ID3v1 exists in file.
  124.    ''' </summary>
  125.    Public Shared Function ID3v1_Exist(ByVal File As String) As Boolean
  126.  
  127.        Try
  128.            [UltraID3].Read(File)
  129.            Return [UltraID3].ID3v1Tag.ExistsInFile
  130.        Catch ex As Exception
  131.            Throw New Exception(ex.Message)
  132.        End Try
  133.  
  134.    End Function
  135.  
  136.    ''' <summary>
  137.    ''' Checks if ID3v2 exists in file.
  138.    ''' </summary>
  139.    Public Shared Function ID3v2_Exist(ByVal File As String) As Boolean
  140.  
  141.        Try
  142.            [UltraID3].Read(File)
  143.            Return [UltraID3].ID3v2Tag.ExistsInFile
  144.        Catch ex As Exception
  145.            Throw New Exception(ex.Message)
  146.        End Try
  147.  
  148.    End Function
  149.  
  150.    ''' <summary>
  151.    ''' Gets ID3 TagTypes of file.
  152.    ''' </summary>
  153.    Public Shared Function Get_ID3_Tags(ByVal File As String) As String
  154.  
  155.        Try
  156.            [UltraID3].Read(File)
  157.  
  158.            Return String.Format("{0}{1}", _
  159.                                 If([UltraID3].ID3v1Tag.ExistsInFile, "ID3v1, ", ""), _
  160.                                 If([UltraID3].ID3v2Tag.ExistsInFile, " ID3v2", "")).Trim
  161.  
  162.        Catch ex As Exception
  163.            Throw New Exception(ex.Message)
  164.  
  165.        End Try
  166.  
  167.    End Function
  168.  
  169.    ''' <summary>
  170.    ''' Removes entire ID3v1 Tag from file.
  171.    ''' </summary>
  172.    Public Shared Sub Remove_ID3v1_Tag(ByVal File As String)
  173.  
  174.        Try
  175.            [UltraID3].Read(File)
  176.            [UltraID3].ID3v1Tag.Clear()
  177.            [UltraID3].Write()
  178.  
  179.        Catch ex As Exception
  180.            Throw New Exception(ex.Message)
  181.  
  182.        End Try
  183.  
  184.    End Sub
  185.  
  186.    ''' <summary>
  187.    ''' Removes entire ID3v2 Tag from file.
  188.    ''' </summary>
  189.    Public Shared Sub Remove_ID3v2_Tag(ByVal File As String)
  190.  
  191.        Try
  192.            [UltraID3].Read(File)
  193.            [UltraID3].ID3v2Tag.Clear()
  194.            [UltraID3].Write()
  195.  
  196.        Catch ex As Exception
  197.            Throw New Exception(ex.Message)
  198.  
  199.        End Try
  200.  
  201.    End Sub
  202.  
  203.    ''' <summary>
  204.    ''' Removes entire ID3v1 + ID3v2 Tags from file.
  205.    ''' </summary>
  206.    Public Shared Sub Remove_ID3v1_ID3v2_Tags(ByVal File As String)
  207.  
  208.        Try
  209.            [UltraID3].Read(File)
  210.            [UltraID3].ID3v1Tag.Clear()
  211.            [UltraID3].ID3v2Tag.Clear()
  212.            [UltraID3].Write()
  213.  
  214.        Catch ex As Exception
  215.            Throw New Exception(ex.Message)
  216.  
  217.        End Try
  218.  
  219.    End Sub
  220.  
  221.    ''' <summary>
  222.    ''' Gets the Title tag field of file.
  223.    ''' </summary>
  224.    Public Shared Function Get_Title(ByVal File As String) As String
  225.  
  226.        Try
  227.            [UltraID3].Read(File)
  228.            Return [UltraID3].Title
  229.  
  230.        Catch ex As Exception
  231.            Throw New Exception(ex.Message)
  232.  
  233.        End Try
  234.  
  235.    End Function
  236.  
  237.    ''' <summary>
  238.    ''' Gets the Artist tag field of file.
  239.    ''' </summary>
  240.    Public Shared Function Get_Artist(ByVal File As String) As String
  241.  
  242.        Try
  243.            [UltraID3].Read(File)
  244.            Return [UltraID3].Artist
  245.  
  246.        Catch ex As Exception
  247.            Throw New Exception(ex.Message)
  248.  
  249.        End Try
  250.  
  251.    End Function
  252.  
  253.    ''' <summary>
  254.    ''' Gets the Album tag field of file.
  255.    ''' </summary>
  256.    Public Shared Function Get_Album(ByVal File As String) As String
  257.  
  258.        Try
  259.            [UltraID3].Read(File)
  260.            Return [UltraID3].Album
  261.  
  262.        Catch ex As Exception
  263.            Throw New Exception(ex.Message)
  264.  
  265.        End Try
  266.  
  267.    End Function
  268.  
  269.    ''' <summary>
  270.    ''' Gets the Genre tag field of file.
  271.    ''' </summary>
  272.    Public Shared Function Get_Genre(ByVal File As String) As String
  273.  
  274.        Try
  275.            [UltraID3].Read(File)
  276.            Return [UltraID3].Genre
  277.  
  278.        Catch ex As Exception
  279.            Throw New Exception(ex.Message)
  280.  
  281.        End Try
  282.  
  283.    End Function
  284.  
  285.    ''' <summary>
  286.    ''' Gets the Year tag field of file.
  287.    ''' </summary>
  288.    Public Shared Function Get_Year(ByVal File As String) As String
  289.  
  290.        Try
  291.            [UltraID3].Read(File)
  292.            Return [UltraID3].Year
  293.  
  294.        Catch ex As Exception
  295.            Throw New Exception(ex.Message)
  296.  
  297.        End Try
  298.  
  299.    End Function
  300.  
  301.    ''' <summary>
  302.    ''' Gets the basic tag fields of file.
  303.    ''' </summary>
  304.    Public Shared Function Get_Basic_Tag_Fields(ByVal File As String) As String
  305.  
  306.        Try
  307.            [UltraID3].Read(File)
  308.  
  309.            Return String.Format("Title: {1}{0}Artist: {2}{0}Album: {3}{0}Genre: {4}{0}Year: {5}", Environment.NewLine, _
  310.                                 [UltraID3].Title, _
  311.                                 [UltraID3].Artist, _
  312.                                 [UltraID3].Album, _
  313.                                 [UltraID3].Genre, _
  314.                                 [UltraID3].Year)
  315.  
  316.        Catch ex As Exception
  317.            Throw New Exception(ex.Message)
  318.            Return String.Empty
  319.  
  320.        End Try
  321.  
  322.    End Function
  323.  
  324.    ''' <summary>
  325.    ''' Sets a Tag field.
  326.    ''' </summary>
  327.    Public Shared Sub Set_Tag_Field(ByVal File As String, _
  328.                                    ByVal FieldSetter As Action(Of UltraID3))
  329.  
  330.        Try
  331.            [UltraID3].Read(File)
  332.            FieldSetter([UltraID3])
  333.            [UltraID3].Write()
  334.  
  335.        Catch ex As Exception
  336.            Throw New Exception(ex.Message)
  337.  
  338.        End Try
  339.  
  340.    End Sub
  341.  
  342.    ''' <summary>
  343.    ''' Sets multiple Tag fields.
  344.    ''' </summary>
  345.    Public Shared Sub Set_Tag_Fields(ByVal File As String, _
  346.                                     ByVal FieldSetter() As Action(Of UltraID3))
  347.  
  348.  
  349.        Try
  350.            [UltraID3].Read(File)
  351.  
  352.            For Each Field As Action(Of UltraID3) In FieldSetter
  353.                Field([UltraID3])
  354.            Next
  355.  
  356.            [UltraID3].Write()
  357.  
  358.        Catch ex As Exception
  359.            Throw New Exception(ex.Message)
  360.  
  361.        End Try
  362.  
  363.    End Sub
  364.  
  365.    ''' <summary>
  366.    ''' Sets Main Picture Cover.
  367.    ''' </summary>
  368.    Public Shared Sub Set_Main_Cover(ByVal File As String, _
  369.                            ByVal Picture As String)
  370.  
  371.        Try
  372.            [UltraID3].Read(File)
  373.            [UltraID3].ID3v2Tag.Frames.Add( _
  374.                       New ID3v23PictureFrame(New Bitmap(Picture), PictureTypes.CoverFront, String.Empty, TextEncodingTypes.Unicode))
  375.  
  376.            [UltraID3].Write()
  377.  
  378.        Catch ex As Exception
  379.            Throw New Exception(ex.Message)
  380.  
  381.        End Try
  382.  
  383.    End Sub
  384.  
  385.    ''' <summary>
  386.    ''' Adds a Picture Cover.
  387.    ''' </summary>
  388.    Public Shared Sub Add_Cover(ByVal File As String, _
  389.                                ByVal Picture As String)
  390.  
  391.        Try
  392.            [UltraID3].Read(File)
  393.            [UltraID3].ID3v2Tag.Frames.Add( _
  394.                       New ID3v23PictureFrame(New Bitmap(Picture), PictureTypes.Other, String.Empty, TextEncodingTypes.Unicode))
  395.            [UltraID3].Write()
  396.  
  397.        Catch ex As Exception
  398.            Throw New Exception(ex.Message)
  399.  
  400.        End Try
  401.  
  402.    End Sub
  403.  
  404.    ''' <summary>
  405.    ''' Deletes all Picture Covers.
  406.    ''' </summary>
  407.    Public Shared Sub Delete_Covers(ByVal File As String)
  408.  
  409.        Try
  410.            [UltraID3].Read(File)
  411.  
  412.            [UltraID3].ID3v2Tag.Frames.Remove( _
  413.                       [UltraID3].ID3v2Tag.Frames.GetFrames(MultipleInstanceID3v2FrameTypes.ID3v22Picture))
  414.  
  415.            [UltraID3].ID3v2Tag.Frames.Remove( _
  416.                       [UltraID3].ID3v2Tag.Frames.GetFrames(MultipleInstanceID3v2FrameTypes.ID3v23Picture))
  417.  
  418.            [UltraID3].Write()
  419.  
  420.        Catch ex As Exception
  421.            Throw New Exception(ex.Message)
  422.  
  423.        End Try
  424.  
  425.    End Sub
  426.  
  427.    ''' <summary>
  428.    ''' Gets Main Picture Cover.
  429.    ''' </summary>
  430.    Public Shared Function Get_Main_Cover(ByVal File As String) As Bitmap
  431.  
  432.        Try
  433.            [UltraID3].Read(File)
  434.  
  435.            If [UltraID3].ID3v2Tag.Frames.GetFrame(MultipleInstanceID3v2FrameTypes.ID3v23Picture, False) IsNot Nothing Then
  436.                Return DirectCast( _
  437.                       [UltraID3].ID3v2Tag.Frames.GetFrame(MultipleInstanceID3v2FrameTypes.ID3v23Picture, False),  _
  438.                       ID3v2PictureFrame).Picture
  439.            End If
  440.  
  441.            If [UltraID3].ID3v2Tag.Frames.GetFrame(MultipleInstanceID3v2FrameTypes.ID3v22Picture, False) IsNot Nothing Then
  442.                Return DirectCast( _
  443.                       [UltraID3].ID3v2Tag.Frames.GetFrame(MultipleInstanceID3v2FrameTypes.ID3v22Picture, False),  _
  444.                       ID3v2PictureFrame).Picture
  445.            End If
  446.  
  447.            Return Nothing
  448.  
  449.        Catch ex As Exception
  450.            Throw New Exception(ex.Message)
  451.  
  452.        End Try
  453.  
  454.    End Function
  455.  
  456.    ''' <summary>
  457.    ''' Gets the generic ID3 genre names.
  458.    ''' </summary>
  459.    Public Shared Function Get_Generic_ID3_Genres() As String()
  460.        Return UltraID3.GenreInfos.Cast(Of GenreInfo).Select(Function(Genre) Genre.Name).ToArray
  461.    End Function
  462.  
  463.    ''' <summary>
  464.    ''' Gets the Audio Bitrate.
  465.    ''' </summary>
  466.    Public Shared Function Get_Bitrate(ByVal File As String) As Short
  467.  
  468.        Try
  469.            [UltraID3].Read(File)
  470.            Return [UltraID3].FirstMPEGFrameInfo.Bitrate
  471.  
  472.        Catch ex As Exception
  473.            Throw New Exception(ex.Message)
  474.  
  475.        End Try
  476.  
  477.    End Function
  478.  
  479.    ''' <summary>
  480.    ''' Gets the Audio Duration.
  481.    ''' </summary>
  482.    Public Shared Function Get_Duration(ByVal File As String) As String
  483.  
  484.        Try
  485.            [UltraID3].Read(File)
  486.            Return String.Format("{0:00}:{1:00}:{2:00}:{3:000}", _
  487.                                  [UltraID3].FirstMPEGFrameInfo.Duration.Hours, _
  488.                                  [UltraID3].FirstMPEGFrameInfo.Duration.Minutes, _
  489.                                  [UltraID3].FirstMPEGFrameInfo.Duration.Seconds, _
  490.                                  [UltraID3].FirstMPEGFrameInfo.Duration.Milliseconds)
  491.  
  492.        Catch ex As Exception
  493.            Throw New Exception(ex.Message)
  494.  
  495.        End Try
  496.  
  497.    End Function
  498.  
  499.    ''' <summary>
  500.    ''' Gets the Audio Frequency.
  501.    ''' </summary>
  502.    Public Shared Function Get_Frequency(ByVal File As String) As Integer
  503.  
  504.        Try
  505.            [UltraID3].Read(File)
  506.            Return [UltraID3].FirstMPEGFrameInfo.Frequency
  507.  
  508.        Catch ex As Exception
  509.            Throw New Exception(ex.Message)
  510.  
  511.        End Try
  512.  
  513.    End Function
  514.  
  515.    ''' <summary>
  516.    ''' Gets the Audio MPEG Layer.
  517.    ''' </summary>
  518.    Public Shared Function Get_Layer(ByVal File As String) As String
  519.  
  520.        Try
  521.            [UltraID3].Read(File)
  522.            Return [UltraID3].FirstMPEGFrameInfo.Layer.ToString
  523.  
  524.        Catch ex As Exception
  525.            Throw New Exception(ex.Message)
  526.  
  527.        End Try
  528.  
  529.    End Function
  530.  
  531.    ''' <summary>
  532.    ''' Gets the Audio Channel mode.
  533.    ''' </summary>
  534.    Public Shared Function Get_Channels(ByVal File As String) As String
  535.  
  536.        Try
  537.            [UltraID3].Read(File)
  538.            Return [UltraID3].FirstMPEGFrameInfo.Mode.ToString
  539.  
  540.        Catch ex As Exception
  541.            Throw New Exception(ex.Message)
  542.  
  543.        End Try
  544.  
  545.    End Function
  546.  
  547.    ''' <summary>
  548.    ''' Gets the File Size.
  549.    ''' </summary>
  550.    Public Shared Function Get_Filesize(ByVal File As String) As Long
  551.  
  552.        Try
  553.            [UltraID3].Read(File)
  554.            Return [UltraID3].Size
  555.  
  556.        Catch ex As Exception
  557.            Throw New Exception(ex.Message)
  558.  
  559.        End Try
  560.  
  561.    End Function
  562.  
  563.    ''' <summary>
  564.    ''' Checks if VBR header is present in file.
  565.    ''' </summary>
  566.    Public Shared Function IsVBR(ByVal File As String) As Boolean
  567.  
  568.        Try
  569.            [UltraID3].Read(File)
  570.            Return [UltraID3].FirstMPEGFrameInfo.VBRInfo.WasFound
  571.  
  572.        Catch ex As Exception
  573.            Throw New Exception(ex.Message)
  574.  
  575.        End Try
  576.  
  577.    End Function
  578.  
  579. End Class
  580.  
  581. #End Region
« Última modificación: 6 Octubre 2013, 03:16 am por EleKtro H@cker » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.878



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #307 en: 10 Octubre 2013, 02:34 am »

Un custom MessageBox que se puede alinear en el centro del formulario y además se puede personalizar la fuente de texto usada.

Modo de empleo:
Código
  1.        Using New CustomMessageBox(Me, New Font(New FontFamily("Lucida Console"), Font.SizeInPoints, FontStyle.Bold))
  2.            MessageBox.Show("Test Text", "Test Title", MessageBoxButtons.OK)
  3.        End Using


Código
  1. Imports System.Drawing
  2. Imports System.Runtime.InteropServices
  3. Imports System.Text
  4. Imports System.Windows.Forms
  5.  
  6. Class CustomMessageBox : Implements IDisposable
  7.  
  8.    Private mTries As Integer = 0
  9.    Private mOwner As Form
  10.    Private mFont As Font
  11.  
  12.    ' P/Invoke declarations
  13.    Private Const WM_SETFONT As Integer = &H30
  14.    Private Const WM_GETFONT As Integer = &H31
  15.  
  16.    Private Delegate Function EnumThreadWndProc(hWnd As IntPtr, lp As IntPtr) As Boolean
  17.  
  18.    <DllImport("user32.dll")> _
  19.    Private Shared Function EnumThreadWindows(tid As Integer, callback As EnumThreadWndProc, lp As IntPtr) As Boolean
  20.    End Function
  21.  
  22.    <DllImport("kernel32.dll")> _
  23.    Private Shared Function GetCurrentThreadId() As Integer
  24.    End Function
  25.  
  26.    <DllImport("user32.dll")> _
  27.    Private Shared Function GetClassName(hWnd As IntPtr, buffer As StringBuilder, buflen As Integer) As Integer
  28.    End Function
  29.  
  30.    <DllImport("user32.dll")> _
  31.    Private Shared Function GetDlgItem(hWnd As IntPtr, item As Integer) As IntPtr
  32.    End Function
  33.  
  34.    <DllImport("user32.dll")> _
  35.    Private Shared Function SendMessage(hWnd As IntPtr, msg As Integer, wp As IntPtr, lp As IntPtr) As IntPtr
  36.    End Function
  37.  
  38.    <DllImport("user32.dll")> _
  39.    Shared Function GetWindowRect(hWnd As IntPtr, ByRef rc As RECT) As Boolean
  40.    End Function
  41.  
  42.    <DllImport("user32.dll")> _
  43.    Shared Function MoveWindow(hWnd As IntPtr, x As Integer, y As Integer, w As Integer, h As Integer, repaint As Boolean) As Boolean
  44.    End Function
  45.  
  46.    Structure RECT
  47.        Public Left As Integer
  48.        Public Top As Integer
  49.        Public Right As Integer
  50.        Public Bottom As Integer
  51.    End Structure
  52.  
  53.    Public Sub New(owner As Form, Optional Custom_Font As Font = Nothing)
  54.        mOwner = owner
  55.        mFont = Custom_Font
  56.        owner.BeginInvoke(New MethodInvoker(AddressOf findDialog))
  57.    End Sub
  58.  
  59.    Private Sub findDialog()
  60.  
  61.        ' Enumerate windows to find the message box
  62.        If mTries < 0 Then
  63.            Return
  64.        End If
  65.  
  66.        Dim callback As New EnumThreadWndProc(AddressOf checkWindow)
  67.  
  68.        If EnumThreadWindows(GetCurrentThreadId(), callback, IntPtr.Zero) Then
  69.            If System.Threading.Interlocked.Increment(mTries) < 10 Then
  70.                mOwner.BeginInvoke(New MethodInvoker(AddressOf findDialog))
  71.            End If
  72.        End If
  73.  
  74.    End Sub
  75.  
  76.    Private Function checkWindow(hWnd As IntPtr, lp As IntPtr) As Boolean
  77.  
  78.        ' Checks if <hWnd> is a dialog
  79.        Dim sb As New StringBuilder(260)
  80.        GetClassName(hWnd, sb, sb.Capacity)
  81.        If sb.ToString() <> "#32770" Then Return True
  82.  
  83.        ' Got it, get the STATIC control that displays the text
  84.        Dim hText As IntPtr = GetDlgItem(hWnd, &HFFFF)
  85.  
  86.        Dim frmRect As New Rectangle(mOwner.Location, mOwner.Size)
  87.        Dim dlgRect As RECT
  88.        GetWindowRect(hWnd, dlgRect)
  89.        MoveWindow(hWnd, frmRect.Left + (frmRect.Width - dlgRect.Right + dlgRect.Left) \ 2, frmRect.Top + (frmRect.Height - dlgRect.Bottom + dlgRect.Top) \ 2, dlgRect.Right - dlgRect.Left, dlgRect.Bottom - dlgRect.Top, True)
  90.        If hText <> IntPtr.Zero Then
  91.  
  92.            If mFont Is Nothing Then
  93.                ' Get the current font
  94.                mFont = Font.FromHfont(SendMessage(hText, WM_GETFONT, IntPtr.Zero, IntPtr.Zero))
  95.            End If
  96.  
  97.            SendMessage(hText, WM_SETFONT, mFont.ToHfont(), New IntPtr(1))
  98.  
  99.        End If
  100.  
  101.        ' Done
  102.        Return False
  103.  
  104.    End Function
  105.  
  106.    Public Sub Dispose() Implements IDisposable.Dispose
  107.        mTries = -1
  108.        mOwner = Nothing
  109.        If mFont IsNot Nothing Then mFont.Dispose()
  110.    End Sub
  111.  
  112. End Class
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.878



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #308 en: 10 Octubre 2013, 23:57 pm »

Un ayudante para manejar la aplicación dBpoweramp Music Converter, es el mejor conversor archivos de música a cualquier formato.

http://www.dbpoweramp.com/dmc.htm

Le agregué lo necesario para convertir a MP3, WAV, y WMA, se puede extender para agregar todos los demás codecs, pero es muy tedioso...

Tambiñen le agregué un par de eventos para capturar el progreso de conversión y mensajes de errores, el modo de empleo está explicado en los primeros comentarios.

PD: También existe una librería llamada dMcscriptinglib.dll, pero los autores de dbPowerAmp me dijeron que no es posible capturar el progreso de una conversión usando la librería, por ese motivo uso el executable CLI.

EDITO: Corregido un bug en las Enumeraciones del SampleRate de los Codecs, y he simplificado parte del código.

Código
  1. #Region " CoreConverter Helper "
  2.  
  3.  
  4.  
  5. ' [ CoreConverter Helper ]
  6. '
  7. ' // By Elektro H@cker
  8. '
  9. '
  10. ' Instructions:
  11. '
  12. ' 1. Add the "CoreConverter.exe" into the project,
  13. '    together with the dbPoweramp Effects and Codec folders.
  14. '
  15. ' Examples :
  16. '
  17. ' -------------------
  18. ' CONVERT FILE TO MP3
  19. ' -------------------
  20. ' CoreConverter.Convert_To_MP3("C:\Input.wav", "C:\Output.mp3", _
  21. '                              CoreConverter.Lame_Bitrate.kbps_320, _
  22. '                              CoreConverter.Lame_Bitrate_Mode.cbr, _
  23. '                              CoreConverter.Lame_Profile.SLOW, _
  24. '                              CoreConverter.Lame_Quality.Q0_Maximum, _
  25. '                              CoreConverter.Lame_Khz.Same_As_Source, _
  26. '                              CoreConverter.Lame_Channels.auto, _
  27. '                              { _
  28. '                                CoreConverter.DSP_Effects.Delete_Output_File_on_Error, _
  29. '                                CoreConverter.DSP_Effects.Recycle_Source_File_After_Conversion _
  30. '                              }, _
  31. '                              False, _
  32. '                              CoreConverter.Priority.normal)
  33. '
  34. ' -------------------
  35. ' CONVERT FILE TO WAV
  36. ' -------------------
  37. ' CoreConverter.Convert_To_WAV_Uncompressed("C:\Input.mp3", "C:\Output.wav", _
  38. '                                           CoreConverter.WAV_Uncompressed_Bitrate.Same_As_Source, _
  39. '                                           CoreConverter.WAV_Uncompressed_Khz.Same_As_Source, _
  40. '                                           CoreConverter.WAV_Uncompressed_Channels.Same_As_Source, , False)
  41. '
  42. ' -------------------
  43. ' CONVERT FILE TO WMA
  44. ' -------------------
  45. ' CoreConverter.Convert_To_WMA("C:\Input.mp3", "C:\Output.wma", _
  46. '                              CoreConverter.WMA_9_2_BitRates.Kbps_128, _
  47. '                              CoreConverter.WMA_9_2_Khz.Khz_44100, _
  48. '                              CoreConverter.WMA_9_2_Channels.stereo, , False)
  49. '
  50. ' ------
  51. ' EVENTS
  52. ' ------
  53. ' Public WithEvents Converter As New CoreConverter()
  54. '
  55. ' Sub Converter_Progress(Progress As Integer, e As EventArgs) Handles Converter.PercentDone
  56. '     ProgressBar1.Maximum = 59
  57. '     ProgressBar1.Step = 1
  58. '     ProgressBar1.PerformStep()
  59. ' End Sub
  60. '
  61. ' Sub Converter_Message(Message As String, e As EventArgs) Handles Converter.Exited
  62. '     ProgressBar1.Value = 0
  63. '     MessageBox.Show(Message)
  64. ' End Sub
  65.  
  66.  
  67.  
  68. Public Class CoreConverter : Implements IDisposable
  69.  
  70. #Region " Variables "
  71.  
  72.    ' <summary>
  73.    ' Gets or sets CoreConverter.exe executable path.
  74.    ' </summary>
  75.    Public Shared CoreConverter_Location As String = ".\CoreConverter.exe"
  76.  
  77.    ' Stores the CoreConverter process progress
  78.    Private Shared CurrentProgress As Integer = 0
  79.  
  80.    ' Stores the CoreConverter process StandarOutput
  81.    Private Shared StandardOutput As String = String.Empty
  82.  
  83.    ' Stores the CoreConverter process ErrorOutput
  84.    Private Shared ErrorOutput As String = String.Empty
  85.  
  86.    ' Stores the next output character
  87.    Private Shared OutputCharacter As Char = Nothing
  88.  
  89.    ' Stores the DSP Effects formatted string
  90.    Private Shared Effects As String = String.Empty
  91.  
  92. #End Region
  93.  
  94. #Region " Events "
  95.  
  96.    ' <summary>
  97.    ' Event raised when conversion progress changes.
  98.    ' </summary>
  99.    Public Shared Event PercentDone As EventHandler(Of PercentDoneEventArgs)
  100.    Public Class PercentDoneEventArgs : Inherits EventArgs
  101.        Public Property Progress As Integer
  102.    End Class
  103.  
  104.    ' <summary>
  105.    ' Event raised when CoreConverter process has exited.
  106.    ' </summary>
  107.    Public Shared Event Exited As EventHandler(Of ExitedEventArgs)
  108.    Public Class ExitedEventArgs : Inherits EventArgs
  109.        Public Property Message As String
  110.    End Class
  111.  
  112. #End Region
  113.  
  114. #Region " Process Info "
  115.  
  116.    ' CoreConverter Process Information.
  117.    Private Shared CoreConverter As New Process() With { _
  118.        .StartInfo = New ProcessStartInfo With { _
  119.        .CreateNoWindow = True, _
  120.        .UseShellExecute = False, _
  121.        .RedirectStandardError = True, _
  122.        .RedirectStandardOutput = True, _
  123.        .StandardErrorEncoding = System.Text.Encoding.Unicode, _
  124.        .StandardOutputEncoding = System.Text.Encoding.Unicode}}
  125.  
  126. #End Region
  127.  
  128. #Region " CoreConverter Enumerations "
  129.  
  130.    ' Priority level of CoreConverter.exe
  131.    Enum Priority
  132.        idle
  133.        low
  134.        normal
  135.        high
  136.    End Enum
  137.  
  138.    ' DSP Effects
  139.    Public Enum DSP_Effects
  140.        Delete_Output_File_on_Error ' Delete failed conversion (not deletes source file).
  141.        Delete_Source_File_After_Conversion ' Delete source file after conversion.
  142.        Recycle_Source_File_After_Conversion ' Send source file to recycle bin after conversion.
  143.        Karaoke_Remove_Voice ' Remove voice from file.
  144.        Karaoke_Remove_Instrument ' Remove instruments from file.
  145.        Reverse ' Reverse complete audio file.
  146.        Write_Silence ' Write silence at start of file.
  147.    End Enum
  148.  
  149. #End Region
  150.  
  151. #Region " Codec Enumerations "
  152.  
  153. #Region " MP3 Lame "
  154.  
  155.    Enum Lame_Bitrate
  156.        kbps_8 = 8
  157.        kbps_16 = 16
  158.        kbps_24 = 24
  159.        kbps_32 = 32
  160.        kbps_40 = 40
  161.        kbps_48 = 48
  162.        kbps_56 = 56
  163.        kbps_64 = 64
  164.        kbps_80 = 80
  165.        kbps_96 = 96
  166.        kbps_112 = 112
  167.        kbps_128 = 128
  168.        kbps_144 = 144
  169.        kbps_160 = 160
  170.        kbps_192 = 192
  171.        kbps_224 = 224
  172.        kbps_256 = 256
  173.        kbps_320 = 320
  174.    End Enum
  175.  
  176.    Enum Lame_Bitrate_Mode
  177.        cbr
  178.        abr
  179.    End Enum
  180.  
  181.    Enum Lame_Profile
  182.        NORMAL
  183.        FAST
  184.        SLOW
  185.    End Enum
  186.  
  187.    Enum Lame_Quality
  188.        Q0_Maximum = 0
  189.        Q1 = 1
  190.        Q2 = 2
  191.        Q3 = 3
  192.        Q4 = 4
  193.        Q5 = 5
  194.        Q6 = 6
  195.        Q7 = 7
  196.        Q8 = 8
  197.        Q9_Minimum = 9
  198.    End Enum
  199.  
  200.    Enum Lame_Khz
  201.        Same_As_Source
  202.        khz_8000 = 8000
  203.        khz_11025 = 11025
  204.        khz_12000 = 12000
  205.        khz_16000 = 16000
  206.        khz_22050 = 22050
  207.        khz_24000 = 24000
  208.        khz_32000 = 32000
  209.        khz_44100 = 44100
  210.        khz_48000 = 48000
  211.    End Enum
  212.  
  213.    Enum Lame_Channels
  214.        auto
  215.        mono
  216.        stereo
  217.        joint_stereo
  218.        forced_joint_stereo
  219.        forced_stereo
  220.        dual_channels
  221.    End Enum
  222.  
  223.  
  224. #End Region
  225.  
  226. #Region " WAV Uncompressed "
  227.  
  228.    Enum WAV_Uncompressed_Bitrate
  229.        Same_As_Source
  230.        bits_8 = 8
  231.        bits_16 = 16
  232.        bits_24 = 24
  233.        bits_32 = 32
  234.    End Enum
  235.  
  236.    Enum WAV_Uncompressed_Khz
  237.        Same_As_Source
  238.        khz_8000 = 8000
  239.        khz_11025 = 11025
  240.        khz_12000 = 12000
  241.        khz_16000 = 16000
  242.        khz_22050 = 22050
  243.        khz_24000 = 24000
  244.        khz_32000 = 32000
  245.        khz_44100 = 44100
  246.        khz_48000 = 48000
  247.        khz_96000 = 96000
  248.        khz_192000 = 192000
  249.    End Enum
  250.  
  251.    Enum WAV_Uncompressed_Channels
  252.        Same_As_Source
  253.        Channels_1_Mono = 1
  254.        Channels_2_Stereo = 2
  255.        Channels_3 = 3
  256.        Channels_4_Quadraphonic = 4
  257.        Channels_5_Surround = 5
  258.        Channels_6_Surround_DVD = 6
  259.        Channels_7 = 7
  260.        Channels_8_Theater = 8
  261.    End Enum
  262.  
  263. #End Region
  264.  
  265. #Region " WMA 9.2 "
  266.  
  267.    Enum WMA_9_2_BitRates
  268.        Kbps_12 = 12
  269.        Kbps_16 = 16
  270.        Kbps_20 = 20
  271.        Kbps_22 = 22
  272.        Kbps_24 = 24
  273.        Kbps_32 = 32
  274.        Kbps_40 = 40
  275.        Kbps_48 = 48
  276.        Kbps_64 = 64
  277.        Kbps_80 = 80
  278.        Kbps_96 = 96
  279.        Kbps_128 = 128
  280.        Kbps_160 = 160
  281.        Kbps_192 = 192
  282.        Kbps_256 = 256
  283.        Kbps_320 = 320
  284.    End Enum
  285.  
  286.    Enum WMA_9_2_Khz
  287.        Khz_8000 = 8
  288.        Khz_16000 = 16
  289.        Khz_22050 = 22
  290.        Khz_32000 = 32
  291.        Khz_44100 = 44
  292.        Khz_48000 = 48
  293.    End Enum
  294.  
  295.    Enum WMA_9_2_Channels
  296.        mono
  297.        stereo
  298.    End Enum
  299.  
  300. #End Region
  301.  
  302. #End Region
  303.  
  304. #Region " Codec Procedures "
  305.  
  306. #Region " MP3 Lame "
  307.  
  308.    ' <summary>
  309.    ' Converts a file to MP3 using Lame codec.
  310.    ' </summary>
  311.    Public Shared Sub Convert_To_MP3(ByVal In_File As String, _
  312.                             ByVal Out_File As String, _
  313.                             ByVal Bitrate As Lame_Bitrate, _
  314.                             ByVal Bitrate_Mode As Lame_Bitrate_Mode, _
  315.                             ByVal Encoding_Profile As Lame_Profile, _
  316.                             ByVal Quality As Lame_Quality, _
  317.                             ByVal Khz As Lame_Khz, _
  318.                             ByVal Channels As Lame_Channels, _
  319.                             Optional ByVal DSP_Effects() As DSP_Effects = Nothing, _
  320.                             Optional ByVal Update_Tag As Boolean = True, _
  321.                             Optional ByVal Priority As Priority = Priority.normal, _
  322.                             Optional ByVal Processor As Short = 1)
  323.  
  324.        Get_Effects(DSP_Effects)
  325.  
  326.        Set_Main_Parametters("mp3 (Lame)", In_File, Out_File, If(Not Update_Tag, "-noidtag", ""), Effects, Priority.ToString, Processor.ToString)
  327.  
  328.        CoreConverter.StartInfo.Arguments &= _
  329.        String.Format("-b {0} --{1} -encoding=""{2}"" -freq=""{3}"" -channels=""{4}"" --noreplaygain --extracli=""-q {5}""", _
  330.                      CInt(Bitrate), _
  331.                      Bitrate_Mode.ToString, _
  332.                      Encoding_Profile.ToString, _
  333.                      If(Khz = Lame_Khz.Same_As_Source, "", CInt(Khz)), _
  334.                      If(Channels = Lame_Channels.auto, "", Channels), _
  335.                      CInt(Quality))
  336.  
  337.        Run_CoreConverter()
  338.  
  339.    End Sub
  340.  
  341. #End Region
  342.  
  343. #Region " WAV Uncompressed "
  344.  
  345.    ' <summary>
  346.    ' Converts a file to WAV
  347.    ' </summary>
  348.    Public Shared Sub Convert_To_WAV_Uncompressed(ByVal In_File As String, _
  349.                                 ByVal Out_File As String, _
  350.                                 ByVal Bitrate As WAV_Uncompressed_Bitrate, _
  351.                                 ByVal Khz As WAV_Uncompressed_Khz, _
  352.                                 ByVal Channels As WAV_Uncompressed_Channels, _
  353.                                 Optional ByVal DSP_Effects() As DSP_Effects = Nothing, _
  354.                                 Optional ByVal Update_Tag As Boolean = True, _
  355.                                 Optional ByVal Priority As Priority = Priority.normal, _
  356.                                 Optional ByVal Processor As Short = 1)
  357.  
  358.        Get_Effects(DSP_Effects)
  359.  
  360.        Set_Main_Parametters("Wave", In_File, Out_File, If(Not Update_Tag, "-noidtag", ""), Effects, Priority.ToString, Processor.ToString)
  361.  
  362.        CoreConverter.StartInfo.Arguments &= _
  363.        String.Format("-compression=""PCM"" -bits=""{0}"" -freq=""{1}"" -channels=""{2}""", _
  364.                      If(Bitrate = WAV_Uncompressed_Bitrate.Same_As_Source, "", CInt(Bitrate)), _
  365.                      If(Khz = WAV_Uncompressed_Khz.Same_As_Source, "", CInt(Khz)), _
  366.                      If(Channels = WAV_Uncompressed_Channels.Same_As_Source, "", CInt(Channels)))
  367.  
  368.        Run_CoreConverter()
  369.  
  370.    End Sub
  371.  
  372. #End Region
  373.  
  374. #Region " WMA 9.2 "
  375.  
  376.    ' <summary>
  377.    ' Converts a file to WMA 9.2
  378.    ' </summary>
  379.    Public Shared Sub Convert_To_WMA(ByVal In_File As String, _
  380.                                 ByVal Out_File As String, _
  381.                                 ByVal Bitrate As WMA_9_2_BitRates, _
  382.                                 ByVal Khz As WMA_9_2_Khz, _
  383.                                 ByVal Channels As WMA_9_2_Channels, _
  384.                                 Optional ByVal DSP_Effects() As DSP_Effects = Nothing, _
  385.                                 Optional ByVal Update_Tag As Boolean = True, _
  386.                                 Optional ByVal Priority As Priority = Priority.normal, _
  387.                                 Optional ByVal Processor As Short = 1)
  388.  
  389.        Get_Effects(DSP_Effects)
  390.  
  391.        Set_Main_Parametters("Windows Media Audio 10", In_File, Out_File, If(Not Update_Tag, "-noidtag", ""), Effects, Priority.ToString, Processor.ToString)
  392.  
  393.        CoreConverter.StartInfo.Arguments &= _
  394.        String.Format("-codec=""Windows Media Audio 9.2"" -settings=""{0} kbps, {1} kHz, {2} CBR""",
  395.                      CInt(Bitrate), _
  396.                      CInt(Khz), _
  397.                      Channels.ToString)
  398.  
  399.        Run_CoreConverter()
  400.  
  401.    End Sub
  402.  
  403. #End Region
  404.  
  405. #End Region
  406.  
  407. #Region " Run Converter Procedure "
  408.  
  409.    Private Shared Sub Run_CoreConverter()
  410.  
  411.        CoreConverter.StartInfo.FileName = CoreConverter_Location
  412.        CoreConverter.Start()
  413.  
  414.        While Not CoreConverter.HasExited
  415.  
  416.            OutputCharacter = ChrW(CoreConverter.StandardOutput.Read)
  417.  
  418.            If OutputCharacter = "*" Then
  419.                CurrentProgress += 1 ' Maximum value is 59, so a ProgressBar Maximum property value would be 59.
  420.                RaiseEvent PercentDone(CurrentProgress, Nothing)
  421.            End If
  422.  
  423.            If CurrentProgress = 59 Then
  424.                ' I store the last line(s) 'cause it has interesting information:
  425.                ' Example message: Conversion completed in 30 seconds x44 realtime encoding
  426.                StandardOutput = CoreConverter.StandardOutput.ReadToEnd.Trim
  427.            End If
  428.  
  429.        End While
  430.  
  431.        ' Stores the Error Message (If any)
  432.        ErrorOutput = CoreConverter.StandardError.ReadToEnd
  433.  
  434.        Select Case CoreConverter.ExitCode
  435.  
  436.            Case 0 : RaiseEvent Exited(StandardOutput, Nothing) ' Return StandardOutput
  437.            Case Else : RaiseEvent Exited(ErrorOutput, Nothing) ' Return ErrordOutput
  438.  
  439.        End Select
  440.  
  441.        CurrentProgress = Nothing
  442.        OutputCharacter = Nothing
  443.        StandardOutput = Nothing
  444.        ErrorOutput = Nothing
  445.        Effects = Nothing
  446.        CoreConverter.Close()
  447.  
  448.    End Sub
  449.  
  450. #End Region
  451.  
  452. #Region " Miscellaneous functions "
  453.  
  454.    ' <summary>
  455.    ' Checks if CoreConverter process is avaliable.
  456.    ' </summary>
  457.    Public Shared Function Is_Avaliable() As Boolean
  458.        Return IO.File.Exists(CoreConverter_Location)
  459.    End Function
  460.  
  461.    ' Set the constant parametters of CoreConverter process
  462.    Private Shared Sub Set_Main_Parametters(ByVal Codec_Name As String, _
  463.                                            ByVal In_File As String, _
  464.                                            ByVal Out_File As String, _
  465.                                            ByVal Update_Tag As String, _
  466.                                            ByVal Effects As String, _
  467.                                            ByVal Priority As String, _
  468.                                            ByVal Processor As String)
  469.  
  470.        CoreConverter.StartInfo.Arguments = _
  471.        String.Format("-infile=""{0}"" -outfile=""{1}"" -convert_to=""{2}"" {3} {4} -priority=""{5}"" -processor=""{6}"" ", _
  472.                      In_File, Out_File, Codec_Name, Update_Tag, Effects, Priority, Processor)
  473.  
  474.    End Sub
  475.  
  476.    ' Returns all joined DSP Effects formatted string
  477.    Private Shared Function Get_Effects(ByVal DSP_Effects() As DSP_Effects) As String
  478.  
  479.        If DSP_Effects Is Nothing Then Return Nothing
  480.  
  481.        For Effect As Integer = 0 To DSP_Effects.Length - 1
  482.            Effects &= String.Format(" -dspeffect{0}={1}", _
  483.                                     Effect + 1, _
  484.                                     Format_DSP_Effect(DSP_Effects(Effect).ToString))
  485.        Next Effect
  486.  
  487.        Return Effects
  488.  
  489.    End Function
  490.  
  491.    ' Returns a DSP Effect formatted string
  492.    Private Shared Function Format_DSP_Effect(ByVal Effect As String)
  493.  
  494.        Select Case Effect
  495.            Case "Reverse" : Return """Reverse"""
  496.            Case "Delete_Output_File_on_Error" : Return """Delete Destination File on Error="""
  497.            Case "Recycle_Source_File_After_Conversion" : Return """Delete Source File=-recycle"""
  498.            Case "Delete_Source_File_After_Conversion" : Return """Delete Source File="""
  499.            Case "Karaoke_Remove_Voice" : Return """Karaoke (Voice_ Instrument Removal)="""
  500.            Case "Karaoke_Remove_Instrument" : Return """Karaoke (Voice_ Instrument Removal)=-i"""
  501.            Case "Write_Silence" : Return """Write Silence=-lengthms={qt}2000{qt}""" ' 2 seconds
  502.            Case Else : Return String.Empty
  503.        End Select
  504.  
  505.    End Function
  506.  
  507. #End Region
  508.  
  509. #Region " Dispose Objects "
  510.  
  511.    Public Sub Dispose() Implements IDisposable.Dispose
  512.        ' CoreConverter_Location = Nothing ' Do not change if want to preserve a custom location.
  513.        OutputCharacter = Nothing
  514.        StandardOutput = Nothing
  515.        ErrorOutput = Nothing
  516.        CurrentProgress = Nothing
  517.        Effects = Nothing
  518.        CoreConverter.Close()
  519.        GC.SuppressFinalize(Me)
  520.    End Sub
  521.  
  522. #End Region
  523.  
  524. End Class
  525.  
  526. #End Region
« Última modificación: 11 Octubre 2013, 16:52 pm por EleKtro H@cker » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.878



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #309 en: 12 Octubre 2013, 01:04 am »

Este snippet comprueba si un nombre de archivo contiene caracteres que no estén en la tabla ASCII (sin contar la tabla ASCII extendida)

Un ejemplo de uso sería, el que yo le doy:
yo dejo el PC descargando miles de archivos de música diariamente, muchos de los nombres de archivos descargados contienen caracteres rusos y otras mierd@s que luego me toca renombrar de forma manual porque no se pueden leer estos nomrbes de archivos por otros programas que uso.

PD: No contiene todos los caracteres de la tabla ASCII normal, recordemos que Windows no permite escribir ciertos caracteres ASCII en los nombres de archivo, asi que no es necesario añadir dichos caracteres la función, además le añadí el caracter "Ñ", y los caracteres de la tabla ASCII extendida yo los considero caracteres extraños, quizás el nombre de la función debería ser: "Filename Has Strange Characters? " :P.

Código:
#Region " Filename Has Non ASCII Characters "

    ' [ Filename Has Non ASCII Characters Function ]
    '
    ' // By Elektro H@cker
    '
    ' Examples :
    ' MsgBox(Filename_Has_Non_ASCII_Characters("ABC├│")) ' Result: True
    ' MsgBox(Filename_Has_Non_ASCII_Characters("ABCDE")) ' Result: False

    Private Function Filename_Has_Non_ASCII_Characters(ByVal [String] As String) As Boolean

        Dim Valid_Characters As String = ( _
            "abcdefghijklmnñopqrstuvwxyz" & _
            "ABCDEFGHIJKLMNÑOPQRSTUVWXYZ" & _
            "áéíóúÁÉÍÓÚàèìòùÀÈÌÒÙçÇ" & _
            "@#~€!·$%&()=!'ºª+-_.,;{}[]" & _
            ":\" & _
            "0123456789" & _
            " " _
        )

        Return Not [String].ToCharArray() _
                   .All(Function(character) Valid_Characters.Contains(character))

        ' Valid_Characters = Nothing

    End Function

#End Region
« Última modificación: 12 Octubre 2013, 01:15 am por EleKtro H@cker » En línea



Páginas: 1 ... 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 [31] 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 ... 60 Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines