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


Tema destacado: Introducción a la Factorización De Semiprimos (RSA)


  Mostrar Mensajes
Páginas: 1 ... 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 [806] 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 ... 1254
8051  Programación / Scripting / Re: [b]Retos python ... u otro lenguaje de scripting....[/b] en: 11 Noviembre 2013, 04:45 am
De esto ya había una sección abierta, has preguntado si sigue activa o si se tiene intención de seguir? La verdad es que yo también estoy interesado, pues es una buena forma de practicar.

Cita de: Fran2013
El ultimo registro de temas como este es de junio del 2012 ...  ;D

Aquél post está con chincheta, por algo será, no importa que el último reto sea del año pasado, que la gente no haya querido aportar no significa que la zona de retos haya dejado de existir.

Es más, mientras haya gente que se dedique a crear nuevos recopilatorios de retos y/o rankings por su cuenta (como este), jamás se podrá llevar a cabo una estructura ni una zona de retos con suficiente sensatez, pues este post con el paso dle tiempo habría quedado en el olvido como todos los demás, por ese motivo se creó un post con chincheta, para permanecer y no crear decenas de posts sobre la misma temática.

Siento decirtelo, @Fran2013, pero deberías haber preguntado como ya te han dicho, el foro es libre, pero preguntar es lo mínimo que podrías haber hecho símplemente por respeto hacia las iniciativas de las demás personas.

He estado ausente unos dias y me encuentro con esto.

Siento ser un aguafiestas chavales, quizás alguno me vaya a ver como una especie de monstruo por esto pero voy a tener que imponer una nueva norma en las normas ya impuestas del subforo de Scripting para que no se publiquen más rankings de retos existiendo ya una sección totálmente dedicada por y para los retos. (La próxima vez fijarse un poco más los temas con chinchetas, o preguntar)

Imagino que muchos os agradecerán la iniciativa y la participación, sobretodo yo, de verdad, gracias, pero esta no ha sido la mejor manera @Fran2013.

Aquí pueden leer las nuevas normas del foro de Scripting:
http://foro.elhacker.net/scripting/normas_del_tablon_leer_antes_de_postear-t201567.0.html;msg957615#msg957615







Para todos los interesados, la zona de retos sigue abierta para todos aquellos que quieran participar y contribuir, solo tienen que hacerlo, considero que la estructura del juego es muy sencilla.

Espero que no dejeis de contribuir con vuestros aportes y vuestros retos, podeis crear posts con retos, porsupuesto, pero sólamente un post por reto y yo me encargaré de añadirlo a los retos de Scripting, ...no plagieis una recopilación de retos con un ranking, eso ya existe y ya forma parte del foro.

Y porfavor, al publicar un reto en solitario, hacerlo siguiendo las reglas de participación del siguiente hilo, que para eso fue creado por un servidor:

http://foro.elhacker.net/scripting/zona_de_retos_scripting-t360782.0.html



Cierro el tema,
cualquier cosa me la pueden comentar por mensaje privado.

Saludos!
8052  Programación / Scripting / Re: Pequeños Proyectos Python... en: 11 Noviembre 2013, 03:12 am
Creo este tema para que se propongan pequeños proyectos en python...

¿Que hay que no se haya inventado ya? :P

Algún WebSpider para alguna página en concreto no estaría nada mal... siempre me han gustado, este tipo de proyectos suelen estar infravalorados (o al menos eso pienso, depende que tipo de página sea quizás solo lo usen 4 gatos, si haces uno relacionado con Facebook quien sabe...) pero la verdad es que son muy útiles y ahorran mucho tiempo, aquí tienes un muy buen ejemplo en Python con GUI por el compañero @0x5d (aunque no es un código muy extenso, según lo que intuyo por la sintaxis y los keywords solo hace una única petición a la url y parsea el source de la respuesta):

http://foro.elhacker.net/scripting/codigopyqt4_iconfinder_jaavier_0x5d-t401819.0.html

PD: Python no es lo mio, que tengas suerte!
8053  Programación / Scripting / Re: Batch Regedit [En que fallo?] en: 11 Noviembre 2013, 02:53 am
@Sonco

Primero de nada, porfavor, no sigas abusando de las letras en colores, es una norma del foro.

Lo que has marcado con un circulo rojo en la imagen, es la representación decimal del valor hexadecimal, y tu estás intentando usar un valor hexadecimal,
No hay ningún problema en especificarle el valor hexadecimal al comando, pero estás usando incorréctamente la sintaxis, tienes que especificar el valor hexadecimal de esta manera:
Código
  1. reg add "HKCU\Software\Microsoft\Command Processor" /v DefaultColor /t reg_dword /d "0x1e" /f

Y también, si lo prefieres, puedes usar la representación decimal:
Código
  1. reg add "HKCU\Software\Microsoft\Command Processor" /v DefaultColor /t reg_dword /d "30" /f

Saludos.
8054  Programación / Scripting / Re: Duda en: 11 Noviembre 2013, 02:39 am
No se toleran los títulos de tipo "ayuda", "duda", "wtf", etc, etc, etc...

Además, tu duda habría sido mejor posteada en el subforo de desarrollo web.

Porfavor, leer las reglas.

-> foro.elhacker.net/reglas

Citar
I.A.1.a. Formato.

El título de los mensajes debe ser descriptivo con acuerdo al contenido. No son descriptivos asuntos que sólo piden ayuda o hacen referencia a la temática general del tablón en los que son escritos.
Los mensajes deben ser legibles y fácilmente entendibles, esto incluye...

Tema cerrado.
8055  Programación / Scripting / Re: Modificacion de archivos de texto (ini) en: 11 Noviembre 2013, 02:32 am
@krizalidk

Se te puede dar una solución adaptada al problema si respondes a las siguientes preguntas:

1. ¿El número de la linea siempre es el mismo, o la posición de la IP puede cambiar a otra linea?

2. ¿Solo hay una IP en el archivo INI?

3. ¿Lalinea de la IP está escrita de esta manera?:
Código:
NombreDelValor=xxx.xxx.xxx.xxx
¿...O de esta otra manera como has dicho en un principio?:
Código:
xxx.xxx.xxx.xxx

Saludos.
8056  Programación / Scripting / Re: Comparar parte de una IP en bash en: 11 Noviembre 2013, 02:19 am
Por si acaso, te muestro el RegEx, no me cuesta nada :P

Código:
^\d{1,3}\.\d{1,3}\.\d{1,3}\.

PD: La saqué en 10 segundos con una aplicación que desarrollé para diseñar expresiones regulares (según la sintaxis del motor RegEx de .NET), si necesitas la aplicación para futuras ocasiones solo dímelo por MP.

Saludos
8057  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets) en: 11 Noviembre 2013, 01:44 am
Un pequeño hook para capturar los mensajes del menú de edición del menú contextual (por defecto) de un Textbox (las opciones de copiar, pegar, cortar, y eliminar).

En un post anterior posteé la forma de capturarl dichos mensajes heredando el Textbox, pero este código es diferente, no depende de ningun control, se puede usar como otra Class cualquiera para capturar los mensajes en cualquier textbox (menos los textbox de Krypton y otros...) sin necesidad de heredar el control.

PD: El código no es del todo de mi propiedad, me han ayudado un poquito.

Código
  1. #Region " Capture Windows ContextMenu Edit Options "
  2.  
  3. ' [ Capture Windows ContextMenu Edit Options ]
  4. '
  5. ' Examples :
  6. '
  7. ' Public Class Form1
  8. '
  9. '     Private WithEvents EditMenu As New EditMenuHook
  10. '
  11. '     Protected Overrides Sub OnLoad(e As EventArgs)
  12. '         MyBase.OnLoad(e)
  13. '         ' Capture the EditMenu Messages for TextBox1 and TextBox2
  14. '         EditMenuHook.Controls = {TextBox1, TextBox2}
  15. '         ' Enable the Hook
  16. '         EditMenuHook.Enable(True)
  17. '     End Sub
  18. '
  19. '     Protected Overrides Sub OnClosed(e As EventArgs)
  20. '         ' Disable the Hook
  21. '         EditMenuHook.Enable(False)
  22. '         MyBase.OnClosed(e)
  23. '     End Sub
  24. '
  25. '     Private Sub TextBox_OnTextCommand(sender As Object, e As EditMenuHook.TextCommandEventArgs) _
  26. '     Handles EditMenu.OnCopy, EditMenu.OnCut, EditMenu.OnPaste, EditMenu.OnDelete
  27. '
  28. '         MessageBox.Show(String.Format("Control:{0}  Message:{1}", sender.name, e.Command.ToString))
  29. '
  30. '     End Sub
  31. '
  32. ' End Class
  33.  
  34. Imports System.Runtime.InteropServices
  35.  
  36. Friend Class EditMenuHook
  37.  
  38.    <DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall)> _
  39.    Public Overloads Shared Function SetWindowsHookEx _
  40.          (ByVal idHook As Integer, ByVal HookProc As CallBack, ByVal hInstance As IntPtr, ByVal wParam As Integer) As Integer
  41.    End Function
  42.  
  43.    <DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall)> _
  44.    Public Overloads Shared Function CallNextHookEx _
  45.          (ByVal idHook As Integer, ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer
  46.    End Function
  47.  
  48.    <DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall)> _
  49.    Public Overloads Shared Function UnhookWindowsHookEx _
  50.              (ByVal idHook As Integer) As Boolean
  51.    End Function
  52.  
  53.    Public Enum TextCommandMessage
  54.        WM_CUT = &H300
  55.        WM_COPY = &H301
  56.        WM_PASTE = &H302
  57.        WM_DELETE = &H303
  58.    End Enum
  59.  
  60.    Public Structure CWPSTRUCT
  61.        Public lParam As IntPtr
  62.        Public wParam As IntPtr
  63.        Public message As UInt32
  64.        Public hWnd As IntPtr
  65.    End Structure
  66.  
  67.    Public Delegate Function CallBack( _
  68.        ByVal nCode As Integer, _
  69.        ByVal wParam As IntPtr, _
  70.        ByVal lParam As IntPtr) As Integer
  71.  
  72.    Private Shared WithEvents CopyOrCut_Timer As New Timer _
  73.                   With {.Interval = 50, .Enabled = False}
  74.  
  75.    ' The Control to monitor and report the TextCommand Messages.
  76.    Public Shared Controls As Control() = Nothing
  77.  
  78.    Public Shared MessagesEnabled As Boolean = True
  79.  
  80.    Private Shared CopyMessageEnabled As Boolean = True
  81.  
  82.    Shared hHook As Integer = 0
  83.  
  84.    Private Shared cwp As CWPSTRUCT
  85.  
  86.    Private Const WH_CALLWNDPROC = 4
  87.  
  88.    'Keep the reference so that the delegate is not garbage collected.
  89.    Private Shared hookproc As CallBack
  90.  
  91.    Public Class TextCommandEventArgs
  92.        Inherits EventArgs
  93.        Public Property Command As TextCommandMessage
  94.    End Class
  95.  
  96.    Shared Event OnCut(sender As Object, e As TextCommandEventArgs)
  97.    Shared Event OnCopy(sender As Object, e As TextCommandEventArgs)
  98.    Shared Event OnPaste(sender As Object, e As TextCommandEventArgs)
  99.    Shared Event OnDelete(sender As Object, e As TextCommandEventArgs)
  100.  
  101.    Friend Shared Sub Enable(enable As Boolean)
  102.  
  103.        If hHook = 0 AndAlso enable = True Then
  104.  
  105.            hookproc = AddressOf EditCommandHook
  106.            hHook = SetWindowsHookEx(WH_CALLWNDPROC, _
  107.                                     hookproc, _
  108.                                     IntPtr.Zero, _
  109.                                     AppDomain.GetCurrentThreadId())
  110.  
  111.            If hHook.Equals(0) Then
  112.                MsgBox("SetWindowsHookEx Failed")
  113.                Return
  114.            End If
  115.  
  116.        ElseIf hHook <> 0 AndAlso enable = False Then
  117.  
  118.            Dim ret As Boolean = UnhookWindowsHookEx(hHook)
  119.  
  120.            If ret.Equals(False) Then
  121.                MsgBox("UnhookWindowsHookEx Failed")
  122.                Return
  123.            Else
  124.                hHook = 0
  125.            End If
  126.  
  127.        End If
  128.  
  129.    End Sub
  130.  
  131.    Private Shared Function EditCommandHook(ByVal nCode As Integer, _
  132.                                            ByVal wParam As IntPtr, _
  133.                                            ByVal lParam As IntPtr) As Integer
  134.  
  135.        If nCode < 0 Then
  136.            Return CallNextHookEx(hHook, nCode, wParam, lParam)
  137.        End If
  138.  
  139.        cwp = DirectCast(Marshal.PtrToStructure(lParam, GetType(CWPSTRUCT)), CWPSTRUCT)
  140.  
  141.        For Each ctrl As Control In Controls
  142.  
  143.            If cwp.hWnd = ctrl.Handle Then
  144.  
  145.                Select Case cwp.message
  146.  
  147.                    Case TextCommandMessage.WM_CUT
  148.                        CopyMessageEnabled = False
  149.                        RaiseEvent OnCut(ctrl, New TextCommandEventArgs() _
  150.                                               With {.Command = TextCommandMessage.WM_CUT})
  151.  
  152.                    Case TextCommandMessage.WM_COPY
  153.                        If CopyMessageEnabled Then
  154.                            RaiseEvent OnCopy(ctrl, New TextCommandEventArgs() _
  155.                                                    With {.Command = TextCommandMessage.WM_COPY})
  156.                        Else
  157.                            CopyMessageEnabled = True
  158.                        End If
  159.  
  160.                    Case TextCommandMessage.WM_PASTE
  161.                        RaiseEvent OnPaste(ctrl, New TextCommandEventArgs() _
  162.                                                 With {.Command = TextCommandMessage.WM_PASTE})
  163.  
  164.                    Case TextCommandMessage.WM_DELETE
  165.                        RaiseEvent OnDelete(ctrl, New TextCommandEventArgs() _
  166.                                                  With {.Command = TextCommandMessage.WM_DELETE})
  167.  
  168.                End Select
  169.  
  170.            End If
  171.        Next
  172.  
  173.        Return CallNextHookEx(hHook, nCode, wParam, lParam)
  174.  
  175.    End Function
  176.  
  177. End Class
  178.  
  179. #End Region
