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)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Código para reproducir notas musicales mediante midiOutShortMsg
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Código para reproducir notas musicales mediante midiOutShortMsg  (Leído 3,432 veces)
Lekim

Desconectado Desconectado

Mensajes: 268



Ver Perfil
Código para reproducir notas musicales mediante midiOutShortMsg
« en: 14 Junio 2016, 00:12 am »

Hola

Quiero compartir este programa que he desarrollado.

Se trata de un teclado musical, un piano que utiliza el parche Standard MIDI Patch Assignments del MIDI Manufacturers Association (MMA) con 128 sonidos de instrumentos diferentes.

Standard MIDI Patch Assignments


Permite tanto tocar con el ratón como con el teclado del ordenador.



Puedes descargarte el código aquí:

Musical_Keyboard.zip

*Elige el botón de la derecha, el que pone  'Descargar con el navegador'



Si lo prefieres puedes hacer simplemente un copia y pega en un nuevo proyecto 'Aplicación de Windows Form'

No necesitas crear controles, tan solo deja todo en blanco en el editor de código de Form1.vb, y pegas este código:

Código
  1. '//////////////////////////////
  2. '//    Date: 13/06/2016      //
  3. '//  Programmed by LEKIM     //
  4. '//////////////////////////////
  5.  
  6. Option Strict On
  7. Imports System.Runtime.InteropServices
  8. Imports System.Text
  9. Imports System.Security
  10.  
  11. Public Class Form1
  12.    Dim lblMuscKey(61) As Label
  13.    Dim lblInstruments(127) As Label
  14.    Dim lblOctave(5) As Label
  15.    Dim FlLayPanel As FlowLayoutPanel
  16.    Dim lblTitle As New Label
  17.    Dim ttip As New ToolTip
  18.    Dim numKeysBlack() As Integer = _
  19.        {2, 4, 7, 9, 11, 14, 16, 19, 21, 23, 26, 28, 31, _
  20.         33, 35, 38, 40, 43, 45, 47, 50, 52, 55, 57, 59}
  21.    Dim numKeysWhite() As Integer = _
  22.        {1, 3, 5, 6, 8, 10, 12, 13, 15, 17, 18, 20, 22, _
  23.         24, 25, 27, 29, 30, 32, 34, 36, 37, 39, 41, 42, _
  24.         44, 46, 48, 49, 51, 53, 54, 56, 58, 60, 61}
  25.    Dim hMidiOut As IntPtr
  26.    Dim intMsg As Integer
  27.    Dim Msg As NativeMethods.MidiMsg
  28.    Dim Octave As Byte = 1 'Octave from where begins the first key of the musical keyboard
  29.    Dim ListKeyPress As New List(Of Integer)
  30.    Dim VolumeKey As Byte = 127 'min=0; max=127
  31.    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  32.        CreateMusicalKeyBoard()
  33.        CreatePanelInstruments()
  34.        CreateOctaveButtons()
  35.        With lblTitle
  36.            .Text = "Standard MIDI Patch Assignments"
  37.            .BackColor = Color.Transparent
  38.            .ForeColor = Color.WhiteSmoke
  39.            .Font = New Font("Arial", 20, FontStyle.Bold)
  40.            .TextAlign = ContentAlignment.MiddleLeft
  41.            .Size = CType(New Point(470, 40), Drawing.Size)
  42.            .Location = New Point(5, 5)
  43.        End With
  44.  
  45.        With Me
  46.            .Controls.Add(lblTitle)
  47.            .KeyPreview = True
  48.            .BackColor = System.Drawing.Color.FromArgb(40, 40, 40)
  49.            .Size = CType(New Point(835, 440), Drawing.Size)
  50.            .Text = "Demo Musical Keyboard"
  51.            .MaximizeBox = False
  52.            .FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle
  53.            .StartPosition = FormStartPosition.CenterScreen
  54.            .SetBounds(CInt((Screen.PrimaryScreen.Bounds.Width - .Width) / 2),
  55.                       CInt((Screen.PrimaryScreen.Bounds.Height - .Height) / 2) - 50,
  56.                       .Width, .Height)
  57.        End With
  58.  
  59.        'Show a tooltip message
  60.        ttip.AutoPopDelay = 2000
  61.        ttip.InitialDelay = 1000
  62.        ttip.ReshowDelay = 500
  63.        For I As Integer = 1 To 5
  64.            ttip.SetToolTip(Me.lblOctave(I), "Octave")
  65.        Next
  66.  
  67.  
  68.        NativeMethods.midiOutOpen(hMidiOut, _
  69.                                  NativeMethods.MIDI_MAPPER, CType(0, IntPtr), _
  70.                                        CType(0, IntPtr), NativeMethods.CALLBACK_NULL)
  71.    End Sub
  72.    Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
  73.        If ListKeyPress.Contains(e.KeyCode) = True Then Exit Sub ' Key is already pressed
  74.        If Key(e.KeyCode) = 0 Then Exit Sub
  75.        PlayMusicalNote(CByte(Key(e.KeyCode)), VolumeKey, Octave)
  76.        ListKeyPress.Add(e.KeyCode)
  77.    End Sub
  78.    Private Sub Form1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp
  79.  
  80.        OffMusicalNote(CByte(Key(e.KeyCode)), Octave)
  81.        ListKeyPress.Remove(e.KeyCode)
  82.        Try
  83.            If numKeysWhite.Contains(Msg.Note) Then
  84.                lblMuscKey(Msg.Note).BackColor = Color.White
  85.            Else
  86.                lblMuscKey(Msg.Note).BackColor = Color.Black
  87.            End If
  88.        Catch ex As Exception
  89.        End Try
  90.  
  91.    End Sub
  92.  
  93. #Region "Octave Buttons"
  94.    Sub CreateOctaveButtons()
  95.        Dim pOct As New Point(30, 265)
  96.        Dim inc As Integer = 0
  97.        For I = 1 To 5
  98.            lblOctave(I) = New Label
  99.            With lblOctave(I)
  100.                .Text = CStr(I)
  101.                .Font = New Font("Arial", 10, FontStyle.Bold)
  102.                .Size = CType(New Point(20, 20), Drawing.Size)
  103.                .BorderStyle = BorderStyle.FixedSingle
  104.                .Location = New Point(pOct.X + inc, pOct.Y)
  105.                .ForeColor = System.Drawing.Color.FromArgb(120, 120, 120)
  106.                .BackColor = System.Drawing.Color.FromArgb(20, 20, 20)
  107.                .TextAlign = ContentAlignment.MiddleCenter
  108.                AddHandler .MouseDown, AddressOf lblOctave_MouseDown
  109.                AddHandler .MouseEnter, AddressOf lblOctave_MouseEnter
  110.                AddHandler .MouseLeave, AddressOf lblOctave_MouseLeave
  111.            End With
  112.            inc = inc + 19
  113.            Me.Controls.Add(lblOctave(I))
  114.        Next
  115.  
  116.        lblOctave(1).BackColor = System.Drawing.Color.FromArgb(150, 150, 150)
  117.        lblOctave(1).ForeColor = System.Drawing.Color.FromArgb(10, 10, 10)
  118.  
  119.    End Sub
  120.    Private Sub lblOctave_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
  121.        Dim Index As Integer = Array.IndexOf(lblOctave, sender)
  122.        For I As Integer = 1 To 5
  123.            lblOctave(I).BackColor = System.Drawing.Color.FromArgb(20, 20, 20)
  124.            lblOctave(I).ForeColor = System.Drawing.Color.FromArgb(120, 120, 120)
  125.        Next
  126.        lblOctave(Index).BackColor = System.Drawing.Color.FromArgb(150, 150, 150)
  127.        lblOctave(Index).ForeColor = System.Drawing.Color.FromArgb(10, 10, 10)
  128.  
  129.        Octave = CByte(Index)
  130.    End Sub
  131.    Private Sub lblOctave_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs)
  132.        Dim Index As Integer = Array.IndexOf(lblOctave, sender)
  133.        Cursor = Cursors.Hand
  134.    End Sub
  135.    Private Sub lblOctave_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs)
  136.        Dim Index As Integer = Array.IndexOf(lblOctave, sender)
  137.        Cursor = Cursors.Default
  138.    End Sub
  139. #End Region
  140.  
  141. #Region "Panel of Instruments"
  142.    ''' <summary>
  143.    ''' Create a panel of instruments
  144.    ''' </summary>
  145.    ''' <remarks></remarks>
  146.    Public Sub CreatePanelInstruments()
  147.        FlLayPanel = New FlowLayoutPanel
  148.        With FlLayPanel
  149.            .AutoScroll = True
  150.            .VerticalScroll.Visible = False
  151.            .BorderStyle = BorderStyle.FixedSingle
  152.            .Size = CType(New Point(808, 205), Drawing.Size)
  153.            .Location = New Point(5, 50)
  154.            .FlowDirection = FlowDirection.TopDown
  155.            .BackColor = System.Drawing.Color.FromArgb(10, 10, 10)
  156.        End With
  157.        Me.Controls.Add(FlLayPanel)
  158.  
  159.        For I As Integer = 0 To lblInstruments.Count - 1
  160.            lblInstruments(I) = New Label
  161.            With lblInstruments(I)
  162.                .Width = 155
  163.                .Font = New Font("Arial", 8, FontStyle.Bold)
  164.                .ForeColor = System.Drawing.Color.FromArgb(120, 120, 120)
  165.                .BorderStyle = BorderStyle.FixedSingle
  166.                .TextAlign = ContentAlignment.MiddleLeft
  167.  
  168.            End With
  169.            FlLayPanel.Controls.Add(lblInstruments(I))
  170.        Next (I)
  171.  
  172.        'Standard MIDI Patch Assignments
  173.        Dim strInstruments() As String = _
  174.            {"000 Acoustic grand piano", "001 Bright acoustic piano", "002 Electric grand piano", "003 Honky-tonk piano",
  175.             "004 Rhodes(piano)", "005 Chorused(piano)", "006 Harpsichord", "007 Clavinet", "008 Celesta",
  176.             "009 Glockenspiel", "010 Music(box)", "011 Vibraphone", "012 Marimba", "013 Xylophone", "014 Tubular(bells)",
  177.             "015 Dulcimer", "016 Hammond(organ)", "017 Percussive(organ)", "018 Rock(organ)", "019 Church(organ)",
  178.             "020 Reed(organ)", "021 Accordion", "022 Harmonica", "023 Tango(accordion)", "024 Acoustic guitar (nylon)",
  179.             "025 Acoustic(guitar(steel))", "026 Electric(guitar(jazz))", "027 Electric(guitar(clean))",
  180.             "028 Electric(guitar(muted))", "029 Overdriven(guitar)", "030 Distortion(guitar)", "031 Guitar(harmonics)",
  181.             "032 Acoustic bass", "033 Electric bass (finger)", "034 Electric bass (pick)", "035 Fretless bass",
  182.             "036 Slap bass 1", "037 Slap bass 2", "038 Synth bass 1", "039 Synth bass 2", "040 Violin",
  183.             "041 Viola", "042 Cello", "043 Contrabass", "044 Tremolo strings", "045 Pizzicato strings", "046 Orchestral harp",
  184.             "047 Timpani", "048 String ensemble 1", "049 String ensemble 2", "050 Synth.strings(1)", "051 Synth.strings(2)",
  185.             "052 Choir(Aahs)", "053 Voice(Oohs)", "054 Synth(voice)", "055 Orchestra(hit)", "056 Trumpet", "057 Trombone",
  186.             "058 Tuba", "059 Muted(trumpet)", "060 French(horn)", "061 Brass(section)", "062 Synth.brass(1)",
  187.             "063 Synth.brass(2)", "064 Soprano sax", "065 Alto sax", "066 Tenor sax", "067 Baritone sax", "068 Oboe",
  188.             "069 English horn", "070 Bassoon", "071 Clarinet", "072 Piccolo", "073 Flute", "074 Recorder",
  189.             "075 Pan flute", "076 Bottle blow", "077 Shakuhachi", "078 Whistle", "079 Ocarina", "080 Lead 1 (square)",
  190.             "081 Lead 2 (sawtooth)", "082 Lead 3 (calliope lead)", "083 Lead 4 (chiff lead)", "084 Lead 5 (charang)",
  191.             "085 Lead 6 (voice)", "086 Lead 7 (fifths)", "087 Lead 8 (brass + lead)", "088 Pad 1 (new age)",
  192.             "089 Pad 2 (warm)", "090 Pad 3 (polysynth)", "091 Pad 4 (choir)", "092 Pad 5 (bowed)", "093 Pad 6 (metallic)",
  193.             "094 Pad 7 (halo)", "095 Pad 8 (sweep)", "096 FX 1 (rain)", "097 FX 2 (soundtrack)", "098 FX 3 (crystal)",
  194.             "099 FX 4 (atmosphere)", "100 FX 5 (brightness)", "101 FX 6 (goblins)", "102 FX 7 (echoes)", "103 FX 8 (sci-fi)",
  195.             "104 Sitar", "105 Banjo", "106 Shamisen", "107 Koto", "108 Kalimba", "119 Bagpipe", "110 Fiddle", "111 Shanai2",
  196.             "112 Tinkle Bell", "113 Agogo", "114 Steel Drums", "115 Woodblock", "116 Taiko Drum", "117 Melodic Tom",
  197.             "118 Synth Drum2", "119 Reverse Cymbal", "120 Guitar fret noise", "121 Breath noise", "122 Seashore",
  198.             "123 Bird tweet", "124 Telephone ring", "125 Helicopter", "126 Applause", "127 Gunshot"}
  199.  
  200.        For I = 0 To 127
  201.            lblInstruments(I).Text = strInstruments(I)
  202.        Next
  203.        For I As Integer = 0 To lblInstruments.Count - 1
  204.            AddHandler lblInstruments(I).MouseDown, AddressOf lblInstruments_MouseDown
  205.        Next
  206.  
  207.    End Sub
  208.    Private Sub lblInstruments_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
  209.        Dim Index As Integer = Array.IndexOf(lblInstruments, sender)
  210.        For I = 0 To lblInstruments.Count - 1
  211.            lblInstruments(I).BackColor = Color.Transparent
  212.            lblInstruments(I).ForeColor = System.Drawing.Color.FromArgb(120, 120, 120)
  213.  
  214.        Next
  215.        lblInstruments(Index).BackColor = System.Drawing.Color.FromArgb(150, 150, 150)
  216.        lblInstruments(Index).ForeColor = System.Drawing.Color.FromArgb(0, 0, 0)
  217.        ChangeInstrument(Index)
  218.    End Sub
  219. #End Region
  220.  
  221. #Region "Musical Keyboard"
  222.    ''' <summary>
  223.    ''' Create the keys of the musical keyboard
  224.    ''' </summary>
  225.    ''' <remarks></remarks>
  226.    Sub CreateMusicalKeyBoard()
  227.        Dim wKeyWhite As New Point(22, 80)
  228.        Dim wKeyBlack As New Point(12, 50)
  229.        Dim PosKeyWhite As New Point(30, 300)
  230.        Dim PosKeyBlack As New Point(25, 300)
  231.  
  232.        For Index As Integer = 1 To lblMuscKey.Count - 1
  233.            lblMuscKey(Index) = New Label
  234.            With lblMuscKey(Index)
  235.                .BorderStyle = BorderStyle.FixedSingle
  236.                Dim incWhiteKeyPosX As Integer
  237.                'White keys
  238.                If numKeysWhite.Contains(Index) Then
  239.                    .Size = New Size(wKeyWhite)
  240.                    .BackColor = Color.White
  241.                    .Location = _
  242.                        New Point(PosKeyWhite.X + incWhiteKeyPosX, PosKeyWhite.Y)
  243.                    incWhiteKeyPosX = incWhiteKeyPosX + 21
  244.                    .SendToBack() 'send to back
  245.                End If
  246.                'Black keys
  247.                If numKeysBlack.Contains(Index) Then
  248.                    .BackColor = Color.Black
  249.                    .Size = New Size(wKeyBlack)
  250.                    .Location = _
  251.                        New Point(PosKeyBlack.X + incWhiteKeyPosX, PosKeyBlack.Y)
  252.                End If
  253.                Me.Controls.Add(lblMuscKey(Index))
  254.                If numKeysBlack.Contains(Index) Then
  255.                    lblMuscKey(Index).BringToFront()
  256.                End If
  257.  
  258.                AddHandler .MouseDown, AddressOf lblMuscKey_MouseDown
  259.                AddHandler .MouseUp, AddressOf lblMuscKey_MouseUp
  260.                AddHandler .MouseMove, AddressOf lblMuscKey_MouseMove
  261.                AddHandler .MouseLeave, AddressOf lblMuscKey_MouseLeave
  262.            End With
  263.  
  264.        Next
  265.  
  266.  
  267.    End Sub
  268.    Private Sub lblMuscKey_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
  269.        Dim Index As Integer = Array.IndexOf(lblMuscKey, sender)
  270.        lblMuscKey(Index).BackColor = Color.Gray 'Change color of the key
  271.        PlayMusicalNote(CByte(Index), VolumeKey, Octave)
  272.    End Sub
  273.    Private Sub lblMuscKey_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
  274.        Dim Index As Integer = Array.IndexOf(lblMuscKey, sender)
  275.        If numKeysWhite.Contains(Index) Then
  276.            lblMuscKey(Index).BackColor = Color.White 'Change color of the key
  277.        Else
  278.            lblMuscKey(Index).BackColor = Color.Black 'Change color of the key
  279.        End If
  280.  
  281.        OffMusicalNote(Index, Octave)
  282.    End Sub
  283.    Private Sub lblMuscKey_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
  284.        Dim Index As Integer = Array.IndexOf(lblMuscKey, sender)
  285.        Dim mPoint As New Point(Me.PointToClient(Cursor.Position).X, Me.PointToClient(Cursor.Position).Y)
  286.        Dim X As Integer = mPoint.X
  287.        Cursor = Cursors.Hand
  288.        If X < CInt(lblMuscKey(Index).Left) Or
  289.            X > (CInt(lblMuscKey(Index).Left) + _
  290.                 CInt(lblMuscKey(Index).Width)) Then
  291.            EventoUp()
  292.            EventoDown()
  293.        End If
  294.  
  295.    End Sub
  296.    Private Sub lblMuscKey_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs)
  297.        Cursor = Cursors.Default
  298.    End Sub
  299. #End Region
  300.  
  301.  
  302. #Region "Play Sounds Functions"
  303.    ''' <summary>
  304.    ''' Play a musical note
  305.    ''' </summary>
  306.    ''' <param name="Note">Value of musical note</param>  
  307.    ''' <param name="Volume">Volume musical note</param>
  308.    ''' <param name="bOct">Octave</param>
  309.    ''' <returns></returns>
  310.    Public Function PlayMusicalNote(ByVal Note As Integer, ByVal Volume As Byte, ByVal bOct As Byte) As Boolean
  311.        Note += 23 + (12 * bOct)
  312.        intMsg = CInt(Volume * Convert.ToInt32(CStr(10000), 16) _
  313. + Note * Convert.ToInt32(CStr(100), 16) + NativeMethods.KeyOn)
  314.  
  315.        Return CBool(NativeMethods.midiOutShortMsg(hMidiOut, intMsg))
  316.    End Function
  317.    ''' <summary>
  318.    ''' Off a musical note
  319.    ''' </summary>
  320.    ''' <param name="Note">Value of musical note</param>
  321.    ''' <param name="bOct">Octave</param>
  322.    ''' <returns></returns>
  323.    ''' <remarks></remarks>
  324.    Public Function OffMusicalNote(ByVal Note As Integer, ByVal bOct As Integer) As Boolean
  325.        Note += 23 + (12 * bOct)
  326.        intMsg = Note * Convert.ToInt32(CStr(100), 16) + NativeMethods.KeyOff
  327.        Return CBool(NativeMethods.midiOutShortMsg(hMidiOut, intMsg))
  328.    End Function
  329.    ''' <summary>
  330.    ''' Change the instrument
  331.    ''' </summary>
  332.    ''' <param name="instCode"></param>
  333.    ''' <returns></returns>
  334.    ''' <remarks></remarks>
  335.    Public Function ChangeInstrument(ByVal instCode As Integer) As Boolean
  336.        intMsg = instCode * Convert.ToInt32(CStr(100), 16) + NativeMethods.Instruments
  337.        Return CBool(NativeMethods.midiOutShortMsg(hMidiOut, intMsg))
  338.        Return Nothing
  339.    End Function
  340. #End Region
  341. #Region "Computer keyboard keys"
  342.    ''' <summary>
  343.    ''' Assigning Computer keyboard keys
  344.    ''' </summary>
  345.    ''' <param name="keycode"></param>
  346.    ''' <returns></returns>
  347.    ''' <remarks></remarks>
  348.    Public Function Key(ByVal keycode As Integer) As Integer
  349.        Dim BlackHalfKey() As Keys = {Keys.W, Keys.E, Keys.T, Keys.Y, Keys.U}
  350.        Dim WhiteHalfKey() As Keys = {Keys.A, Keys.S, Keys.D, Keys.F, Keys.G, Keys.H, Keys.J, Keys.K}
  351.        Dim BassKey() As Keys = {Keys.Z, Keys.X, Keys.C, Keys.V, Keys.B, Keys.N, Keys.M, Keys.Oemcomma}
  352.        Dim AltoKey() As Keys = {Keys.D1, Keys.D2, Keys.D3, Keys.D4, Keys.D5, Keys.D6, Keys.D7, Keys.D8}
  353.  
  354.        If BlackHalfKey.Contains(CType(keycode, Keys)) Or _
  355.            WhiteHalfKey.Contains(CType(keycode, Keys)) Or _
  356.            BassKey.Contains(CType(keycode, Keys)) Or _
  357.             AltoKey.Contains(CType(keycode, Keys)) Then
  358.            For I As Integer = 10 To 14
  359.                If keycode = BlackHalfKey(I - 10) Then Msg.Note = CByte(numKeysBlack(I))
  360.            Next
  361.  
  362.            For I As Integer = 14 To 21
  363.                If keycode = WhiteHalfKey(I - 14) Then Msg.Note = CByte(numKeysWhite(I))
  364.            Next
  365.  
  366.            For I As Integer = 0 To 7
  367.                If keycode = BassKey(I) Then Msg.Note = CByte(numKeysWhite(I))
  368.            Next
  369.            For I As Integer = 28 To 35
  370.                If keycode = AltoKey(I - 28) Then Msg.Note = CByte(numKeysWhite(I))
  371.            Next
  372.  
  373.            lblMuscKey(Msg.Note).BackColor = Color.Gray
  374.  
  375.            Return Msg.Note
  376.        Else
  377.            Return 0
  378.        End If
  379.  
  380.    End Function
  381. #End Region
  382. End Class
  383.  
  384. Module MouseEvents
  385.    ''' <summary>
  386.    ''' Simulate MouseDown the left mouse button
  387.    ''' </summary>
  388.    ''' <remarks></remarks>
  389.    Public Sub EventoDown()
  390.        NativeMethods.mouse_event(NativeMethods.MouseEventFlags.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
  391.    End Sub
  392.    ''' <summary>
  393.    ''' Simulate MouseUp the left mouse button
  394.    ''' </summary>
  395.    ''' <remarks></remarks>
  396.    Public Sub EventoUp()
  397.        NativeMethods.mouse_event(NativeMethods.MouseEventFlags.MOUSEEVENTF_MIDDLEUP, 0, 0, 0, 0)
  398.    End Sub
  399.  
  400. End Module
  401.  
  402. <SuppressUnmanagedCodeSecurity()>
  403. Friend NotInheritable Class NativeMethods
  404.    Inherits Attribute
  405.    Private Sub New()
  406.    End Sub
  407.  
  408. #Region "API MIDI message"
  409.    <DllImport("winmm.dll")>
  410.    Public Shared Function midiOutOpen(ByRef lphMidiOut As IntPtr,
  411.                                       ByVal uDeviceID As Integer,
  412.                                       ByVal dwCallback As IntPtr,
  413.                                       ByVal dwInstance As IntPtr,
  414.                                       ByVal dwFlags As UInteger) As UInteger
  415.    End Function
  416.    <DllImport("winmm.dll")>
  417.    Public Shared Function midiOutShortMsg(ByVal hMidiOut As IntPtr,
  418.                                           ByVal dwMsg As Integer) As UInteger
  419.    End Function
  420.  
  421.    <DllImport("winmm.dll")>
  422.    Public Shared Function midiOutClose(ByVal hMidiOut As IntPtr) As Integer
  423.    End Function
  424.  
  425.    <StructLayout(LayoutKind.Auto)> _
  426.    Public Structure MidiMsg
  427.        Dim status As Byte
  428.        Dim Note As Byte
  429.        Dim Volume As Byte
  430.        Dim Data3 As Byte
  431.    End Structure
  432.    Public Const MIDI_MAPPER As Int32 = -1
  433.    Public Const CALLBACK_NULL = &H0
  434.    Public Const KeyOn As Integer = &H90
  435.    Public Const KeyOff As Integer = &H80
  436.    Public Const Instruments As Integer = &HC0
  437. #End Region
  438.  
  439. #Region "API Mouse Events"
  440.  
  441.  
  442.    <DllImport("user32.dll", CharSet:=CharSet.Auto)> _
  443.    Friend Shared Sub mouse_event(ByVal dwFlags As UInteger, _
  444.                                   ByVal dx As UInteger, _
  445.                                   ByVal dy As UInteger, _
  446.                                   ByVal dwData As UInteger, _
  447.                                   ByVal dwExtraInfo As Integer)
  448.    End Sub
  449.  
  450.    <Flags()> _
  451.    Public Enum MouseEventFlags As UInteger
  452.        MOUSEEVENTF_ABSOLUTE = &H8000
  453.        MOUSEEVENTF_LEFTDOWN = &H2
  454.        MOUSEEVENTF_LEFTUP = &H4
  455.        MOUSEEVENTF_MIDDLEDOWN = &H20
  456.        MOUSEEVENTF_MIDDLEUP = &H40
  457.        MOUSEEVENTF_MOVE = &H1
  458.        MOUSEEVENTF_RIGHTDOWN = &H8
  459.        MOUSEEVENTF_RIGHTUP = &H10
  460.        MOUSEEVENTF_XDOWN = &H80
  461.        MOUSEEVENTF_XUP = &H100
  462.        MOUSEEVENTF_WHEEL = &H800
  463.        MOUSEEVENTF_HWHEEL = &H1000
  464.    End Enum
  465.  
  466. #End Region
  467.  
  468.  
  469. End Class
  470.  


CÓDIGO BÁSICO PARA REPRODUCIR SONIDOS MIDI

Crea un Button, y pegas esto. Al pulsar el botón se escucha un sonido C2 (Do 2ª escala), que su valor es 47.


Código
  1.  
  2. Option Strict On
  3. Imports System.Runtime.InteropServices
  4. Imports System.Security
  5.  
  6. Public Class Form1
  7.    Dim hMidiOut As IntPtr
  8.    Dim intMsg As Integer
  9.    Dim msg As New NativeMethods.MidiMsg
  10.  
  11.    Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
  12.        'Cierra los mensajes midi
  13.        NativeMethods.midiOutClose(hMidiOut)
  14.    End Sub
  15.    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  16.        'Abre los mensajes midi
  17.        NativeMethods.midiOutOpen(hMidiOut, NativeMethods.MIDI_MAPPER,
  18.                         CType(0, IntPtr), CType(0, IntPtr),
  19.                         NativeMethods.CALLBACK_NULL)
  20.  
  21.        'Cambiar instrumento
  22.        Dim MyInstr As Integer = 1 'min:0 (piano) ; max:127 (Gunshot)
  23.        intMsg = MyInstr * Convert.ToInt32(CStr(100), 16) + NativeMethods.Instruments
  24.        NativeMethods.midiOutShortMsg(hMidiOut, intMsg)
  25.    End Sub
  26.  
  27.    Private Sub Button1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Button1.MouseDown
  28.        'Reproduce un sonido los mensajes midi
  29.        msg.status = NativeMethods.KeyOn
  30.        msg.Volume = 127
  31.        msg.Note = 47 '<---Sonido
  32.        intMsg = msg.Volume * Convert.ToInt32(CStr(10000), 16) + _
  33.            msg.Note * Convert.ToInt32(CStr(100), 16) + _
  34.            msg.status
  35.        NativeMethods.midiOutShortMsg(hMidiOut, intMsg)
  36.    End Sub
  37.  
  38.    Private Sub Button1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Button1.MouseUp
  39.        'Apaga el sonido al soltar el botón
  40.        '**El sonido debe ser el mismo que el que se quiere apagar
  41.        msg.status = NativeMethods.KeyOff
  42.        msg.Volume = 0
  43.        msg.Data3 = 0
  44.        msg.Note = 47 '<---Sonido
  45.        intMsg = msg.Volume * Convert.ToInt32(CStr(10000), 16) _
  46.            + msg.Note * Convert.ToInt32(CStr(100), 16) + _
  47.            msg.status
  48.        NativeMethods.midiOutShortMsg(hMidiOut, intMsg)
  49.    End Sub
  50. End Class
  51.  
  52.  
  53.  
  54. <SuppressUnmanagedCodeSecurity()>
  55. Friend NotInheritable Class NativeMethods
  56.    Inherits Attribute
  57.    Private Sub New()
  58.    End Sub
  59.  
  60. #Region "API MIDI message"
  61.    <DllImport("winmm.dll")>
  62.    Public Shared Function midiOutOpen(ByRef lphMidiOut As IntPtr,
  63.                                       ByVal uDeviceID As Integer,
  64.                                       ByVal dwCallback As IntPtr,
  65.                                       ByVal dwInstance As IntPtr,
  66.                                       ByVal dwFlags As UInteger) As UInteger
  67.    End Function
  68.    <DllImport("winmm.dll")>
  69.    Public Shared Function midiOutShortMsg(ByVal hMidiOut As IntPtr,
  70.                                           ByVal dwMsg As Integer) As UInteger
  71.    End Function
  72.  
  73.    <DllImport("winmm.dll")>
  74.    Public Shared Function midiOutClose(ByVal hMidiOut As IntPtr) As Integer
  75.    End Function
  76.  
  77.    <StructLayout(LayoutKind.Auto)> _
  78.    Public Structure MidiMsg
  79.        Dim status As Byte
  80.        Dim Note As Byte
  81.        Dim Volume As Byte
  82.        Dim Data3 As Byte
  83.    End Structure
  84.    Public Const MIDI_MAPPER As Int32 = -1
  85.    Public Const CALLBACK_NULL = &H0
  86.    Public Const KeyOn As Integer = &H90
  87.    Public Const KeyOff As Integer = &H80
  88.    Public Const Instruments As Integer = &HC0
  89. #End Region
  90.  
  91. End Class
  92.  
  93.  

Espero que disfrutéis del programa.

No soy un programador  experto así que supongo que los más avispados veréis cosas corregibles.

Me he visto obligado a usar APIs. He estado buscando la forma de no tener que usarlo y usar puro código .NET, pero no lo he conseguido. A no ser que use mi propia biblioteca MIDI de sonidos.

[DESLIZANDO EL CURSOR]
He preguntado en varios sitios incluido aquí como crear el efecto de arrastrar el dedo por las teclas de un piano usando el puntero del ratón y con puro código NET. Pero no he tenido éxito, por ahora.

Como alternativa, de nuevo me he visto obligado a usar llamada API. La razón es que cuando pulsas una tecla del piano y mantienes pulsado el botón izquierdo al pasar a otra tecla se mantiene el evento de la tecla inicial ignorando por completo el hecho de que el puntero se haya en una nueva tecla. Con la imposibilidad de usar MouseEnter, ya que el que trabaja es el evento MouseEnter de la primera tecla. Usando Mouse_Event emulo la acción de soltar el botón, aunque en realidad aun lo tenga pulsado justo al entrar en la otra tecla. De nuevo emulo el evento de pulsar y la nueva tecla captura el evento. Es fácil conseguirlo con elementos que no forma parte de una matriz, pero se complica al usar un array de controles. Por esta razón he tenido que usar Mouse_Event.

S2s






« Última modificación: 25 Septiembre 2020, 23:48 pm por Lekim » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.810



Ver Perfil
Re: Disfruta tocando el Piano con este programa
« Respuesta #1 en: 14 Junio 2016, 23:30 pm »

Hola.

Antes de nada: Gracias por compartir.

Con intención de que puedas mejorar el código que has compartido, te digo lo siguiente:

En el primer código cometiste una errata sin importancia, pero todo hay que mencionarlo, tienes declarado un método que se llama "ConstruyeTeclado",
eso lo descubrí observando las asociaciones de eventos (AddHandler ...), los cuales me he dado cuenta de que no las desasocias en ningún momento (RemoveHandler ...), lo cual en un principio no es un problema real, ya que solo los asocias una única vez durante el tiempo de vida de la aplicación, pero para prevenir futuros despistes que causen residuos sin liberar, convendría añadir las respectivas desasociaciones al inicio de los correspondientes métodos donde creas las asociaciones de eventos.

No he analizado mucho más el primer código, pero he visto que recurres a la función mouse_event de la WinAPI para sintetizar el botón izquierda y el del centro, ¿por qué motivo?, parece ser una metodología sustituible por código administrado, por ende optimizable, (o tal vez no) pero sin conocer el motivo no diré nada más por el momento.



Por último, me gustaría aconsejarte unas optimizaciones de diseño, solo son unos pequeños consejos que puedes aplicar u obviar (ya que no afectarán al funcionamiento del código):

1. Une las definiciones Win32 del módulo modEventMouse con la class ApiMidimessage (en la class, NO en el módulo).
De esta manera habrás separado el código administrado, del no administrado, compactándolo en un único lugar o class.

2. Asigna un nombre más convencional o estándar a la class modEventMouse, como por ejemplo SafeNativeMethods.
¿Por qué?, realmente no es por nada más que por seguir los estándares de nomenclatura de miembros y convenciones de uso.
Puedes leer más acerca de ello en la MSDN: https://msdn.microsoft.com/en-us/library/ms182161.aspx

3. Define un constructor por defecto y con visibilidad privada (Private Sub New() End Sub), para prevenir instanciar la class ApiMidimessage por error.

4. Asígnale el atributo SuppressUnmanagedCodeSecurity en esas funciones Win32 que has definido (o bien puedes asignarle el atributo a la class, y afectará a todos los miembros que contenga. ),
esto servirá para optimizar el rendimiento de las llamadas a esos métodos ...aunque para ser sinceros, en tu código practicamente no habrá diferencia al hacerlo (en el buen sentido).
Te recomiendo leer la sección 'Remarks' de este artículo de la MSDN: https://msdn.microsoft.com/en-us/library/system.security.suppressunmanagedcodesecurityattribute%28v=vs.110%29.aspx

5. Elimina el módulo.
Bueno, mejor dicho: Convierte el módulo en una clase no instanciable (leer el consejo nº3) dejando solo los wrappers EventoDown y EventoUp (el resto deberías haberlo movido a la class ApiMidimessage si aplicaste el consejo), y asígnale a esos wrappers una visibilidad global mediante el keyword Shared (Public Shared Sub EventoDown(...)).

6. No uses el keyword Call, ¡jamás!. No necesitas hacerlo, tampoco se recomiendo hacerlo, y aparte, está mal visto hacerlo, ya que es sinónimo de un acercamiento a las costumbres de VB6.
Cita de: MSDN
You can use the Call keyword when you call a procedure. For most procedure calls, you aren’t required to use this keyword.

You typically use the Call keyword when the called expression doesn’t start with an identifier. Use of the Call keyword for other uses isn’t recommended.


If the procedure returns a value, the Call statement discards it.
( https://msdn.microsoft.com/en-us/library/sxz296wz.aspx )

Si lo que intentas es descartar/ignorar el valor de retorno de la función mouse_event, entonces en lugar de ignorarlo, contrólalo, y así mejoras la calidad de control de errores del código.

Saludos


« Última modificación: 14 Junio 2016, 23:49 pm por Eleкtro » En línea

Lekim

Desconectado Desconectado

Mensajes: 268



Ver Perfil
Re: Disfruta tocando el Piano con este programa
« Respuesta #2 en: 14 Junio 2016, 23:57 pm »

Hola

Gracias por los consejos, muy buenos. La verdad es que esas cosas me hace falta saberlas, para que el código sea profesional, ya que yo he aprendido de forma autodidacta y lo pongo todo de cualquier manera aunque he mejorado. Además que el 80% de lo que se lo he aprendido aquí y con la MSDN, porque no he cogido un libro de NET en la vida. Si en su día de VB6 y algunos aún los conservo.

En el primer código cometiste una errata sin importancia, pero todo hay que mencionarlo, tienes declarado un método que se llama "ConstruyeTeclado",

 :xD
Bueno, yo quería ponerlo todo en inglés, pero eso se me pasó y encima con errata.
Ya lo he corregido.

La idea es mostrar una forma de crear sonidos sin necesidad de incrustar archivos de sonido a nuestro programa y que no fuera tampoco el típico Beep, que se escucha a través del altavoz interno.

Por cierto que curiosamente creo que de todos los sonidos no está el sonido "pulse" que creo que es así como se llama a sonido que produce  el Beep.

S2s




6. No uses el keyword Call, ¡jamás!. No necesitas hacerlo, tampoco se recomiendo hacerlo, y aparte, está mal visto hacerlo, ya que es sinónimo de un acercamiento a las costumbres de VB6.

Corregido


Creo que he corregido más o menos todo.  Gracias de nuevo.

Lo del mouse_event estoy en ello, casi está, pero me voy a dormir ::)
« Última modificación: 15 Junio 2016, 01:30 am por Lekim » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Software de vídeo para crear videoclips musicales
Multimedia
francis_knoxville 1 2,096 Último mensaje 28 Octubre 2007, 17:05 pm
por robertt_23
Codigo para reproducir videos?
.NET (C#, VB.NET, ASP)
_CrisiS_ 2 4,518 Último mensaje 18 Diciembre 2010, 20:03 pm
por Shell Root
Clave Wpa mediante codigo PIN
Wireless en Linux
ps3ps3ps3 1 2,027 Último mensaje 9 Julio 2013, 19:21 pm
por sanson
NO ME FUNCIONA EL CODIGO EN EL BLOC DE NOTAS JQUERY
Desarrollo Web
kasail 2 1,899 Último mensaje 14 Enero 2014, 22:22 pm
por kasail
Codigo avanzado para reproducir videos en tu Web.
Desarrollo Web
hackmastter 8 4,147 Último mensaje 28 Febrero 2015, 19:53 pm
por Usuario Invitado
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines