Click here to Skip to main content
15,887,027 members
Articles / Multimedia / DirectX
Article

Simple VB.NET MIDI & Wave Play Class

Rate me:
Please Sign up or sign in to vote.
2.89/5 (7 votes)
7 Oct 2004 135.7K   24   16
MIDI & Wave Player for VB.NET.

Introduction

This is a simple class to play MIDI and Wave files with your VB.NET application.

Using the code

Add a new class file into your project and copy the code into it. Make a reference to DirectX7 COM-Object.

VB
Imports System
Imports DxVBLib

Public Class SoundPlayer

    ' Basic Wave and MIDI Player Class for VB.net 1.1
    ' Requires COM-Object : DirectX7 

    Private Declare Function mciSendString Lib "Winmm.dll" Alias "mciSendStringA" _
    (ByVal lpstrCommand As String, ByVal lpstrReturnString As String, _
    ByVal uReturnLength As Long, ByVal hwndCallback As Long) As Long
    
    Private File As String

    Private m_dx As New DirectX7
    Private m_ds As DirectSound

    Public Sub New(ByVal strFileName As String)

        Me.File = strFileName

    End Sub

    ' To show what file is selected (if needed)
    Public ReadOnly Property FileName() As String

        Get
            Return File
        End Get

    End Property

    Public Function PlaySound() As Boolean

        If InitAudio() = True Then
            If PlayFile() = True Then
                Return True
            Else
                Return False
            End If
        Else
            ' Audiohardware not found
            ' exit here
            Return False
        End If

    End Function

    Public Function StopSound() As Boolean

        StopFile()

    End Function

    Private Function PlayFile() As Boolean

        Dim lRet As Long

        Try
            StopFile()

            lRet = mciSendString("open " & Me.File & " alias track", "", 0, 0)
            lRet = mciSendString("play track", "", 0, 0)
            PlayFile = (lRet = 0)

        Catch ex As Exception
            Return False
        End Try

        Return True

    End Function

    Public Function CloseAudio()

        mciSendString("close all", 0, 0, 0)

    End Function

    Private Function StopFile() As Boolean

        Dim lRet As Long

        Try
            lRet = mciSendString("stop track", "", 0, 0)
            lRet = mciSendString("close track", "", 0, 0)
            Return True
        Catch ex As Exception
            Return False
        End Try

    End Function

    Private Function InitAudio() As Boolean

        m_ds = m_dx.DirectSoundCreate("")
        If Err.Number <> 0 Then
            Return False
        Else
            Return True
        End If

    End Function

End Class

In your application, play a sound like this:

VB
Dim Sound As New SoundPlayer(".\sound\testmidi.mid")
Sound.PlaySound()

or

VB
Sound.StopSound()

to stop playing.

Sound.FileName shows the filename given to the class on declare.

I didn't test it but I'm sure that it works with DX8 or DX9 too. And always remember: this code is for the beginners to show how to play MIDI and Wave files. The class plays each file once. No loop...

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
Shimmy Weitzhandler20-Jun-10 15:33
Shimmy Weitzhandler20-Jun-10 15:33 
GeneralMy vote of 1 Pin
Mike Trethowan8-Jun-09 12:38
Mike Trethowan8-Jun-09 12:38 
GeneralPlay File name with Chinese Characters Pin
serene joey25-Sep-08 17:33
serene joey25-Sep-08 17:33 
Generalhelp me please! Pin
taki3310-Jun-08 22:54
taki3310-Jun-08 22:54 
GeneralHelp!! Pin
nicieri20-Feb-07 14:25
nicieri20-Feb-07 14:25 
GeneralHelp with mci progress bar plzzzzz Pin
steve shafa18-Dec-06 6:43
steve shafa18-Dec-06 6:43 
Hi i am doing a mci music player in vb.net. I have done everything except a progress bar to skip song and a duration bar. How would I do this and what MCI strings would I use heres what i have done far


Private Paused As Boolean = False 'this is a class level variable

'Private close As Long

Private Declare Function mciGetErrorString Lib "winmm.dll" Alias "mciGetErrorStringA" (ByVal dwError As Long, ByVal lpstrBuffer As String, ByVal uLength As Long) As Long