8058  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets) en: 11 Noviembre 2013, 01:40 am
Una versión mejorada de mi ayudante para la aplicación mp3val... mejoré lo que pude el código y le añadi algunos eventos esenciales...

Un ejemplo de uso:

Código
  1.    Public Class Form1
  2.  
  3.        Private WithEvents _mp3val As New mp3val _
  4.                With {.mp3val_location = "C:\windows\system32\mp3val.exe",
  5.                      .CheckFileExist = True}
  6.  
  7.        Private Sub Test() Handles MyBase.Shown
  8.  
  9.            MsgBox(_mp3val.Is_Avaliable()) ' Checks if mp3gain executable is avaliable.
  10.  
  11.            MsgBox(_mp3val.Get_Tags(New IO.FileInfo("C:\File.mp3"))) ' Return the TagTypes of an MP3 file.
  12.  
  13.            _mp3val.Analyze("C:\File.mp3") ' Analyzes an MP3 file.
  14.  
  15.            _mp3val.Fix("C:\File.mp3") ' Fix an MP3 file.
  16.  
  17.        End Sub
  18.  
  19.        ' mp3val [Started]
  20.        Private Sub mp3val_Started(ByVal sender As Process, ByVal e As mp3val.StartedEventArgs) _
  21.        Handles _mp3val.Started
  22.  
  23.            Dim sb As New System.Text.StringBuilder
  24.  
  25.            sb.AppendLine(String.Format("Started an ""{0}"" operation", e.Operation.ToString))
  26.            sb.AppendLine(String.Format("Input file is: ""{0}""", e.File))
  27.            sb.AppendLine(String.Format("mp3val process PID is: ""{0}""", CStr(sender.Id)))
  28.  
  29.            MessageBox.Show(sb.ToString, "mp3val", MessageBoxButtons.OK, MessageBoxIcon.Information)
  30.  
  31.        End Sub
  32.  
  33.        ' mp3val [Exited]
  34.        Private Sub mp3val_Exited(ByVal sender As Process, ByVal e As mp3val.ExitedEventArgs) _
  35.        Handles _mp3val.Exited
  36.  
  37.            Dim sb As New System.Text.StringBuilder
  38.  
  39.            sb.AppendLine(String.Format("Finished an ""{1}"" operation in file ""{2}""{0}",
  40.                                        Environment.NewLine,
  41.                                        e.Operation.ToString,
  42.                                        e.File))
  43.  
  44.            sb.AppendLine(String.Format("File information:{0}{1}{0}",
  45.                                        Environment.NewLine,
  46.                                        e.Info))
  47.  
  48.            sb.AppendLine("Warnings found:")
  49.            If e.Warnings.Count Then
  50.                For Each wrn As String In e.Warnings
  51.                    sb.AppendLine(wrn)
  52.                Next wrn
  53.            Else
  54.                sb.AppendLine("Any" & Environment.NewLine)
  55.            End If
  56.  
  57.            sb.AppendLine("Errors found:")
  58.            If e.Errors.Count Then
  59.                For Each err As String In e.Errors
  60.                    sb.AppendLine(err)
  61.                Next err
  62.            Else
  63.                sb.AppendLine("Any" & Environment.NewLine)
  64.            End If
  65.  
  66.            If e.Operation = mp3val.Operation.Fix Then
  67.                sb.AppendLine(String.Format("File was fixed?: {0}",
  68.                                            e.FileIsFixed))
  69.            End If
  70.  
  71.            MessageBox.Show(sb.ToString,
  72.                            "mp3val",
  73.                            MessageBoxButtons.OK,
  74.                            MessageBoxIcon.Information)
  75.  
  76.        End Sub
  77.  
  78.    End Class

El ayudante:

Código:
' [ mp3val Helper ]
'
' // By Elektro H@cker
'
' Instructions:
' 1. Add the "mp3val.exe" into the directory project.

