SoundPlayer in WPF

The code snippet in this article shows how to play sounds in WPF.
  • 2678
Download Files:
 

WPF uses Win32 or Windows Forms SoundPlayer and MediaPlayer controls to play sounds. The following code snippet and attached source code shows how to use it in WPF.

Private Sub BrowseButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim dlg As OpenFileDialog = New OpenFileDialog()
        dlg.InitialDirectory = "c:\\"
        dlg.Filter = "Sound files (*.wav)|*.wav|All Files (*.*)|*.*"
        dlg.FilterIndex = 2
        dlg.RestoreDirectory = True

         If dlg.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
            Dim selectedFileName As String = dlg.FileName

            FileTextBox.Text = selectedFileName
            Dim mp As MediaPlayer = New MediaPlayer()
            mp.Open(New Uri(selectedFileName, UriKind.Relative))
            mp.Play()
        End If
    End Sub

Note: By default a WPF application does not have reference to the System.Windows.Forms namespace and assembly. You need to add references to the System.Windows.Forms.dll and also import the namespace by adding the following line of code to your class:

Imports System.Windows.Forms

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.