<dllimport("winmm.dll", entrypoint:="mciSendStringA" )=""> _
Public Shared Function mciSendString(ByVal lpstrCommand As String, ByVal lpstrReturnString As String, ByVal uReturnLength As Integer, ByVal hwndCallback As Integer) As Integer
'Used to call MCI

End Function

Public Function PlayMCI(ByVal filename As String, Optional ByVal ShowMsg As Boolean = False) As Boolean

' close any previous commands that have opened the media
mciSendString("Close all", 0, 0, 0)
' and create the string which will open the new one

mciSendString("Open " & Chr(34) & filename & Chr(34) & " Type " & SoundFormat(filename) & _
" Alias Med", 0, 0, 0)


mciSendString("Close", 0, 0, 0)
mciSendString("Pause Med ", 0, 0, 0)

mciSendString("Open " & Chr(34) & filename & Chr(34) & " Alias Med style child parent " + PictureBox1.Handle.ToString, 0, 0, 0)

mciSendString("Play Med", 0, 0, 0)

' End If
End Function ' Play MCI

Private Function SoundFormat(ByVal FullPath As String) As String
Dim Sound As New FileInfo(FullPath)
Dim FileExt As String = Sound.Extension.ToLower

Select Case FileExt
Case ".wav"
Return "Waveaudio"
Case ".mid"
Return "Mpeg3"
Case ".mp3"
Return "MPEGVideo"
Case ".mpg"
Return "CDAudio"
Case ".wma"
Return "MPEGVideo"
Case ".mpeg"
Return "Windows Media Player"
Case Else
Return "NotSoundFile"
End Select
End Function ' SoundFormat
#Region " Windows Form Designer generated code "

Public Sub New()
MyBase.New()

'This call is required by the Windows Form Designer.
InitializeComponent()



#End Region

Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
mciSendString("close Med", 0&, 0, 0)


End Sub

Private Sub play_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim OpenFile As New OpenFileDialog


With OpenFile
.InitialDirectory = "G:\"
.Filter = "MP3 Files (*.mp3)/*.mp3/Wma files(*.wma)/*.wma/Wav Files(*.wav)/*.wav/Mpg Files (*.mpg) /*.mpg/flash Files (*.flvplayer) /*.flvplayer/All Files(*.*)/*.*"
'.Filter = "Mpg Files (*.mpg) /*.mpg"
.CheckFileExists = True

' Open the dialog
If .ShowDialog = DialogResult.OK Then



PlayMCI(.FileName)
'mul.wait = False
Label2.Text = .FileName


Timer1.Enabled = True


End If
End With
End Sub


Private Sub Stop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
mciSendString("Close all", 0, 0, 0)
End Sub

Private Sub TrackBar1_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrackBar1.Scroll
mciSendString("seek Med to " & TrackBar1.Value, 0&, 0, 0)
mciSendString("Play Med", 0, 0, 0)


TrackBar1.Minimum = 0
TrackBar1.Maximum = 24000
TrackBar1.SmallChange = 1000 'To make intervale of 1 second...
End Sub

Private Sub ProgressBar1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ProgressBar1.Click

End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick


End Sub
GeneralHelp !! ( also) Pin
totok_fr2-Dec-06 14:44
totok_fr2-Dec-06 14:44 
QuestionAny suggestion on how to record wav / mp3 files ? Pin
Parik Advani12-Jun-06 3:00
Parik Advani12-Jun-06 3:00 
GeneralHelp with setup project Pin
kche1289-Sep-05 17:55
kche1289-Sep-05 17:55 
GeneralHelp! Pin
Anonymous29-Jan-05 10:37
Anonymous29-Jan-05 10:37 
GeneralRe: Help! Pin
Anonymous20-Apr-05 23:53
Anonymous20-Apr-05 23:53 
GeneralPlaying files sequentially Pin
learner5413-Nov-04 10:00
learner5413-Nov-04 10:00 
GeneralRe: Playing files sequentially Pin
ycc7124-Jan-05 23:32
ycc7124-Jan-05 23:32 
Questionhow we know the midi have finised Pin
subandono18-Oct-04 17:22
subandono18-Oct-04 17:22 
AnswerRe: how we know the midi have finised Pin
EcoSys19-Oct-04 13:37
EcoSys19-Oct-04 13:37 
GeneralMCI Commands Pin
EcoSys11-Oct-04 2:07
EcoSys11-Oct-04 2:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.