Código
  1. #Region " mp3val Helper "
  2.  
  3. Public Class mp3val : Implements IDisposable
  4.  
  5. #Region " CommandLine parametter legend "
  6.  
  7.    ' -f  | try to fix errors
  8.    ' -nb | delete .bak file
  9.    ' -t  | keep file timestamp
  10.  
  11. #End Region
  12.  
  13. #Region " Variables, Properties, Enums "
  14.  
  15.    ''' <summary>
  16.    ''' Gets or sets the mp3val executable path.
  17.    ''' </summary>
  18.    Public Property mp3val_location As String = ".\mp3val.exe"
  19.  
  20.    ''' <summary>
  21.    ''' Indicates if should check that the MP3 file exist before realize an operation.
  22.    ''' If True, an exception will be launched if file does not exist.
  23.    ''' </summary>
  24.    Public Property CheckFileExist As Boolean = False
  25.  
  26.    ''' <summary>
  27.    ''' Stores the process StandardOutput.
  28.    ''' </summary>
  29.    Private StandardOutput As String = String.Empty
  30.  
  31.    ''' <summary>
  32.    ''' Stores the process StandardError.
  33.    ''' </summary>
  34.    Private StandardError As String = String.Empty
  35.  
  36.    ''' <summary>
  37.    ''' Stores some information about the file.
  38.    ''' </summary>
  39.    Private Info As String = String.Empty
  40.  
  41.    ''' <summary>
  42.    ''' Stores all the warnings of the file.
  43.    ''' </summary>
  44.    Private Warnings As New List(Of String)
  45.  
  46.    ''' <summary>
  47.    ''' Stores all the errors of the file.
  48.    ''' </summary>
  49.    Private Errors As New List(Of String)
  50.  
  51.    ''' <summary>
  52.    ''' Stores the tags of the file.
  53.    ''' </summary>
  54.    Private Tags As String = String.Empty
  55.  
  56.    ''' <summary>
  57.    ''' Gets some information about the file.
  58.    ''' </summary>
  59.    Private Info_RegEx As New System.Text.RegularExpressions.Regex("INFO:.*:\s(.*)",
  60.                              System.Text.RegularExpressions.RegexOptions.Multiline)
  61.  
  62.    ''' <summary>
  63.    ''' Gets all the warning occurences.
  64.    ''' </summary>
  65.    Private Warning_RegEx As New System.Text.RegularExpressions.Regex("WARNING:.*:\s(.*)",
  66.                                 System.Text.RegularExpressions.RegexOptions.Multiline)
  67.  
  68.    ''' <summary>
  69.    ''' Gets a value indicating if the file was fixed or not.
  70.    ''' </summary>
  71.    Private Fixed_RegEx As New System.Text.RegularExpressions.Regex("^FIXED:",
  72.                               System.Text.RegularExpressions.RegexOptions.Multiline)
  73.  
  74.    ''' <summary>
  75.    ''' mp3val Process
  76.    ''' </summary>
  77.    Private p As Process =
  78.        New Process With {.StartInfo =
  79.            New ProcessStartInfo With {
  80.                  .CreateNoWindow = True,
  81.                  .UseShellExecute = False,
  82.                  .RedirectStandardError = True,
  83.                  .RedirectStandardOutput = True _
  84.           }
  85.        }
  86.  
  87.    ''' <summary>
  88.    ''' Stores the StartedEventArgs Arguments.
  89.    ''' </summary>
  90.    Private StartedArgs As New StartedEventArgs
  91.  
  92.    ''' <summary>
  93.    ''' Stores the ExitedEventArgs Arguments.
  94.    ''' </summary>
  95.    Private ExitedArgs As New ExitedEventArgs
  96.  
  97.    ''' <summary>
  98.    ''' MP3Val Type Of Operation.
  99.    ''' </summary>
  100.    Public Enum Operation As Short
  101.        Analyze = 0
  102.        Fix = 1
  103.        Get_Tags = 2
  104.    End Enum
  105.  
  106. #End Region
  107.  
  108. #Region " Events "
  109.  
  110.    ''' <summary>
  111.    ''' Event raised when the process has started.
  112.    ''' </summary>
  113.    Public Event Started As EventHandler(Of StartedEventArgs)
  114.    Public Class StartedEventArgs : Inherits EventArgs
  115.        ''' <summary>
  116.        ''' Gets the file that was passed as argument to the process.
  117.        ''' </summary>
  118.        Public Property File As String
  119.        ''' <summary>
  120.        ''' Gets the type of operation to realize.
  121.        ''' </summary>
  122.        Public Property Operation As Operation
  123.    End Class
  124.  
  125.    ''' <summary>
  126.    ''' Event raised when the process has exited.
  127.    ''' </summary>
  128.    Public Event Exited As EventHandler(Of ExitedEventArgs)
  129.    Public Class ExitedEventArgs : Inherits EventArgs
  130.        ''' <summary>
  131.        ''' Gets the file that was passed as argument to the process.
  132.        ''' </summary>
  133.        Public Property File As String
  134.        ''' <summary>
  135.        ''' Gets the type of operation to realize.
  136.        ''' </summary>
  137.        Public Property Operation As Operation
  138.        ''' <summary>
  139.        ''' Gets some information about the file.
  140.        ''' </summary>
  141.        Public Property Info As String
  142.        ''' <summary>
  143.        ''' Gets the warnings found.
  144.        ''' </summary>
  145.        Public Property Warnings As New List(Of String)
  146.        ''' <summary>
  147.        ''' Gets the errors found.
  148.        ''' </summary>
  149.        Public Property Errors As New List(Of String)
  150.        ''' <summary>
  151.        ''' Gets a value indicating if file was fixed.
  152.        ''' This is only usefull when doing a Fix operation.
  153.        ''' </summary>
  154.        Public Property FileIsFixed As Boolean
  155.    End Class
  156.  
  157. #End Region
  158.  
  159. #Region " MP3Val Procedures "
  160.  
  161.    ''' <summary>
  162.    ''' Checks if mp3val process is avaliable.
  163.    ''' </summary>
  164.    Public Function Is_Avaliable() As Boolean
  165.        Return IO.File.Exists(Me.mp3val_location)
  166.    End Function
  167.  
  168.    ''' <summary>
  169.    ''' Analyzes a file and returns the problems (if any).
  170.    ''' </summary>
  171.    Public Function Analyze(ByVal MP3_File As String) As List(Of String)
  172.  
  173.        Return Run_MP3VAL(MP3_File,
  174.                          Operation.Analyze,
  175.                          ControlChars.Quote & MP3_File & ControlChars.Quote)
  176.  
  177.    End Function
  178.  
  179.    ''' <summary>
  180.    ''' Analyzes a file and returns the problems (if any).
  181.    ''' </summary>
  182.    Public Function Analyze(ByVal MP3_File As IO.FileInfo) As List(Of String)
  183.  
  184.        Return Run_MP3VAL(MP3_File.FullName,
  185.                          Operation.Analyze,
  186.                          ControlChars.Quote & MP3_File.FullName & ControlChars.Quote)
  187.  
  188.    End Function
  189.  
  190.    ''' <summary>
  191.    ''' Try to Fix/Rebuild problems of a file,
  192.    ''' and returns a value indicating if file was fixed or not.
  193.    ''' </summary>
  194.    Public Function Fix(ByVal MP3_File As String,
  195.                        Optional ByVal Delete_Backup_File As Boolean = False,
  196.                        Optional ByVal Preserve_Datestamp As Boolean = True) As Boolean
  197.  
  198.        Return Run_MP3VAL(MP3_File,
  199.                          Operation.Fix,
  200.                          String.Format("-f {0} {1} ""{2}""",
  201.                                        If(Delete_Backup_File, "-nb", ""),
  202.                                        If(Preserve_Datestamp, "-t", ""),
  203.                                        MP3_File))
  204.  
  205.    End Function
  206.  
  207.    ''' <summary>
  208.    ''' Try to Fix/Rebuild problems of a file,
  209.    ''' and returns a value indicating if file was fixed or not.
  210.    ''' </summary>
  211.    Public Function Fix(ByVal MP3_File As IO.FileInfo,
  212.                        Optional ByVal Delete_Backup_File As Boolean = False,
  213.                        Optional ByVal Preserve_Datestamp As Boolean = True) As Boolean
  214.  
  215.        Return Run_MP3VAL(MP3_File.FullName,
  216.                          Operation.Fix,
  217.                          String.Format("-f {0} {1} ""{2}""",
  218.                                        If(Delete_Backup_File, "-nb", ""),
  219.                                        If(Preserve_Datestamp, "-t", ""),
  220.                                        MP3_File.FullName))
  221.  
  222.    End Function
  223.  
  224.    ''' <summary>
  225.    ''' Return the metadata ID types of a file.
  226.    ''' </summary>
  227.    Public Function Get_Tags(ByVal MP3_File As String) As String
  228.  
  229.        Return Run_MP3VAL(MP3_File,
  230.                          Operation.Get_Tags,
  231.                          ControlChars.Quote & MP3_File & ControlChars.Quote)
  232.  
  233.    End Function
  234.  
  235.    ''' <summary>
  236.    ''' Return the metadata ID types of a file.
  237.    ''' </summary>
  238.    Public Function Get_Tags(ByVal MP3_File As IO.FileInfo) As String
  239.  
  240.        Return Run_MP3VAL(MP3_File.FullName,
  241.                          Operation.Get_Tags,
  242.                          ControlChars.Quote & MP3_File.FullName & ControlChars.Quote)
  243.  
  244.    End Function
  245.  
  246. #End Region
  247.  
  248. #Region " Run Procedure "
  249.  
  250.    ''' <summary>
  251.    ''' Runs mp3val process.
  252.    ''' </summary>
  253.    Private Function Run_MP3VAL(ByVal MP3_File As String,
  254.                                ByVal operation As Operation,
  255.                                ByVal arguments As String) As Object
  256.  
  257.        If Me.CheckFileExist Then
  258.            FileExist(MP3_File)
  259.        End If
  260.  
  261.        With p.StartInfo
  262.            .FileName = Me.mp3val_location
  263.            .Arguments = arguments
  264.        End With
  265.  
  266.        Warnings.Clear() : Errors.Clear()
  267.  
  268.        p.Start()
  269.        RaiseEvent_Started(MP3_File, operation)
  270.        p.WaitForExit()
  271.  
  272.        StandardError = p.StandardError.ReadToEnd
  273.        StandardOutput = p.StandardOutput.ReadToEnd
  274.  
  275.        Info = Info_RegEx.Match(StandardOutput).Groups(1).Value.Trim
  276.  
  277.        For Each m As System.Text.RegularExpressions.Match In Warning_RegEx.Matches(StandardOutput)
  278.            Warnings.Add(m.Groups(1).Value)
  279.        Next m
  280.  
  281.        For Each e As String In StandardError.Split(Environment.NewLine)
  282.            If Not String.IsNullOrEmpty(e.Trim) Then
  283.                Errors.Add(e)
  284.            End If
  285.        Next e
  286.  
  287.        Select Case operation
  288.  
  289.            Case mp3val.Operation.Analyze
  290.                RaiseEvent_Exited(MP3_File,
  291.                                  operation.Analyze,
  292.                                  Info,
  293.                                  Warnings.Distinct.ToList,
  294.                                  Errors,
  295.                                  False)
  296.  
  297.                Return Warnings.Concat(Errors).Distinct.ToList
  298.  
  299.            Case mp3val.Operation.Fix
  300.                RaiseEvent_Exited(MP3_File,
  301.                                  operation.Fix,
  302.                                  Info,
  303.                                  Warnings.Distinct.ToList,
  304.                                  Errors,
  305.                                  Fixed_RegEx.IsMatch(StandardOutput))
  306.  
  307.                Return Fixed_RegEx.IsMatch(StandardOutput)
  308.  
  309.            Case mp3val.Operation.Get_Tags
  310.                RaiseEvent_Exited(MP3_File,
  311.                                  operation.Get_Tags,
  312.                                  Info,
  313.                                  Warnings.Distinct.ToList,
  314.                                  Errors,
  315.                                  False)
  316.  
  317.                If Not String.IsNullOrEmpty(Info) Then
  318.  
  319.                    Tags = Info.Split(",")(1).Trim
  320.  
  321.                    If Tags = "no tags" Then
  322.                        Return "No tags"
  323.                    Else
  324.                        Return Tags.Substring(1).Replace("+", ", ")
  325.                    End If
  326.  
  327.                Else
  328.  
  329.                    Return "Can't examine tag type."
  330.  
  331.                End If
  332.  
  333.            Case Else
  334.                Return Nothing
  335.  
  336.        End Select
  337.  
  338.    End Function
  339.  
  340. #End Region
  341.  
  342. #Region " Miscellaneous preocedures "
  343.  
  344.    ''' <summary>
  345.    ''' Checks if a file exists.
  346.    ''' </summary>
  347.    Private Sub FileExist(ByVal File As String)
  348.  
  349.        If Not IO.File.Exists(File) Then
  350.            Throw New Exception(String.Format("File doesn't exist: ""{0}""", File))
  351.            ' MessageBox.Show(String.Format("File doesn't exist: ""{0}""", File), "mp3val", MessageBoxButtons.OK, MessageBoxIcon.Error)
  352.        End If
  353.  
  354.    End Sub
  355.  
  356.    ''' <summary>
  357.    ''' Raises the Event Started
  358.    ''' </summary>
  359.    Private Sub RaiseEvent_Started(ByVal File As String,
  360.                                   ByVal Operation As Operation)
  361.  
  362.        With StartedArgs
  363.            .File = File
  364.            .Operation = Operation
  365.        End With
  366.  
  367.        RaiseEvent Started(p, StartedArgs)
  368.  
  369.    End Sub
  370.  
  371.    ''' <summary>
  372.    ''' Raises the Event Exited
  373.    ''' </summary>
  374.    Private Sub RaiseEvent_Exited(ByVal File As String,
  375.                                  ByVal Operation As Operation,
  376.                                  ByVal Info As String,
  377.                                  ByVal Warnings As List(Of String),
  378.                                  ByVal Errors As List(Of String),
  379.                                  ByVal IsFixed As Boolean)
  380.  
  381.        With ExitedArgs
  382.            .File = File
  383.            .Operation = Operation
  384.            .Info = Info
  385.            .Warnings = Warnings
  386.            .Errors = Errors
  387.            .FileIsFixed = IsFixed
  388.        End With
  389.  
  390.        RaiseEvent Exited(p, ExitedArgs)
  391.  
  392.    End Sub
  393.  
  394. #End Region
  395.  
  396. #Region " IDisposable "
  397.  
  398.      ''' <summary>
  399.      ''' Disposes the objects generated by this instance.
  400.      ''' </summary>
  401.      Public Sub Dispose() Implements IDisposable.Dispose
  402.          Dispose(True)
  403.          GC.SuppressFinalize(Me)
  404.      End Sub
  405.  
  406.      Protected Overridable Sub Dispose(IsDisposing As Boolean)
  407.  
  408.          Static IsBusy As Boolean ' To detect redundant calls.
  409.  
  410.          If Not IsBusy AndAlso IsDisposing Then
  411.  
  412.              p.Dispose()
  413.  
  414.          End If
  415.  
  416.          IsBusy = True
  417.  
  418.      End Sub
  419.  
  420.  #End Region
  421.  
  422. End Class
  423.  
  424. #End Region
8059  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets) en: 11 Noviembre 2013, 01:36 am
Una versión mejorada de mi ayudante para la aplicación CoreConverter... mejoré lo que pude el código y le añadi algunos eventos esenciales...

Un ejemplo de uso:

Código
  1.    Public Class Form1
  2.  
  3.        Private WithEvents _converter As New CoreConverter _
  4.                With {.CoreConverter_location = "C:\windows\system32\coreconverter.exe",
  5.                      .CheckFileExist = True}
  6.  
  7.        Private Sub Test() Handles MyBase.Shown
  8.  
  9.            ' Checks if CoreConverter executable is avaliable.
  10.            MsgBox(_converter.Is_Avaliable())
  11.  
  12.            ' Convert a file to MP3
  13.            _converter.Convert_To_MP3("C:\Input.wav", "C:\Output.mp3",
  14.                                      CoreConverter.Lame_Bitrate.kbps_320,
  15.                                      CoreConverter.Lame_Bitrate_Mode.cbr,
  16.                                      CoreConverter.Lame_Profile.SLOW,
  17.                                      CoreConverter.Lame_Quality.Q0_Maximum,
  18.                                      CoreConverter.Lame_Khz.Same_As_Source,
  19.                                      CoreConverter.Lame_Channels.auto,
  20.                                      {
  21.                                       CoreConverter.DSP_Effects.Delete_Output_File_on_Error,
  22.                                       CoreConverter.DSP_Effects.Recycle_Source_File_After_Conversion
  23.                                      },
  24.                                      False,
  25.                                      CoreConverter.Priority.normal)
  26.  
  27.            ' Convert a file to WAV
  28.            _converter.Convert_To_WAV_Uncompressed("C:\Input.mp3", "C:\Output.wav", _
  29.                                                   CoreConverter.WAV_Uncompressed_Bitrate.Same_As_Source, _
  30.                                                   CoreConverter.WAV_Uncompressed_Khz.Same_As_Source, _
  31.                                                   CoreConverter.WAV_Uncompressed_Channels.Same_As_Source, , False)
  32.  
  33.            ' Convert a file to WMA
  34.            _converter.Convert_To_WMA("C:\Input.mp3", "C:\Output.wma", _
  35.                                      CoreConverter.WMA_9_2_BitRates.Kbps_128, _
  36.                                      CoreConverter.WMA_9_2_Khz.Khz_44100, _
  37.                                      CoreConverter.WMA_9_2_Channels.stereo, , False)
  38.  
  39.        End Sub
  40.  
  41.        ' CoreConverter [Started]
  42.        Private Sub CoreConverter_Started(ByVal sender As Process, ByVal e As CoreConverter.StartedEventArgs) _
  43.        Handles _converter.Started
  44.  
  45.            ProgressBar1.Value = ProgressBar1.Minimum
  46.  
  47.            Dim sb As New System.Text.StringBuilder
  48.  
  49.            sb.AppendLine(String.Format("Started an ""{0}"" operation", e.Operation.ToString))
  50.            sb.AppendLine(String.Format("Input file is: ""{0}""", e.File))
  51.            sb.AppendLine(String.Format("CoreConverter process PID is: ""{0}""", CStr(sender.Id)))
  52.  
  53.            MessageBox.Show(sb.ToString, "CoreConverter", MessageBoxButtons.OK, MessageBoxIcon.Information)
  54.  
  55.        End Sub
  56.  
  57.        ' CoreConverter [Exited]
  58.        Private Sub CoreConverter_Exited(ByVal sender As Process, ByVal e As CoreConverter.ExitedEventArgs) _
  59.        Handles _converter.Exited
  60.  
  61.            Dim sb As New System.Text.StringBuilder
  62.  
  63.            sb.AppendLine(String.Format("Finished an ""{0}"" operation", e.Operation.ToString))
  64.            sb.AppendLine(String.Format("Input file is: ""{0}""", e.File))
  65.            sb.AppendLine(String.Format("CoreConverter process PID is: {0}", CStr(sender.Id)))
  66.  
  67.            If Not String.IsNullOrEmpty(e.InfoMessage) Then
  68.                sb.AppendLine(String.Format("Operation Information: {0}", e.InfoMessage))
  69.            End If
  70.  
  71.            If Not String.IsNullOrEmpty(e.ErrorMessage) Then
  72.                sb.AppendLine(String.Format("Error Information: {0}", e.ErrorMessage))
  73.            End If
  74.  
  75.            If Not String.IsNullOrEmpty(e.ElapsedTime) Then
  76.                sb.AppendLine(String.Format("Total elapsed time: {0}", e.ElapsedTime))
  77.            End If
  78.  
  79.            MessageBox.Show(sb.ToString, "CoreConverter", MessageBoxButtons.OK, MessageBoxIcon.Information)
  80.  
  81.        End Sub
  82.  
  83.        ' CoreConverter [Progress]
  84.        Sub CoreConverter_Progress(sender As Process, e As CoreConverter.ProgressEventArgs) _
  85.        Handles _converter.Progress
  86.  
  87.            ProgressBar1.Value = e.Percent
  88.  
  89.        End Sub
  90.  
  91.    End Class


