SoundPlayer in WPF

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 void BrowseButton_Click(object sender, RoutedEventArgs e)

{

    OpenFileDialog dlg = 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)

    {

        string selectedFileName = dlg.FileName;

        FileTextBox.Text = selectedFileName;

        MediaPlayer mp = new MediaPlayer();

        mp.Open(new Uri(selectedFileName, UriKind.Relative ));

        mp.Play();

    }

}

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:

using System.Windows.Forms;

 

Up Next
    Ebook Download
    View all
    Learn
    View all