El ayudante:

Código:
' [ CoreConverter Helper ]
'
' // By Elektro H@cker
'
' Instructions:

' 1. Add the "CoreConverter.exe" into the project,
'    together with dbPoweramp Effects and Codec folders.

Código
  1. #Region " CoreConverter Helper "
  2.  
  3. Public Class CoreConverter : Implements IDisposable
  4.  
  5. #Region " Variables, Properties, Enumerations "
  6.  
  7.    ''' <summary>
  8.    ''' Gets or sets CoreConverter.exe executable path.
  9.    ''' </summary>
  10.    Public Property CoreConverter_location As String = ".\CoreConverter.exe"
  11.  
  12.    ''' <summary>
  13.    ''' Indicates if should check that the file exist before realize an operation.
  14.    ''' If True, an exception would be launched if file does not exist.
  15.    ''' </summary>
  16.    Public Property CheckFileExist As Boolean = False
  17.  
  18.    ''' <summary>
  19.    ''' Stores the converter process progress
  20.    ''' </summary>
  21.    Private CurrentProgress As Integer = 0
  22.  
  23.    ''' <summary>
  24.    ''' Stores an information message of the realized operation (if any).
  25.    ''' </summary>
  26.    Private InfoMessage As String = Nothing
  27.  
  28.    ''' <summary>
  29.    ''' Stores an error message of the realized operation (if any).
  30.    ''' </summary>
  31.    Private ErrorMessage As String = Nothing
  32.  
  33.    ''' <summary>
  34.    ''' Stores the next converter process output character.
  35.    ''' </summary>
  36.    Private OutputCharacter As Char = Nothing
  37.  
  38.    ''' <summary>
  39.    ''' Stores the DSP Effects formatted string.
  40.    ''' </summary>
  41.    Private Effects As String = Nothing
  42.  
  43.    ''' <summary>
  44.    ''' Stores the total elapsed time of conversion.
  45.    ''' </summary>
  46.    Private ElapsedTime As String = Nothing
  47.  
  48.    ''' <summary>
  49.    ''' Stores additional information about the conversion.
  50.    ''' </summary>
  51.    Private ExtraInfo() As String = Nothing
  52.  
  53.    ''' <summary>
  54.    ''' Stores the StartedEventArgs Arguments.
  55.    ''' </summary>
  56.    Private StartedArgs As New StartedEventArgs
  57.  
  58.    ''' <summary>
  59.    ''' Stores the ExitedEventArgs Arguments.
  60.    ''' </summary>
  61.    Private ExitedArgs As New ExitedEventArgs
  62.  
  63.    ''' <summary>
  64.    ''' Stores the ProgressEventArgs Arguments.
  65.    ''' </summary>
  66.    Private ProgressArgs As New ProgressEventArgs
  67.  
  68.    ''' <summary>
  69.    ''' CoreConverter Type Of Operation.
  70.    ''' </summary>
  71.    Public Enum Operation
  72.        MP3_Conversion = 0
  73.        WAV_Conversion = 1
  74.        WMA_Conversion = 2
  75.    End Enum
  76.  
  77.    ''' <summary>
  78.    ''' Priority level of CoreConverter process.
  79.    ''' </summary>
  80.    Public Enum Priority
  81.        idle
  82.        low
  83.        normal
  84.        high
  85.    End Enum
  86.  
  87.    ''' <summary>
  88.    ''' DSP Effects.
  89.    ''' </summary>
  90.    Public Enum DSP_Effects
  91.        Delete_Output_File_on_Error ' Delete failed conversion (not deletes source file).
  92.        Delete_Source_File_After_Conversion ' Delete source file after conversion.
  93.        Recycle_Source_File_After_Conversion ' Send source file to recycle bin after conversion.
  94.        Karaoke_Remove_Voice ' Remove voice from file.
  95.        Karaoke_Remove_Instrument ' Remove instruments from file.
  96.        Reverse ' Reverse complete audio file.
  97.        Write_Silence ' Write silence at start of file.
  98.    End Enum
  99.  
  100.    ''' <summary>
  101.    ''' CoreConverter Process.
  102.    ''' </summary>
  103.    Private p As Process =
  104.        New Process With {.StartInfo =
  105.            New ProcessStartInfo With {
  106.                .CreateNoWindow = True, _
  107.                .UseShellExecute = False, _
  108.                .RedirectStandardError = True, _
  109.                .RedirectStandardOutput = True, _
  110.                .StandardErrorEncoding = System.Text.Encoding.Unicode, _
  111.                .StandardOutputEncoding = System.Text.Encoding.Unicode
  112.           }
  113.        }
  114.  
  115. #End Region
  116.  
  117. #Region " Events "
  118.  
  119.    ''' <summary>
  120.    ''' Event raised when CoreConverter operation progress changes.
  121.    ''' </summary>
  122.    Public Event Progress As EventHandler(Of ProgressEventArgs)
  123.    Public Class ProgressEventArgs : Inherits EventArgs
  124.        ''' <summary>
  125.        ''' Gets the CoreConverter operation percent done.
  126.        ''' </summary>
  127.        Public Property Percent As Integer
  128.    End Class
  129.  
  130.    ''' <summary>
  131.    ''' Event raised when CoreConverter process has started.
  132.    ''' </summary>
  133.    Public Event Started As EventHandler(Of StartedEventArgs)
  134.    Public Class StartedEventArgs : Inherits EventArgs
  135.        ''' <summary>
  136.        ''' Gets the file that was passed as argument to the process.
  137.        ''' </summary>
  138.        Public Property File As String
  139.        ''' <summary>
  140.        ''' Gets the type of operation to realize.
  141.        ''' </summary>
  142.        Public Property Operation As Operation
  143.    End Class
  144.  
  145.    ''' <summary>
  146.    ''' Event raised when CoreConverter process has exited.
  147.    ''' </summary>
  148.    Public Event Exited As EventHandler(Of ExitedEventArgs)
  149.    Public Class ExitedEventArgs : Inherits EventArgs
  150.        ''' <summary>
  151.        ''' Gets the file that was passed as argument to the process.
  152.        ''' </summary>
  153.        Public Property File As String
  154.        ''' <summary>
  155.        ''' Gets the type of operation to realize.
  156.        ''' </summary>
  157.        Public Property Operation As Operation
  158.        ''' <summary>
  159.        ''' Gets an information message of the realized operation.
  160.        ''' </summary>
  161.        Public Property InfoMessage As String
  162.        ''' <summary>
  163.        ''' Gets an error message of the realized operation (if any).
  164.        ''' </summary>
  165.        Public Property ErrorMessage As String
  166.        ''' <summary>
  167.        ''' Gets the total elapsed time of the operation.
  168.        ''' </summary>
  169.        Public Property ElapsedTime As String
  170.    End Class
  171.  
  172. #End Region
  173.  
  174. #Region " Codec Enumerations "
  175.  
  176. #Region " MP3 Lame "
  177.  
  178.    Public Enum Lame_Bitrate
  179.        kbps_8 = 8
  180.        kbps_16 = 16
  181.        kbps_24 = 24
  182.        kbps_32 = 32
  183.        kbps_40 = 40
  184.        kbps_48 = 48
  185.        kbps_56 = 56
  186.        kbps_64 = 64
  187.        kbps_80 = 80
  188.        kbps_96 = 96
  189.        kbps_112 = 112
  190.        kbps_128 = 128
  191.        kbps_144 = 144
  192.        kbps_160 = 160
  193.        kbps_192 = 192
  194.        kbps_224 = 224
  195.        kbps_256 = 256
  196.        kbps_320 = 320
  197.    End Enum
  198.  
  199.    Public Enum Lame_Bitrate_Mode
  200.        cbr
  201.        abr
  202.    End Enum
  203.  
  204.    Public Enum Lame_Profile
  205.        NORMAL
  206.        FAST
  207.        SLOW
  208.    End Enum
  209.  
  210.    Public Enum Lame_Quality
  211.        Q0_Maximum = 0
  212.        Q1 = 1
  213.        Q2 = 2
  214.        Q3 = 3
  215.        Q4 = 4
  216.        Q5 = 5
  217.        Q6 = 6
  218.        Q7 = 7
  219.        Q8 = 8
  220.        Q9_Minimum = 9
  221.    End Enum
  222.  
  223.    Public Enum Lame_Khz
  224.        Same_As_Source
  225.        khz_8000 = 8000
  226.        khz_11025 = 11025
  227.        khz_12000 = 12000
  228.        khz_16000 = 16000
  229.        khz_22050 = 22050
  230.        khz_24000 = 24000
  231.        khz_32000 = 32000
  232.        khz_44100 = 44100
  233.        khz_48000 = 48000
  234.    End Enum
  235.  
  236.    Public Enum Lame_Channels
  237.        auto
  238.        mono
  239.        stereo
  240.        joint_stereo
  241.        forced_joint_stereo
  242.        forced_stereo
  243.        dual_channels
  244.    End Enum
  245.  
  246. #End Region
  247.  
  248. #Region " WAV Uncompressed "
  249.  
  250.    Public Enum WAV_Uncompressed_Bitrate
  251.        Same_As_Source
  252.        bits_8 = 8
  253.        bits_16 = 16
  254.        bits_24 = 24
  255.        bits_32 = 32
  256.    End Enum
  257.  
  258.    Public Enum WAV_Uncompressed_Khz
  259.        Same_As_Source
  260.        khz_8000 = 8000
  261.        khz_11025 = 11025
  262.        khz_12000 = 12000
  263.        khz_16000 = 16000
  264.        khz_22050 = 22050
  265.        khz_24000 = 24000
  266.        khz_32000 = 32000
  267.        khz_44100 = 44100
  268.        khz_48000 = 48000
  269.        khz_96000 = 96000
  270.        khz_192000 = 192000
  271.    End Enum
  272.  
  273.    Public Enum WAV_Uncompressed_Channels
  274.        Same_As_Source
  275.        Channels_1_Mono = 1
  276.        Channels_2_Stereo = 2
  277.        Channels_3 = 3
  278.        Channels_4_Quadraphonic = 4
  279.        Channels_5_Surround = 5
  280.        Channels_6_Surround_DVD = 6
  281.        Channels_7 = 7
  282.        Channels_8_Theater = 8
  283.    End Enum
  284.  
  285. #End Region
  286.  
  287. #Region " WMA 9.2 "
  288.  
  289.    Public Enum WMA_9_2_BitRates
  290.        Kbps_12 = 12
  291.        Kbps_16 = 16
  292.        Kbps_20 = 20
  293.        Kbps_22 = 22
  294.        Kbps_24 = 24
  295.        Kbps_32 = 32
  296.        Kbps_40 = 40
  297.        Kbps_48 = 48
  298.        Kbps_64 = 64
  299.        Kbps_80 = 80
  300.        Kbps_96 = 96
  301.        Kbps_128 = 128
  302.        Kbps_160 = 160
  303.        Kbps_192 = 192
  304.        Kbps_256 = 256
  305.        Kbps_320 = 320
  306.    End Enum
  307.  
  308.    Enum WMA_9_2_Khz
  309.        Khz_8000 = 8
  310.        Khz_16000 = 16
  311.        Khz_22050 = 22
  312.        Khz_32000 = 32
  313.        Khz_44100 = 44
  314.        Khz_48000 = 48
  315.    End Enum
  316.  
  317.    Enum WMA_9_2_Channels
  318.        mono
  319.        stereo
  320.    End Enum
  321.  
  322. #End Region
  323.  
  324. #End Region
  325.  
  326. #Region " CoreConverter Procedures "
  327.  
  328.    ''' <summary>
  329.    ''' Checks if CoreConverter process is avaliable.
  330.    ''' </summary>
  331.    Public Function Is_Avaliable() As Boolean
  332.        Return IO.File.Exists(Me.CoreConverter_location)
  333.    End Function
  334.  
  335.    ''' <summary>
  336.    ''' Converts a file to MP3 using Lame codec.
  337.    ''' </summary>
  338.    Public Sub Convert_To_MP3(ByVal In_File As String, _
  339.                              ByVal Out_File As String, _
  340.                              ByVal Bitrate As Lame_Bitrate, _
  341.                              ByVal Bitrate_Mode As Lame_Bitrate_Mode, _
  342.                              ByVal Encoding_Profile As Lame_Profile, _
  343.                              ByVal Quality As Lame_Quality, _
  344.                              ByVal Khz As Lame_Khz, _
  345.                              ByVal Channels As Lame_Channels, _
  346.                              Optional ByVal DSP_Effects() As DSP_Effects = Nothing, _
  347.                              Optional ByVal Update_Tag As Boolean = True, _
  348.                              Optional ByVal Priority As Priority = Priority.normal, _
  349.                              Optional ByVal Processor As Short = 1)
  350.  
  351.        Get_Effects(DSP_Effects)
  352.  
  353.        Set_Main_Arguments("mp3 (Lame)",
  354.                           In_File,
  355.                           Out_File,
  356.                           If(Not Update_Tag, "-noidtag", ""),
  357.                           Effects,
  358.                           Priority.ToString,
  359.                           Processor.ToString)
  360.  
  361.        p.StartInfo.Arguments &= _
  362.        String.Format("-b {0} --{1} -encoding=""{2}"" -freq=""{3}"" -channels=""{4}"" --noreplaygain --extracli=""-q {5}""", _
  363.                      CInt(Bitrate), _
  364.                      Bitrate_Mode.ToString, _
  365.                      Encoding_Profile.ToString, _
  366.                      If(Khz = Lame_Khz.Same_As_Source, "", CInt(Khz)), _
  367.                      If(Channels = Lame_Channels.auto, "", Channels), _
  368.                      CInt(Quality))
  369.  
  370.        Run_CoreConverter(In_File, Operation.MP3_Conversion)
  371.  
  372.    End Sub
  373.  
  374.    ''' <summary>
  375.    ''' Converts a file to Uncompressed WAV.
  376.    ''' </summary>
  377.    Public Sub Convert_To_WAV_Uncompressed(ByVal In_File As String, _
  378.                                           ByVal Out_File As String, _
  379.                                           ByVal Bitrate As WAV_Uncompressed_Bitrate, _
  380.                                           ByVal Khz As WAV_Uncompressed_Khz, _
  381.                                           ByVal Channels As WAV_Uncompressed_Channels, _
  382.                                           Optional ByVal DSP_Effects() As DSP_Effects = Nothing, _
  383.                                           Optional ByVal Update_Tag As Boolean = True, _
  384.                                           Optional ByVal Priority As Priority = Priority.normal, _
  385.                                           Optional ByVal Processor As Short = 1)
  386.  
  387.        Get_Effects(DSP_Effects)
  388.  
  389.        Set_Main_Arguments("Wave",
  390.                           In_File,
  391.                           Out_File,
  392.                           If(Not Update_Tag, "-noidtag", ""),
  393.                           Effects,
  394.                           Priority.ToString,
  395.                           Processor.ToString)
  396.  
  397.        p.StartInfo.Arguments &= _
  398.        String.Format("-compression=""PCM"" -bits=""{0}"" -freq=""{1}"" -channels=""{2}""", _
  399.                      If(Bitrate = WAV_Uncompressed_Bitrate.Same_As_Source, "", CInt(Bitrate)), _
  400.                      If(Khz = WAV_Uncompressed_Khz.Same_As_Source, "", CInt(Khz)), _
  401.                      If(Channels = WAV_Uncompressed_Channels.Same_As_Source, "", CInt(Channels)))
  402.  
  403.        Run_CoreConverter(In_File, Operation.WAV_Conversion)
  404.  
  405.    End Sub
  406.  
  407.    ''' <summary>
  408.    ''' Converts a file to WMA v9.2
  409.    ''' </summary>
  410.    Public Sub Convert_To_WMA(ByVal In_File As String, _
  411.                              ByVal Out_File As String, _
  412.                              ByVal Bitrate As WMA_9_2_BitRates, _
  413.                              ByVal Khz As WMA_9_2_Khz, _
  414.                              ByVal Channels As WMA_9_2_Channels, _
  415.                              Optional ByVal DSP_Effects() As DSP_Effects = Nothing, _
  416.                              Optional ByVal Update_Tag As Boolean = True, _
  417.                              Optional ByVal Priority As Priority = Priority.normal, _
  418.                              Optional ByVal Processor As Short = 1)
  419.  
  420.        Get_Effects(DSP_Effects)
  421.  
  422.        Set_Main_Arguments("Windows Media Audio 10",
  423.                           In_File,
  424.                           Out_File,
  425.                           If(Not Update_Tag, "-noidtag", ""),
  426.                           Effects,
  427.                           Priority.ToString,
  428.                           Processor.ToString)
  429.  
  430.        p.StartInfo.Arguments &= _
  431.        String.Format("-codec=""Windows Media Audio 9.2"" -settings=""{0} kbps, {1} kHz, {2} CBR""",
  432.                      CInt(Bitrate), _
  433.                      CInt(Khz), _
  434.                      Channels.ToString)
  435.  
  436.        Run_CoreConverter(In_File, Operation.WMA_Conversion)
  437.  
  438.    End Sub
  439.  
  440. #End Region
  441.  
  442. #Region " Run Procedure "
  443.  
  444.    ''' <summary>
  445.    ''' Runs a specific operation of CoreConverter.
  446.    ''' </summary>
  447.    Private Sub Run_CoreConverter(ByVal file As String,
  448.                                  ByVal operation As Operation)
  449.  
  450.        If Me.CheckFileExist Then
  451.            FileExist(file)
  452.        End If
  453.  
  454.        CurrentProgress = 0
  455.  
  456.        p.StartInfo.FileName = Me.CoreConverter_location
  457.        p.Start()
  458.  
  459.        With StartedArgs
  460.            .File = file
  461.            .Operation = operation
  462.        End With
  463.  
  464.        RaiseEvent Started(p, StartedArgs)
  465.  
  466.        While Not p.HasExited
  467.  
  468.            OutputCharacter = ChrW(p.StandardOutput.Read)
  469.  
  470.            If OutputCharacter = "*" Then
  471.                ProgressArgs.Percent = CInt((Threading.Interlocked.Increment(CurrentProgress) / 59) * 100)
  472.                RaiseEvent Progress(p, ProgressArgs)
  473.            End If
  474.  
  475.            If CurrentProgress = 59 Then
  476.                ' I store the last line(s) because it has interesting information:
  477.                ' Example Output: "Conversion completed in 30 seconds x44 realtime encoding"
  478.                InfoMessage = p.StandardOutput.ReadToEnd.Trim
  479.            End If
  480.  
  481.        End While
  482.  
  483.        ' Stores the Error Message (If any)
  484.        ErrorMessage = p.StandardError.ReadToEnd.Trim
  485.  
  486.        If Not String.IsNullOrEmpty(InfoMessage) Then
  487.  
  488.            ' Stores additional information
  489.            ExtraInfo = InfoMessage.Split(Environment.NewLine)
  490.  
  491.            Select Case ExtraInfo.Length
  492.  
  493.                Case 1
  494.                    ElapsedTime = ExtraInfo.Last.Split()(3) & " " & ExtraInfo.Last.Split()(4) ' Example: "50,2 seconds"
  495.  
  496.                Case 2
  497.                    ElapsedTime = ExtraInfo.Last.Split()(4) & " " & ExtraInfo.Last.Split()(5) ' Example: "50,2 seconds"
  498.  
  499.                Case Is < 1, Is > 2
  500.                    Throw New Exception("Unmanaged Process Output Length")
  501.  
  502.            End Select
  503.  
  504.        End If
  505.  
  506.        With ExitedArgs
  507.            .File = file
  508.            .Operation = operation
  509.            .InfoMessage = InfoMessage
  510.            .ErrorMessage = ErrorMessage
  511.            .ElapsedTime = ElapsedTime
  512.        End With
  513.  
  514.        RaiseEvent Exited(p, ExitedArgs)
  515.  
  516.        ' CoreConverter.Close()
  517.  
  518.    End Sub
  519.  
  520. #End Region
  521.  
  522. #Region " Miscellaneous procedures "
  523.  
  524.    ''' <summary>
  525.    ''' Checks if a file exists.
  526.    ''' </summary>
  527.    Private Sub FileExist(ByVal File As String)
  528.  
  529.        If Not IO.File.Exists(File) Then
  530.            ' Throw New Exception("File doesn't exist: " & File)
  531.            MessageBox.Show("File doesn't exist: " & File, "CoreConverter", MessageBoxButtons.OK, MessageBoxIcon.Error)
  532.        End If
  533.  
  534.    End Sub
  535.  
  536.    ''' <summary>
  537.    ''' Sets the static arguments of CoreConverter process.
  538.    ''' </summary>
  539.    Private Sub Set_Main_Arguments(ByVal Codec_Name As String, _
  540.                                   ByVal In_File As String, _
  541.                                   ByVal Out_File As String, _
  542.                                   ByVal Update_Tag As String, _
  543.                                   ByVal Effects As String, _
  544.                                   ByVal Priority As String, _
  545.                                   ByVal Processor As String)
  546.  
  547.        p.StartInfo.Arguments = _
  548.        String.Format("-infile=""{0}"" -outfile=""{1}"" -convert_to=""{2}"" {3} {4} -priority=""{5}"" -processor=""{6}"" ",
  549.                      In_File,
  550.                      Out_File,
  551.                      Codec_Name,
  552.                      Update_Tag,
  553.                      Effects,
  554.                      Priority,
  555.                      Processor)
  556.  
  557.    End Sub
  558.  
  559.    ''' <summary>
  560.    ''' Join all DSP Effects and returns a formatted string.
  561.    ''' </summary>
  562.    Private Function Get_Effects(ByVal DSP_Effects() As DSP_Effects) As String
  563.  
  564.        If DSP_Effects Is Nothing Then
  565.  
  566.            Return Nothing
  567.  
  568.        Else
  569.  
  570.            For Effect As Integer = 0 To DSP_Effects.Length - 1
  571.                Effects &= String.Format(" -dspeffect{0}={1}", _
  572.                                         Effect + 1, _
  573.                                         Format_DSP_Effect(DSP_Effects(Effect).ToString))
  574.            Next Effect
  575.  
  576.            Return Effects
  577.  
  578.        End If
  579.  
  580.    End Function
  581.  
  582.    ''' <summary>
  583.    ''' Returns a formatted string of a single DSP Effects.
  584.    ''' </summary>
  585.    Private Shared Function Format_DSP_Effect(ByVal Effect As String)
  586.  
  587.        Select Case Effect
  588.  
  589.            Case "Reverse"
  590.                Return """Reverse"""
  591.  
  592.            Case "Delete_Output_File_on_Error"
  593.                Return """Delete Destination File on Error="""
  594.  
  595.            Case "Recycle_Source_File_After_Conversion"
  596.                Return """Delete Source File=-recycle"""
  597.  
  598.            Case "Delete_Source_File_After_Conversion"
  599.                Return """Delete Source File="""
  600.  
  601.            Case "Karaoke_Remove_Voice"
  602.                Return """Karaoke (Voice_ Instrument Removal)="""
  603.  
  604.            Case "Karaoke_Remove_Instrument"
  605.                Return """Karaoke (Voice_ Instrument Removal)=-i"""
  606.  
  607.            Case "Write_Silence"
  608.                Return """Write Silence=-lengthms={qt}2000{qt}""" ' 2 seconds
  609.  
  610.            Case Else
  611.                Return String.Empty
  612.  
  613.        End Select
  614.  
  615.    End Function
  616.  
  617. #End Region
  618.  
  619. #Region " IDisposable "
  620.  
  621.      ''' <summary>
  622.      ''' Disposes the objects generated by this instance.
  623.      ''' </summary>
  624.      Public Sub Dispose() Implements IDisposable.Dispose
  625.          Dispose(True)
  626.          GC.SuppressFinalize(Me)
  627.      End Sub
  628.  
  629.      Protected Overridable Sub Dispose(IsDisposing As Boolean)
  630.  
  631.          Static IsBusy As Boolean ' To detect redundant calls.
  632.  
  633.          If Not IsBusy AndAlso IsDisposing Then
  634.  
  635.              p.Dispose()
  636.  
  637.          End If
  638.  
  639.          IsBusy = True
  640.  
  641.      End Sub
  642.  
  643.  #End Region
  644.  
  645. End Class
  646.  
  647. #End Region
8060  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets) en: 11 Noviembre 2013, 01:34 am
Una versión mejorada de mi ayudante para la aplicación mp3gain... mejoré lo que pude el código y le añadi algunos eventos esenciales...

Un ejemplo de uso:

Código
  1.    Public Class Form1
  2.  
  3.        Private WithEvents _mp3gain As New mp3gain _
  4.                With {.mp3gain_location = "C:\windows\system32\mp3gain.exe",
  5.                      .CheckFileExist = True}
  6.  
  7.        Private Sub Test() Handles MyBase.Shown
  8.  
  9.            ' Checks if mp3gain executable is avaliable.
  10.            MsgBox(_mp3gain.Is_Avaliable())
  11.  
  12.            ' Checks if file contains APEv2 mp3gain tag
  13.            MsgBox(_mp3gain.File_Has_MP3Gain_Tag("C:\File.mp3"))
  14.  
  15.            ' Set the global volume Gain of file to "89" db (In a scale of "0-100"),
  16.            ' and preserve the datetime of file.
  17.            _mp3gain.Set_Gain("C:\File.mp3", 89, True)
  18.  
  19.            ' Apply a volume change of +5 db,
  20.            ' in the curent global volume gain of file.
  21.            _mp3gain.Apply_Gain("C:\File.mp3", +5)
  22.  
  23.            ' Apply a volume change of -5 db,
  24.            ' in the curent global volume gain of file.
  25.            _mp3gain.Apply_Gain("C:\File.mp3", -5)
  26.  
  27.            ' Apply a volume change of +10 db,
  28.            ' in the curent volume gain of the Left channel of an Stereo file.
  29.            _mp3gain.Apply_Channel_Gain("C:\File.mp3", mp3gain.Channel.Left, +10)
  30.  
  31.            ' Apply a volume change of -10 db,
  32.            ' in the curent volume gain of the Right channel of an Stereo file.
  33.            _mp3gain.Apply_Channel_Gain("C:\File.mp3", mp3gain.Channel.Right, -10)
  34.  
  35.            ' Undos all volume gain changes made in file.
  36.            _mp3gain.Undo_Gain("C:\File.mp3")
  37.  
  38.        End Sub
  39.  
  40.        ' mp3gain [Started]
  41.        Private Sub mp3gain_Started(ByVal sender As Process, ByVal e As mp3gain.StartedEventArgs) _
  42.        Handles _mp3gain.Started
  43.  
  44.            ProgressBar1.Value = ProgressBar1.Minimum
  45.  
  46.            Dim sb As New System.Text.StringBuilder
  47.  
  48.            sb.AppendLine(String.Format("Started an ""{0}"" operation", e.Operation.ToString))
  49.            sb.AppendLine(String.Format("Input file is: ""{0}""", e.File))
  50.            sb.AppendLine(String.Format("mp3gain process PID is: ""{0}""", CStr(sender.Id)))
  51.  
  52.            MessageBox.Show(sb.ToString, "mp3gain", MessageBoxButtons.OK, MessageBoxIcon.Information)
  53.  
  54.        End Sub
  55.  
  56.        ' mp3gain [Exited]
  57.        Private Sub mp3gain_Exited(ByVal sender As Process, ByVal e As mp3gain.ExitedEventArgs) _
  58.        Handles _mp3gain.Exited
  59.  
  60.            Dim sb As New System.Text.StringBuilder
  61.  
  62.            If e.Operation <> mp3gain.Operation.Check_Tag Then
  63.  
  64.                sb.AppendLine(String.Format("Finished an ""{0}"" operation", e.Operation.ToString))
  65.                sb.AppendLine(String.Format("Input file is: ""{0}""", e.File))
  66.                sb.AppendLine(String.Format("mp3gain process PID is: {0}", CStr(sender.Id)))
  67.  
  68.                If Not String.IsNullOrEmpty(e.InfoMessage) Then
  69.                    sb.AppendLine(String.Format("Operation Information: {0}", e.InfoMessage))
  70.                End If
  71.  
  72.                If Not String.IsNullOrEmpty(e.ErrorMessage) Then
  73.                    sb.AppendLine(String.Format("Error Information: {0}", e.ErrorMessage))
  74.                End If
  75.  
  76.                If e.db <> 0 Then
  77.                    sb.AppendLine(String.Format("Volume gain change: {0}", CStr(e.db)))
  78.                End If
  79.  
  80.                MessageBox.Show(sb.ToString, "mp3gain", MessageBoxButtons.OK, MessageBoxIcon.Information)
  81.  
  82.            End If
  83.  
  84.        End Sub
  85.  
  86.        ' mp3gain [Progress]
  87.        Sub mp3gain_Progress(sender As Process, e As mp3gain.ProgressEventArgs) _
  88.        Handles _mp3gain.Progress
  89.  
  90.            ProgressBar1.Value = e.Percent
  91.  
  92.        End Sub
  93.  
  94.    End Class

El ayudante:

Código:
' [ mp3gain Helper ]
'
' // By Elektro H@cker
'
' Instructions:
' 1. Add the "mp3gain.exe" into the project.

Código
  1. #region " mp3gain Helper "
  2.  
  3. Public Class mp3gain : Implements IDisposable
  4.  
  5. #Region " CommandLine parametter legend "
  6.  
  7.    ' /c   - Ignore clipping warning when applying gain.
  8.    ' /d   - Set global gain.
  9.    ' /e   - Skip Album analysis, even if multiple files listed.
  10.    ' /g   - apply gain
  11.    ' /p   - Preserve original file timestamp.
  12.    ' /r   - apply Track gain automatically (all files set to equal loudness)
  13.    ' /t   - Writes modified data to temp file, then deletes original instead of modifying bytes in original file.
  14.    ' /u   - Undo changes made (based on stored APEv2 mp3gain tag info).
  15.    ' /s c - Check stored APEv2 mp3gain tag info.
  16.  
  17. #End Region
  18.  
  19. #Region " Variables, Properties, Enumerations "
  20.  
  21.    ''' <summary>
  22.    ''' Gets or sets the mp3gain.exe executable path.
  23.    ''' </summary>
  24.    Public Property mp3gain_location As String = ".\mp3gain.exe"
  25.  
  26.    ''' <summary>
  27.    ''' Indicates if should check that the file exist before realize an operation.
  28.    ''' If True, an exception would be launched if file does not exist.
  29.    ''' </summary>
  30.    Public Property CheckFileExist As Boolean = False
  31.  
  32.    ''' <summary>
  33.    ''' Sets a Flag to indicate if file has APEv2 mp3gain tag or not.
  34.    ''' </summary>
  35.    Private HasTag As Boolean = False
  36.  
  37.    ''' <summary>
  38.    ''' Stores the StandardOutput.
  39.    ''' </summary>
  40.    Private Output As String() = Nothing
  41.  
  42.    ''' <summary>
  43.    ''' Stores an information message of the realized operation (if any).
  44.    ''' </summary>
  45.    Private InfoMessage As String = String.Empty
  46.  
  47.    ''' <summary>
  48.    ''' Stores an error message of the realized operation (if any).
  49.    ''' </summary>
  50.    Private ErrorMessage As String = String.Empty
  51.  
  52.    ''' <summary>
  53.    ''' Stores the volume gain level change applied to file (if any).
  54.    ''' </summary>
  55.    Private db As Integer = 0
  56.  
  57.    ''' <summary>
  58.    ''' Gets some information about the file.
  59.    ''' </summary>
  60.    Private db_RegEx As New System.Text.RegularExpressions.Regex("Applying.+change of (.*) to",
  61.                            System.Text.RegularExpressions.RegexOptions.None)
  62.  
  63.    ''' <summary>
  64.    ''' Process to realize an operation,
  65.    ''' for files that already contains APEv2 mp3gain tag.
  66.    ''' Also is used to realize a single TagCheck operation.
  67.    ''' </summary>
  68.    Private Process_For_Tag As Process =
  69.        New Process With {.StartInfo =
  70.            New ProcessStartInfo With {
  71.                .CreateNoWindow = True,
  72.                .UseShellExecute = False,
  73.                .RedirectStandardError = False,
  74.                .RedirectStandardOutput = True
  75.           }
  76.        }
  77.  
  78.    ''' <summary>
  79.    ''' Process to realize an operation,
  80.    ''' for files that does not contains mp3gain Tag.
  81.    ''' </summary>
  82.    Private Process_For_NonTag As Process =
  83.        New Process With {.StartInfo =
  84.            New ProcessStartInfo With {
  85.                .CreateNoWindow = True,
  86.                .UseShellExecute = False,
  87.                .RedirectStandardError = True,
  88.                .RedirectStandardOutput = True
  89.           }
  90.        }
  91.  
  92.    ''' <summary>
  93.    ''' Stores the StartedEventArgs Arguments.
  94.    ''' </summary>
  95.    Private StartedArgs As New StartedEventArgs
  96.  
  97.    ''' <summary>
  98.    ''' Stores the ExitedEventArgs Arguments.
  99.    ''' </summary>
  100.    Private ExitedArgs As New ExitedEventArgs
  101.  
  102.    ''' <summary>
  103.    ''' Stores the ProgressEventArgs Arguments.
  104.    ''' </summary>
  105.    Private ProgressArgs As New ProgressEventArgs
  106.  
  107.    ''' <summary>
  108.    ''' File Stereo Channel.
  109.    ''' </summary>
  110.    Public Enum Channel As Short
  111.        Left = 0  ' /l 0
  112.        Right = 1 ' /l 1
  113.    End Enum
  114.  
  115.    ''' <summary>
  116.    ''' MP3Gain Type Of Operation.
  117.    ''' </summary>
  118.    Public Enum Operation
  119.        Check_Tag = 0
  120.        Apply_Gain = 1
  121.        Apply_Channel_Gain = 2
  122.        Set_Gain = 3
  123.        Undo_Gain = 4
  124.    End Enum
  125.  
  126. #End Region
  127.  
  128. #Region " Events "
  129.  
  130.    ''' <summary>
  131.    ''' Event raised when the process has started.
  132.    ''' </summary>
  133.    Public Event Started As EventHandler(Of StartedEventArgs)
  134.    Public Class StartedEventArgs : Inherits EventArgs
  135.        ''' <summary>
  136.        ''' Gets the file that was passed as argument to the process.
  137.        ''' </summary>
  138.        Public Property File As String
  139.        ''' <summary>
  140.        ''' Gets the type of operation to realize.
  141.        ''' </summary>
  142.        Public Property Operation As Operation
  143.    End Class
  144.  
  145.    ''' <summary>
  146.    ''' Event raised when the process has exited.
  147.    ''' </summary>
  148.    Public Event Exited As EventHandler(Of ExitedEventArgs)
  149.    Public Class ExitedEventArgs : Inherits EventArgs
  150.        ''' <summary>
  151.        ''' Gets the file that was passed as argument to the process.
  152.        ''' </summary>
  153.        Public Property File As String
  154.        ''' <summary>
  155.        ''' Gets the type of operation to realize.
  156.        ''' </summary>
  157.        Public Property Operation As Operation
  158.        ''' <summary>
  159.        ''' Gets the information message of the realized operation (if any).
  160.        ''' </summary>
  161.        Public Property InfoMessage As String
  162.        ''' <summary>
  163.        ''' Gets the error message of the realized operation (if any).
  164.        ''' </summary>
  165.        Public Property ErrorMessage As String
  166.        ''' <summary>
  167.        ''' Gets the volume gain level change applied to file (if any).
  168.        ''' </summary>
  169.        Public Property db As Integer
  170.    End Class
  171.  
  172.    ''' <summary>
  173.    ''' Event raised when the process progress changes.
  174.    ''' </summary>
  175.    Public Event Progress As EventHandler(Of ProgressEventArgs)
  176.    Public Class ProgressEventArgs : Inherits EventArgs
  177.        ''' <summary>
  178.        ''' Gets the process operation percent done.
  179.        ''' </summary>
  180.        Public Property Percent As Integer
  181.    End Class
  182.  
  183. #End Region
  184.  
  185. #Region " MP3Gain Procedures "
  186.  
  187.    ''' <summary>
  188.    ''' Checks if mp3gain.exe process is avaliable.
  189.    ''' </summary>
  190.    Public Function Is_Avaliable() As Boolean
  191.        Return IO.File.Exists(Me.mp3gain_location)
  192.    End Function
  193.  
  194.    ''' <summary>
  195.    ''' Checks if APEv2 mp3gain tag exists in file.
  196.    ''' </summary>
  197.    Public Function File_Has_MP3Gain_Tag(ByVal MP3_File As String) As Boolean
  198.  
  199.        Run_MP3Gain(MP3_File,
  200.                    Operation.Check_Tag,
  201.                    String.Format("/s c ""{0}""", MP3_File),
  202.                    True)
  203.  
  204.        Return HasTag
  205.  
  206.    End Function
  207.  
  208.    ''' <summary>
  209.    ''' Set the global volume gain of file.
  210.    ''' </summary>
  211.    Public Sub Set_Gain(ByVal MP3_File As String,
  212.                        ByVal Gain As Integer,
  213.                        Optional ByVal Preserve_Datestamp As Boolean = True)
  214.  
  215.        File_Has_MP3Gain_Tag(MP3_File)
  216.  
  217.        Run_MP3Gain(MP3_File,
  218.                    Operation.Set_Gain,
  219.                    String.Format("/c /e /r /t {1} /d {2} ""{0}""",
  220.                                  MP3_File,
  221.                                  If(Preserve_Datestamp, "/p", ""),
  222.                                  If(Gain < 0, Gain + 89.0, Gain - 89.0)),
  223.                    False)
  224.  
  225.    End Sub
  226.  
  227.    ''' <summary>
  228.    ''' Apply a volume gain change to file.
  229.    ''' </summary>
  230.    Public Sub Apply_Gain(ByVal MP3_File As String,
  231.                          ByVal Gain As Integer,
  232.                          Optional ByVal Preserve_Datestamp As Boolean = True)
  233.  
  234.        File_Has_MP3Gain_Tag(MP3_File)
  235.  
  236.        Run_MP3Gain(MP3_File,
  237.                    Operation.Apply_Gain,
  238.                    String.Format("/c /e /r /t {1} /g {2} ""{0}""",
  239.                                  MP3_File,
  240.                                  If(Preserve_Datestamp, "/p", ""),
  241.                                  Gain),
  242.                    False)
  243.  
  244.    End Sub
  245.  
  246.    ''' <summary>
  247.    ''' Apply a volume gain change to file only in left or right channel.
  248.    ''' Only works for Stereo MP3 files.
  249.    ''' </summary>
  250.    Public Sub Apply_Channel_Gain(ByVal MP3_File As String,
  251.                                  ByVal Channel As Channel,
  252.                                  ByVal Gain As Integer,
  253.                                  Optional ByVal Preserve_Datestamp As Boolean = True)
  254.  
  255.        File_Has_MP3Gain_Tag(MP3_File)
  256.  
  257.        Run_MP3Gain(MP3_File,
  258.                    Operation.Apply_Channel_Gain,
  259.                    String.Format("/c /e /r /l {2} {3} ""{0}""",
  260.                                  MP3_File,
  261.                                  If(Preserve_Datestamp, "/p", ""),
  262.                                  If(Channel = Channel.Left, 0, 1),
  263.                                  Gain),
  264.                    False)
  265.  
  266.    End Sub
  267.  
  268.    ''' <summary>
  269.    ''' Undos all mp3gain volume changes made in a file,
  270.    ''' based on stored APEv2 mp3gain tag info.
  271.    ''' </summary>
  272.    Public Sub Undo_Gain(ByVal MP3_File As String,
  273.                         Optional ByVal Preserve_Datestamp As Boolean = True)
  274.  
  275.        File_Has_MP3Gain_Tag(MP3_File)
  276.  
  277.        Run_MP3Gain(MP3_File,
  278.                    Operation.Undo_Gain,
  279.                    String.Format("/c /t {1} /u ""{0}""",
  280.                                  MP3_File,
  281.                                  If(Preserve_Datestamp, "/p", "")),
  282.                    False)
  283.  
  284.    End Sub
  285.  
  286. #End Region
  287.  
  288. #Region " Run Procedures "
  289.  
  290.    ''' <summary>
  291.    ''' Run MP3Gain process.
  292.    ''' </summary>
  293.    Private Sub Run_MP3Gain(ByVal MP3_File As String,
  294.                            ByVal operation As Operation,
  295.                            ByVal Parametters As String,
  296.                            ByVal IsCheckTagOperation As Boolean)
  297.  
  298.        If Me.CheckFileExist Then
  299.            FileExist(MP3_File)
  300.        End If
  301.  
  302.        With Process_For_Tag.StartInfo
  303.            .FileName = Me.mp3gain_location
  304.            .Arguments = Parametters
  305.        End With
  306.  
  307.        With Process_For_NonTag.StartInfo
  308.            .FileName = Me.mp3gain_location
  309.            .Arguments = Parametters
  310.        End With
  311.  
  312.        ' Reset Variables before relaize the operation.
  313.        InfoMessage = Nothing
  314.        ErrorMessage = Nothing
  315.        db = 0
  316.  
  317.        ' Check if file has APEv2 mp3gain tag or not,
  318.        ' before doing any other operation.
  319.        If IsCheckTagOperation Then
  320.  
  321.            Run_MP3Gain_For_Tag(Process_For_Tag, MP3_File, operation.Check_Tag, True)
  322.            Exit Sub ' If only would to check the tag then exit from this sub.
  323.  
  324.        Else ' Else, continue with the operation (Modify volume gain)...
  325.  
  326.            Select Case HasTag
  327.  
  328.                Case True
  329.                    Run_MP3Gain_For_Tag(Process_For_Tag, MP3_File, operation, False)
  330.  
  331.                Case False
  332.                    Run_MP3Gain_For_NonTag(Process_For_NonTag, MP3_File, operation)
  333.  
  334.            End Select ' HasTag
  335.  
  336.        End If ' IsCheckTagOperation
  337.  
  338.    End Sub
  339.  
  340.    ''' <summary>
  341.    ''' Runs mp3gain for files that already contains APEv2 mp3gain tag.
  342.    ''' </summary>
  343.    Private Sub Run_MP3Gain_For_Tag(ByVal p As Process,
  344.                                    ByVal MP3_File As String,
  345.                                    ByVal operation As Operation,
  346.                                    ByVal IsTagCheckOperation As Boolean)
  347.  
  348.        p.Start()
  349.        RaiseEvent_Started(p, MP3_File, operation)
  350.        p.WaitForExit()
  351.  
  352.        If IsTagCheckOperation Then
  353.            HasTag = CBool(p.StandardOutput.ReadToEnd.Trim.Split(Environment.NewLine).Count - 1)
  354.        End If
  355.  
  356.        ProgressArgs.Percent = 100
  357.        RaiseEvent Progress(p, ProgressArgs)
  358.  
  359.        SetMessages(p.StandardOutput.ReadToEnd())
  360.  
  361.        RaiseEvent_Exited(p,
  362.                          MP3_File,
  363.                          operation,
  364.                          If(IsTagCheckOperation, "File Has Tag?: " & CStr(HasTag), InfoMessage),
  365.                          ErrorMessage,
  366.                          db)
  367.  
  368.        ' p.Close()
  369.  
  370.    End Sub
  371.  
  372.    ''' <summary>
  373.    ''' Runs mp3gain for files that doesn't contains APEv2 mp3gain tag.
  374.    ''' </summary>
  375.    Private Sub Run_MP3Gain_For_NonTag(ByVal p As Process,
  376.                                       ByVal MP3_File As String,
  377.                                       ByVal operation As Operation)
  378.  
  379.        p.Start()
  380.        RaiseEvent_Started(p, MP3_File, operation)
  381.  
  382.        Do Until p.HasExited
  383.  
  384.            Try
  385.  
  386.                ProgressArgs.Percent = CInt(p.StandardError.ReadLine.Split("%").First.Trim)
  387.  
  388.                If ProgressArgs.Percent < 101 Then
  389.                    RaiseEvent Progress(p, ProgressArgs)
  390.                End If
  391.  
  392.            Catch
  393.            End Try
  394.  
  395.        Loop
  396.  
  397.        ProgressArgs.Percent = 100
  398.        RaiseEvent Progress(p, ProgressArgs)
  399.  
  400.        SetMessages(p.StandardOutput.ReadToEnd())
  401.  
  402.        RaiseEvent_Exited(p,
  403.                          MP3_File,
  404.                          operation,
  405.                          InfoMessage,
  406.                          ErrorMessage,
  407.                          db)
  408.  
  409.        ' p.Close()
  410.  
  411.    End Sub
  412.  
  413. #End Region
  414.  
  415. #Region " Miscellaneous Procedures "
  416.  
  417.    ''' <summary>
  418.    ''' Checks if a file exists.
  419.    ''' </summary>
  420.    Private Sub FileExist(ByVal File As String)
  421.  
  422.        If Not IO.File.Exists(File) Then
  423.            Throw New Exception(String.Format("File doesn't exist: ""{0}""", File))
  424.            ' MessageBox.Show(String.Format("File doesn't exist: ""{0}""", File), "mp3gain", MessageBoxButtons.OK, MessageBoxIcon.Error)
  425.        End If
  426.  
  427.    End Sub
  428.  
  429.    ''' <summary>
  430.    ''' Raises the Event Started
  431.    ''' </summary>
  432.    Private Sub RaiseEvent_Started(ByVal p As Process,
  433.                                   ByVal file As String,
  434.                                   ByVal operation As Operation)
  435.  
  436.        With StartedArgs
  437.            .File = file
  438.            .Operation = operation
  439.        End With
  440.  
  441.        RaiseEvent Started(p, StartedArgs)
  442.  
  443.    End Sub
  444.  
  445.    ''' <summary>
  446.    ''' Raises the Event Exited
  447.    ''' </summary>
  448.    Private Sub RaiseEvent_Exited(ByVal p As Process,
  449.                                  ByVal file As String,
  450.                                  ByVal operation As Operation,
  451.                                  ByVal InfoMessage As String,
  452.                                  ByVal ErrorMessage As String,
  453.                                  ByVal db As Integer)
  454.  
  455.        With ExitedArgs
  456.            .File = file
  457.            .Operation = operation
  458.            .InfoMessage = InfoMessage
  459.            .ErrorMessage = ErrorMessage
  460.            .db = db
  461.        End With
  462.  
  463.        RaiseEvent Exited(p, ExitedArgs)
  464.  
  465.    End Sub
  466.  
  467.    ''' <summary>
  468.    ''' Sets the InfoMessage, ErrorMessage and db variables.
  469.    ''' </summary>
  470.    Private Sub SetMessages(ByVal StandardOutput As String)
  471.  
  472.        Output = StandardOutput.
  473.                 Split(Environment.NewLine).
  474.                 Select(Function(line) line.Replace(Environment.NewLine, "").Trim).
  475.                 Where(Function(null) Not String.IsNullOrEmpty(null)).ToArray
  476.  
  477.        For Each line In Output
  478.  
  479.            Select Case True
  480.  
  481.                Case line.StartsWith("No changes")
  482.                    InfoMessage = "No volume gain changes are necessary."
  483.  
  484.                Case line.StartsWith("Applying")
  485.                    db = db_RegEx.Match(line).Groups(1).Value
  486.                    If String.IsNullOrEmpty(InfoMessage) Then
  487.                        InfoMessage = line
  488.                    End If
  489.  
  490.                Case line.StartsWith("Can't")
  491.                    ErrorMessage = line
  492.  
  493.            End Select
  494.  
  495.        Next line
  496.  
  497.    End Sub
  498.  
  499. #End Region
  500.  
  501. #Region " IDisposable "
  502.  
  503.      ''' <summary>
  504.      ''' Disposes the objects generated by this instance.
  505.      ''' </summary>
  506.      Public Sub Dispose() Implements IDisposable.Dispose
  507.          Dispose(True)
  508.          GC.SuppressFinalize(Me)
  509.      End Sub
  510.  
  511.      Protected Overridable Sub Dispose(IsDisposing As Boolean)
  512.  
  513.          Static IsBusy As Boolean ' To detect redundant calls.
  514.  
  515.          If Not IsBusy AndAlso IsDisposing Then
  516.  
  517.             Process_For_Tag.Dispose()
  518.         Process_For_NonTag.Dispose()
  519.  
  520.          End If
  521.  
  522.          IsBusy = True
  523.  
  524.      End Sub
  525.  
  526.  #End Region
  527.  
  528. End Class
  529.  
  530. #End Region
Páginas: 1 ... 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 [806] 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 ... 1254
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines